diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..5fe6eaef67 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,5 @@ +Please delete this text, and add a link to the Jira issue solved by this PR; +see https://hibernate.atlassian.net/browse/HBX. + +Remember to prepend the title of this PR, as well as all commit messages, +with the key of the Jira issue (`HBX-`). diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..2bd7143061 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,17 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "monthly" + groups: + workflow-actions: + patterns: + - "*" + allow: + - dependency-name: "actions/*" diff --git a/.github/hibernate-github-bot.yml b/.github/hibernate-github-bot.yml new file mode 100644 index 0000000000..01c56ba41d --- /dev/null +++ b/.github/hibernate-github-bot.yml @@ -0,0 +1,3 @@ +--- +jira: + projectKey: "HBX" diff --git a/.github/workflows/build_test.yml b/.github/workflows/build_test.yml new file mode 100644 index 0000000000..3076dfeeab --- /dev/null +++ b/.github/workflows/build_test.yml @@ -0,0 +1,26 @@ +name: Build and Test + +on: + pull_request + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout PR Branch + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + + - name: Setup Java 8 + uses: actions/setup-java@3a4f6e1af504cf6a31855fa899c6aa5355ba6c12 # v4.7.0 + with: + java-version: 8 + distribution: temurin + + - name: Build and Test + uses: GabrielBB/xvfb-action@b706e4e27b14669b486812790492dc50ca16b465 # v1.7 + with: + run: mvn clean install diff --git a/.gitignore b/.gitignore index 303f952212..ab7680cf6f 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ reverseoutput .settings .DS_Store .idea +.java-version *.iml diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000000..7967f30dd1 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..f5b763a229 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +wrapperVersion=3.3.2 +distributionType=bin +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar diff --git a/.release/.gitignore b/.release/.gitignore new file mode 100644 index 0000000000..cdd9a17d6b --- /dev/null +++ b/.release/.gitignore @@ -0,0 +1,3 @@ +# The folder into which we checkout our release scripts into +* +!.gitignore \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000..2682aaf9ce --- /dev/null +++ b/README.md @@ -0,0 +1,40 @@ + + +[![Hibernate](https://static.jboss.org/hibernate/images/hibernate_200x150.png)](https://tools.hibernate.org) + +# Hibernate Tools - Tooling for your Hibernate Projects + +Working with Hibernate is very easy and developers enjoy using the APIs and the query language. Even creating mapping metadata is not an overly complex task once you've mastered the basics. Hibernate Tools makes working with Hibernate or JPA even more pleasant. + +## Project Contents + +Hibernate Tools is developed under the form of a hierarchical multi module Maven project. This parent module contains the following child modules: + +* [**main:**](./main) +This module contains the base tools to reverse engineer Hibernate artifacts from an existing database as well as a number of Ant tasks that use these tools and can be used in Ant build script to generate Hibernate and JPA artifacts. +* [**hibernate-tools-maven**:](./maven-plugin) +This module uses the tools defined in the main module to create some Maven mojos that bring the reverse engineering power to your Maven build. +* [**hibernate-tools-test**:](./test) +The test module is a multi module in itself that contains tests targeting different databases as well as no database tests. + +## Contributing + +If you run into errors, have ideas on how to improve the project or if you just want to collaborate, checkout the [contribution guide](./contribute.md). \ No newline at end of file diff --git a/ci/release/Jenkinsfile b/ci/release/Jenkinsfile new file mode 100644 index 0000000000..c41042dea7 --- /dev/null +++ b/ci/release/Jenkinsfile @@ -0,0 +1,119 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2016-2024 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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. + */ +@Library('hibernate-jenkins-pipeline-helpers') _ + +import org.hibernate.jenkins.pipeline.helpers.version.Version + +pipeline { + agent { + label 'Release' + } + tools { + maven 'Apache Maven 3.9' + jdk 'OpenJDK 8 Latest' + } + options { + buildDiscarder logRotator(daysToKeepStr: '30', numToKeepStr: '10') + disableConcurrentBuilds(abortPrevious: false) + } + parameters { + string( + name: 'RELEASE_VERSION', + defaultValue: '5.6.16.Final', + description: 'The version to be released, e.g. 5.6.16.Final.', + trim: true + ) + string( + name: 'DEVELOPMENT_VERSION', + defaultValue: '5.6.17-SNAPSHOT', + description: 'The next version to be used after the release, e.g. 5.6.17-SNAPSHOT.', + trim: true + ) + booleanParam( + name: 'RELEASE_DRY_RUN', + defaultValue: true, + description: 'If true, just simulate the release, without pushing any commits or tags, and without uploading any artifacts or documentation.' + ) + booleanParam( + name: 'RELEASE_PUBLISH_AUTOMATICALLY', + defaultValue: false, + description: 'If true, staging repository will get closed and published automatically, otherwise the artifacts will only be uploaded and the publishing (releasing the staging repository) has to be performed manually at Maven Central portal.' + ) + } + stages { + stage('Release') { + when { + beforeAgent true + // Releases must be triggered explicitly + // This is just for safety; normally the Jenkins job for this pipeline + // should be configured to "Suppress automatic SCM triggering" + // See https://stackoverflow.com/questions/58259326/prevent-jenkins-multibranch-pipeline-from-triggering-builds-for-new-branches + triggeredBy cause: "UserIdCause" + } + steps { + script { + // Check that all the necessary parameters are set + if (!params.RELEASE_VERSION) { + throw new IllegalArgumentException("Missing value for parameter RELEASE_VERSION.") + } + if (!params.DEVELOPMENT_VERSION) { + throw new IllegalArgumentException("Missing value for parameter DEVELOPMENT_VERSION.") + } + + def releaseVersion = Version.parseReleaseVersion(params.RELEASE_VERSION) + def developmentVersion = Version.parseDevelopmentVersion(params.DEVELOPMENT_VERSION) + env.JRELEASER_DRY_RUN = params.RELEASE_DRY_RUN + if (!params.RELEASE_PUBLISH_AUTOMATICALLY) { + env.JRELEASER_DEPLOY_MAVEN_MAVENCENTRAL_STAGE='UPLOAD' + } + echo "Performing full release for version ${releaseVersion.toString()}" + + withMaven(mavenSettingsConfig: params.RELEASE_DRY_RUN ? null : 'ci-hibernate.deploy.settings.maven', + mavenLocalRepo: env.WORKSPACE_TMP + '/.m2repository') { + configFileProvider([configFile(fileId: 'release.config.ssh', targetLocation: env.HOME + '/.ssh/config'), + configFile(fileId: 'release.config.ssh.knownhosts', targetLocation: env.HOME + '/.ssh/known_hosts')]) { + // using MAVEN_GPG_PASSPHRASE (the default env variable name for passphrase in maven gpg plugin) + withCredentials([file(credentialsId: 'release.gpg.private-key', variable: 'RELEASE_GPG_PRIVATE_KEY_PATH'), + string(credentialsId: 'release.gpg.passphrase', variable: 'JRELEASER_GPG_PASSPHRASE'), + usernamePassword(credentialsId: 'central.sonatype.com', passwordVariable: 'JRELEASER_MAVENCENTRAL_TOKEN', usernameVariable: 'JRELEASER_MAVENCENTRAL_USERNAME'), + string(credentialsId: 'Hibernate-CI.github.com', variable: 'JRELEASER_GITHUB_TOKEN')]) { + sshagent(['ed25519.Hibernate-CI.github.com', 'hibernate.filemgmt.jboss.org', 'hibernate-ci.frs.sourceforge.net']) { + sh 'cat $HOME/.ssh/config' + dir('.release/scripts') { + sh 'git clone https://github.com/hibernate/hibernate-release-scripts.git .' + } + sh """ + bash -xe .release/scripts/release.sh -j ${params.RELEASE_DRY_RUN ? '-d' : ''} \ + tools ${releaseVersion.toString()} ${developmentVersion.toString()} + """ + } + } + } + } + } + } + } + } + post { + always { + notifyBuildResult notifySuccessAfterSuccess: true, maintainers: 'koen@hibernate.org' + } + } +} diff --git a/contribute.md b/contribute.md new file mode 100644 index 0000000000..3802c1ee94 --- /dev/null +++ b/contribute.md @@ -0,0 +1,65 @@ + + +# Contribution guide + +**Want to contribute? Great!** +We try to make it easy, and all contributions, even the smaller ones, are more than welcome. +This includes bug reports, fixes, documentation, examples... +But first, read this page (including the small print at the end). + +## Legal + +All original contributions to Hibernate Tools are licensed under the +[GNU Lesser General Public License (LGPL)](http://www.gnu.org/licenses/lgpl-2.1.html), +version 2.1 or later, or, if another license is specified as governing the file or directory being +modified, such other license. + +All contributions are subject to the [Developer Certificate of Origin (DCO)](https://developercertificate.org/). +The DCO text is also included verbatim in the [dco.txt](./dco.txt) file in the root directory of the repository. + +## Reporting an issue + +This project uses the [Hibernate Tools JIRA](https://hibernate.atlassian.net/projects/HBX/summary) to manage bugs and feature requests. Open an issue directly in JIRA. + +If you believe you found a bug, and it's likely possible, please indicate a way to reproduce it, what you are seeing and what you would expect to see. +Don't forget to indicate your Java and Hibernate versions. + +## Before you contribute + +To contribute, use GitHub Pull Requests, from your **own** fork. + +## Import the Projects + +The project is developed under the form of a hierarchical multimodule Maven project. +After cloning the git repository to your local machine you can import it as such into +your favorite IDE. + +## Work on a Topic Branch + +When you want to contribute code or documentation you first need to create a topic branch. It is common practice to give your branch a name that refers to the issue you are solving. E.g. if you want to fix the JIRA issue HBX-2000, name your topic branch 'HBX-2000' (`git checkout -b HBX-2000`). + +When the work is done or the issue is (partly) fixed, squash the commits into one. It is good practice to refer to the solved issue in the commit message. E.g. `git commit -m "HBX-2000: Create README.md files for the parent and child modules of the project - Add a 'contribute.md' file"`. + +Rebase your topic branch against the current master branch if necessary (`git rebase master`), push the branch to your own fork on GitHub (`git push HBX-2000`) and open a pull request (`https://github.com//quarkus-eclipse/pull/new/HBX-2000`). + +## The small print + +This project is an open source project, please act responsibly, be nice, polite and enjoy! \ No newline at end of file diff --git a/dco.txt b/dco.txt new file mode 100644 index 0000000000..0cdce0c397 --- /dev/null +++ b/dco.txt @@ -0,0 +1,37 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +1 Letterman Drive +Suite D4700 +San Francisco, CA, 94129 + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. \ No newline at end of file diff --git a/lgpl.txt b/lgpl.txt new file mode 100644 index 0000000000..4362b49151 --- /dev/null +++ b/lgpl.txt @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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! diff --git a/main/pom.xml b/main/pom.xml index 23734d3e42..cf46899760 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -6,7 +6,7 @@ org.hibernate hibernate-tools-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools @@ -49,38 +49,34 @@ koentsje - Koen Aersn + Koen Aers koen@hibernate.org http://koentsje.blogspot.be - false - false + + false - + - - commons-collections - commons-collections - + + com.google.googlejavaformat + google-java-format + - commons-logging - commons-logging + javax.persistence + javax.persistence-api - - jaxen - jaxen - org.apache.ant ant - - org.eclipse.jdt - org.eclipse.jdt.core - + + org.apache.commons + commons-collections4 + org.freemarker freemarker @@ -93,18 +89,28 @@ org.hibernate.common hibernate-commons-annotations - - org.hibernate.javax.persistence - hibernate-jpa-2.1-api - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - + + + + org.jboss.maven.plugins + maven-injection-plugin + + + + ${project.version} + + + org.hibernate.tool.Version + versionString + + + + + + + + + diff --git a/main/readme.txt b/main/readme.txt deleted file mode 100644 index 21538b1b69..0000000000 --- a/main/readme.txt +++ /dev/null @@ -1,35 +0,0 @@ -Hibernate Tools -=============== -Version: 4.0.0, February 2012 - -What is it ----------- - -The tools for Hibernate provides various tools to use with Hibernate. -The primary tools can be used for generating source artifacts such as -mapping files, java entities, DAO and other scaffolding code. The -source of this generation can be JDBC database, classes or even just -existing mappings. - -It uses Hibernate core metamodel to generate from and to the source -artifacts. Allowing it to support both top-down, bottom-up and -middle-out development. - -Hibernate Tools is used in JBoss Tools Hibernate plugins to provide -parts of the Eclipse plugins for Hibernate. - -Licensing ---------- - -This software is distributed under the terms of the FSF Lesser Gnu Public -License (see lgpl.txt). This product includes software developed by the Apache -Software Foundation (http://www.apache.org/). - -Hibernate Tools URLs --------------------- - -Home Page: http://tools.hibernate.org | http://jboss.org/tools -Downloads: http://jboss.org/tools/download -Mailing lists: http://www.hibernate.org/community/mailinglists.html -Source Code: https://github.com/hibernate/hibernate-tools/ -Issue Tracking: http://opensource.atlassian.com/projects/hibernate/browse/HBX diff --git a/main/src/main/java/org/hibernate/cfg/JDBCBinder.java b/main/src/main/java/org/hibernate/cfg/JDBCBinder.java index 625513ded8..7422b5a4e8 100644 --- a/main/src/main/java/org/hibernate/cfg/JDBCBinder.java +++ b/main/src/main/java/org/hibernate/cfg/JDBCBinder.java @@ -22,18 +22,17 @@ import org.hibernate.boot.internal.InFlightMetadataCollectorImpl; import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.cfg.binder.BinderUtils; import org.hibernate.cfg.binder.PrimaryKeyInfo; import org.hibernate.cfg.binder.PropertyBinder; import org.hibernate.cfg.reveng.AssociationInfo; import org.hibernate.cfg.reveng.DatabaseCollector; import org.hibernate.cfg.reveng.JDBCReader; -import org.hibernate.cfg.reveng.JDBCToHibernateTypeHelper; import org.hibernate.cfg.reveng.MappingsDatabaseCollector; import org.hibernate.cfg.reveng.RevEngUtils; import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; import org.hibernate.cfg.reveng.TableIdentifier; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.Mapping; @@ -58,8 +57,7 @@ import org.hibernate.tool.util.TableNameQualifier; import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; /** @@ -69,10 +67,11 @@ public class JDBCBinder { private Properties properties; - private static final Logger log = LoggerFactory.getLogger(JDBCBinder.class); + private static final Logger log = Logger.getLogger(JDBCBinder.class); private final MetadataBuildingContext mdbc; + private final InFlightMetadataCollector metadataCollector; private Metadata metadata; @@ -190,6 +189,7 @@ private void createPersistentClasses(DatabaseCollector collector, Mapping mappin rc.setDiscriminatorValue( rc.getEntityName() ); rc.setTable(table); + rc.setOptimisticLockStyle(OptimisticLockStyle.NONE); try { metadataCollector.addEntityBinding(rc); } catch(DuplicateMappingException dme) { @@ -278,7 +278,7 @@ private void bindIncomingForeignKeys(PersistentClass rc, Set processed, private Property bindOneToOne(PersistentClass rc, Table targetTable, ForeignKey fk, Set processedColumns, boolean constrained, boolean inverseProperty) { - OneToOne value = new OneToOne((MetadataImplementor)metadata, targetTable, rc); + OneToOne value = new OneToOne(mdbc, targetTable, rc); value.setReferencedEntityName(revengStrategy .tableToClassName(TableIdentifier.create(targetTable))); @@ -333,7 +333,7 @@ private Property bindOneToOne(PersistentClass rc, Table targetTable, * @param propName */ private Property bindManyToOne(String propertyName, boolean mutable, Table table, ForeignKey fk, Set processedColumns) { - ManyToOne value = new ManyToOne((MetadataImplementor)metadata, table); + ManyToOne value = new ManyToOne(mdbc, table); value.setReferencedEntityName( fk.getReferencedEntityName() ); Iterator columns = fk.getColumnIterator(); while ( columns.hasNext() ) { @@ -453,7 +453,7 @@ private Property bindOneToMany(PersistentClass rc, ForeignKey foreignKey, Set foreignKeyIterator = foreignKey.getTable().getForeignKeyIterator(); List keys = new ArrayList(); @@ -489,13 +489,20 @@ private Property bindOneToMany(PersistentClass rc, ForeignKey foreignKey, Set columnIterator = fk.getColumns().iterator(); + while (columnIterator.hasNext()) { + Column fkcolumn = (Column) columnIterator.next(); + if(fkcolumn.getSqlTypeCode() != null) { // TODO: user defined foreign ref columns does not have a type set. + guessAndAlignType(fk.getTable(), fkcolumn, mapping, false); // needed to ensure foreign key columns has same type as the "property" column. + } + element.addColumn(fkcolumn); + } collection.setElement( element ); } else { String tableToClassName = bindCollection( rc, foreignKey, null, collection ); - OneToMany oneToMany = new OneToMany((MetadataImplementor)metadata, collection.getOwner() ); + OneToMany oneToMany = new OneToMany(mdbc, collection.getOwner() ); oneToMany.setReferencedEntityName( tableToClassName ); // Child metadataCollector.addSecondPass( new JDBCCollectionSecondPass(mdbc, collection) ); @@ -514,7 +521,7 @@ private Property bindOneToMany(PersistentClass rc, ForeignKey foreignKey, Set columnIterator = foreignKey.getColumnIterator(); @@ -844,7 +851,7 @@ private Property bindBasicProperty(String propertyName, Table table, Column colu } private SimpleValue bindColumnToSimpleValue(Table table, Column column, Mapping mapping, boolean generatedIdentifier) { - SimpleValue value = new SimpleValue((MetadataImplementor)metadata, table); + SimpleValue value = new SimpleValue(mdbc, table); value.addColumn(column); value.setTypeName(guessAndAlignType(table, column, mapping, generatedIdentifier)); return value; @@ -896,7 +903,10 @@ private String guessAndAlignType(Table table, Column column, Mapping mapping, bo column.getLength(), column.getPrecision(), column.getScale(), column.isNullable(), generatedIdentifier ); - Type wantedType = metadataCollector.getTypeResolver().heuristicType(preferredHibernateType); + Type wantedType = metadataCollector + .getTypeConfiguration() + .getBasicTypeRegistry() + .getRegisteredType(preferredHibernateType); if(wantedType!=null) { int[] wantedSqlTypes = wantedType.sqlTypes(mapping); @@ -925,7 +935,7 @@ private String guessAndAlignType(Table table, Column column, Mapping mapping, bo } private String typeCodeName(int sqlTypeCode) { - return sqlTypeCode + "(" + JDBCToHibernateTypeHelper.getJDBCTypeName(sqlTypeCode) + ")"; + return sqlTypeCode + "(" + JdbcToHibernateTypeHelper.getJDBCTypeName(sqlTypeCode) + ")"; } /** @@ -936,7 +946,7 @@ private String typeCodeName(int sqlTypeCode) { * @return */ private SimpleValue handleCompositeKey(RootClass rc, Set processedColumns, List keyColumns, Mapping mapping) { - Component pkc = new Component((MetadataImplementor)metadata, rc); + Component pkc = new Component(mdbc, rc); pkc.setMetaAttributes(Collections.EMPTY_MAP); pkc.setEmbedded(false); diff --git a/main/src/main/java/org/hibernate/cfg/binder/PropertyBinder.java b/main/src/main/java/org/hibernate/cfg/binder/PropertyBinder.java index bfdd6cc767..053d7fc020 100644 --- a/main/src/main/java/org/hibernate/cfg/binder/PropertyBinder.java +++ b/main/src/main/java/org/hibernate/cfg/binder/PropertyBinder.java @@ -4,12 +4,11 @@ import org.hibernate.mapping.Property; import org.hibernate.mapping.Table; import org.hibernate.mapping.Value; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class PropertyBinder { - private static final Logger log = LoggerFactory.getLogger(PropertyBinder.class); + private static final Logger log = Logger.getLogger(PropertyBinder.class); public static Property makeProperty( Table table, diff --git a/main/src/main/java/org/hibernate/cfg/reveng/BasicColumnProcessor.java b/main/src/main/java/org/hibernate/cfg/reveng/BasicColumnProcessor.java index 407f96dab8..ab274d98e9 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/BasicColumnProcessor.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/BasicColumnProcessor.java @@ -7,15 +7,15 @@ import org.hibernate.JDBCException; import org.hibernate.cfg.JDBCBinderException; import org.hibernate.cfg.reveng.dialect.MetaDataDialect; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; import org.hibernate.tool.util.TableNameQualifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class BasicColumnProcessor { - private static final Logger log = LoggerFactory.getLogger(BasicColumnProcessor.class); + private static final Logger log = Logger.getLogger(BasicColumnProcessor.class); public static void processBasicColumns( MetaDataDialect metaDataDialect, @@ -83,15 +83,15 @@ public static void processBasicColumns( column.setComment(comment); column.setSqlTypeCode(new Integer(sqlType) ); if(intBounds(size) ) { - if(JDBCToHibernateTypeHelper.typeHasLength(sqlType) ) { + if(JdbcToHibernateTypeHelper.typeHasLength(sqlType) ) { column.setLength(size); } - if(JDBCToHibernateTypeHelper.typeHasScaleAndPrecision(sqlType) ) { + if(JdbcToHibernateTypeHelper.typeHasPrecision(sqlType) ) { column.setPrecision(size); } } if(intBounds(decimalDigits) ) { - if(JDBCToHibernateTypeHelper.typeHasScaleAndPrecision(sqlType) ) { + if(JdbcToHibernateTypeHelper.typeHasScale(sqlType) ) { column.setScale(decimalDigits); } } diff --git a/main/src/main/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java b/main/src/main/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java index 06dcb43f00..b5d5959afd 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/DefaultReverseEngineeringStrategy.java @@ -10,6 +10,7 @@ import java.util.Properties; import java.util.Set; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Column; import org.hibernate.mapping.ForeignKey; @@ -17,12 +18,11 @@ import org.hibernate.mapping.PrimaryKey; import org.hibernate.mapping.Table; import org.hibernate.tool.util.TableNameQualifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class DefaultReverseEngineeringStrategy implements ReverseEngineeringStrategy { - static final private Logger log = LoggerFactory.getLogger(DefaultReverseEngineeringStrategy.class); + static final private Logger log = Logger.getLogger(DefaultReverseEngineeringStrategy.class); private static Set AUTO_OPTIMISTICLOCK_COLUMNS; @@ -33,6 +33,7 @@ public class DefaultReverseEngineeringStrategy implements ReverseEngineeringStra AUTO_OPTIMISTICLOCK_COLUMNS = new HashSet(); AUTO_OPTIMISTICLOCK_COLUMNS.add("version"); AUTO_OPTIMISTICLOCK_COLUMNS.add("timestamp"); + AUTO_OPTIMISTICLOCK_COLUMNS.add("dbtimestamp"); } @@ -106,11 +107,11 @@ public String foreignKeyToEntityName(String keyname, TableIdentifier fromTable, } public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { - String preferredHibernateType = JDBCToHibernateTypeHelper.getPreferredHibernateType(sqlType, length, precision, scale, nullable, generatedIdentifier); + String preferredHibernateType = JdbcToHibernateTypeHelper.getPreferredHibernateType(sqlType, length, precision, scale, nullable, generatedIdentifier); String location = ""; if(log.isDebugEnabled()) { - String info = " t:" + JDBCToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; + String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; if(table!=null) { location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName + info; } else { diff --git a/main/src/main/java/org/hibernate/cfg/reveng/ForeignKeyProcessor.java b/main/src/main/java/org/hibernate/cfg/reveng/ForeignKeyProcessor.java index 081051e3f7..897daec7fa 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/ForeignKeyProcessor.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/ForeignKeyProcessor.java @@ -14,12 +14,11 @@ import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.Table; import org.hibernate.tool.util.TableNameQualifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class ForeignKeyProcessor { - private static final Logger log = LoggerFactory.getLogger(ForeignKeyProcessor.class); + private static final Logger log = Logger.getLogger(ForeignKeyProcessor.class); public static ForeignKeysInfo processForeignKeys( MetaDataDialect metaDataDialect, diff --git a/main/src/main/java/org/hibernate/cfg/reveng/IndexProcessor.java b/main/src/main/java/org/hibernate/cfg/reveng/IndexProcessor.java index 44eb94b6e3..4c3ff2bb30 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/IndexProcessor.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/IndexProcessor.java @@ -16,12 +16,11 @@ import org.hibernate.mapping.Table; import org.hibernate.mapping.UniqueKey; import org.hibernate.tool.util.TableNameQualifier; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class IndexProcessor { - private static final Logger log = LoggerFactory.getLogger(IndexProcessor.class); + private static final Logger log = Logger.getLogger(IndexProcessor.class); public static void processIndices( MetaDataDialect metaDataDialect, diff --git a/main/src/main/java/org/hibernate/cfg/reveng/JDBCReader.java b/main/src/main/java/org/hibernate/cfg/reveng/JDBCReader.java index 7852523a43..817cd9ed09 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/JDBCReader.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/JDBCReader.java @@ -155,9 +155,8 @@ public Set readSequences(String sql) { try { statement = connection.createStatement(); rs = statement.executeQuery(sql); - while ( rs.next() ) { - sequences.add( rs.getString(1).toLowerCase().trim() ); + sequences.add( rs.getString("SEQUENCE_NAME").toLowerCase().trim() ); } } finally { diff --git a/main/src/main/java/org/hibernate/cfg/reveng/MetaAttributeBinder.java b/main/src/main/java/org/hibernate/cfg/reveng/MetaAttributeBinder.java deleted file mode 100644 index 0f06f65b35..0000000000 --- a/main/src/main/java/org/hibernate/cfg/reveng/MetaAttributeBinder.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.hibernate.cfg.reveng; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import org.apache.commons.collections.MultiMap; -import org.apache.commons.collections.map.MultiValueMap; -import org.dom4j.Element; -import org.hibernate.mapping.MetaAttribute; -import org.hibernate.tool.hbm2x.MetaAttributeHelper; - -public class MetaAttributeBinder { - - /** - * Merges a Multimap with inherited maps. - * Values specified always overrules/replaces the inherited values. - * - * @param specific - * @param general - * @return a MultiMap with all values from local and extra values - * from inherited - */ - public static MultiMap mergeMetaMaps(MultiMap specific, MultiMap general) { - MultiValueMap result = new MultiValueMap(); - MetaAttributeHelper.copyMultiMap(result, specific); - - if (general != null) { - for (Iterator iter = general.keySet().iterator();iter.hasNext();) { - Object key = iter.next(); - - if (!specific.containsKey(key) ) { - // inheriting a meta attribute only if it is inheritable - Collection ml = (Collection)general.get(key); - for (Iterator iterator = ml.iterator(); iterator.hasNext();) { - SimpleMetaAttribute element = (SimpleMetaAttribute) iterator.next(); - if (element.inheritable) { - result.put(key, element); - } - } - } - } - } - - return result; - - } - - public static MetaAttribute toRealMetaAttribute(String name, List values) { - MetaAttribute attribute = new MetaAttribute(name); - for (Iterator iter = values.iterator(); iter.hasNext();) { - SimpleMetaAttribute element = (SimpleMetaAttribute) iter.next(); - attribute.addValue(element.value); - } - - return attribute; - } - - - /** - * Method loadAndMergeMetaMap. - * @param classElement - * @param inheritedMeta - * @return MultiMap - */ - public static MultiMap loadAndMergeMetaMap( - Element classElement, - MultiMap inheritedMeta) { - return MetaAttributeBinder.mergeMetaMaps(loadMetaMap(classElement), inheritedMeta); - } - - - /** - * Load meta attributes from jdom element into a MultiMap. - * - * @param element - * @return MultiMap - */ - protected static MultiMap loadMetaMap(Element element) { - MultiMap result = new MultiValueMap(); - List metaAttributeList = new ArrayList(); - for (Object obj : element.elements("meta")) { - metaAttributeList.add((Element)obj); - } - - for (Iterator iter = metaAttributeList.iterator(); iter.hasNext();) { - Element metaAttrib = iter.next(); - // does not use getTextNormalize() or getTextTrim() as that would remove the formatting in new lines in items like description for javadocs. - String attribute = metaAttrib.attributeValue("attribute"); - String value = metaAttrib.getText(); - String inheritStr= metaAttrib.attributeValue("inherit"); - boolean inherit = true; - if(inheritStr!=null) { - inherit = Boolean.valueOf(inheritStr).booleanValue(); - } - - SimpleMetaAttribute ma = new SimpleMetaAttribute(value, inherit); - result.put(attribute, ma); - } - return result; - - } - -} diff --git a/main/src/main/java/org/hibernate/cfg/reveng/OverrideBinder.java b/main/src/main/java/org/hibernate/cfg/reveng/OverrideBinder.java index 004e30197d..25a667767f 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/OverrideBinder.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/OverrideBinder.java @@ -1,442 +1,429 @@ package org.hibernate.cfg.reveng; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Properties; -import org.apache.commons.collections.MultiMap; -import org.apache.commons.collections.map.MultiValueMap; -import org.dom4j.Document; -import org.dom4j.Element; +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; import org.hibernate.MappingException; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper.SimpleMetaAttribute; +import org.hibernate.cfg.reveng.utils.RevengUtils; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Column; import org.hibernate.mapping.ForeignKey; import org.hibernate.mapping.Table; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +public class OverrideBinder { -public final class OverrideBinder { - - private OverrideBinder() { - // empty + public static void bindRoot(OverrideRepository repository, Document doc) { + Element rootElement = doc.getDocumentElement(); + bindSchemaSelections(getChildElements(rootElement, "schema-selection"), repository); + bindTypeMappings(getChildElements(rootElement, "type-mapping"), repository); + bindTableFilters(getChildElements(rootElement, "table-filter"), repository); + bindTables(getChildElements(rootElement, "table"), repository); } - public static void bindRoot(OverrideRepository repository, Document doc) { - - Element rootElement = doc.getRootElement(); - - Element element; - List elements; - - elements = rootElement.elements("schema-selection"); - bindSchemaSelection(elements, repository); - - element = rootElement.element("type-mapping"); - - if(element!=null) { - bindTypeMappings(element, repository); + private static void bindSchemaSelections( + ArrayList schemaSelections, + OverrideRepository repository) { + for (Element schemaSelection : schemaSelections) { + bindSchemaSelection(schemaSelection, repository); } - - - elements = rootElement.elements("table-filter"); - bindTableFilters(elements, repository); - - List tables = rootElement.elements("table"); - bindTables(tables, repository); - } - - static boolean bindManyToOneAndCollection(Element element, String constraintName, OverrideRepository repository) { - - String manyToOneProperty = null; - Boolean excludeManyToOne = null; - - DefaulAssociationInfo associationInfo = null; - DefaulAssociationInfo inverseAssociationInfo = null; - Element manyToOne = element.element("many-to-one"); - if(manyToOne!=null) { - manyToOneProperty = manyToOne.attributeValue("property"); - excludeManyToOne = BooleanValue(manyToOne.attributeValue("exclude")); - associationInfo = extractAssociationInfo(manyToOne); - } - - String collectionProperty = null; - Boolean excludeCollection = null; - Element collection = element.element("set"); - if(collection!=null) { - collectionProperty = collection.attributeValue("property"); - excludeCollection = BooleanValue(collection.attributeValue("exclude")); - inverseAssociationInfo = extractAssociationInfo(collection); - } - - if ( (manyToOne!=null) || (collection!=null) ) { - repository.addForeignKeyInfo(constraintName, manyToOneProperty, excludeManyToOne, collectionProperty, excludeCollection, associationInfo, inverseAssociationInfo); - return true; - } else { - return false; + + private static void bindTypeMappings( + ArrayList typeMappings, + OverrideRepository repository) { + if (typeMappings.size() > 0) { + bindTypeMapping(typeMappings.get(0), repository); } } - private static void bindSchemaSelection(List selection, OverrideRepository repository) { - Iterator iterator = selection.iterator(); - - while ( iterator.hasNext() ) { - Element element = (Element) iterator.next(); - SchemaSelection schemaSelection = new SchemaSelection(); - schemaSelection.setMatchCatalog( element.attributeValue("match-catalog") ); - schemaSelection.setMatchSchema( element.attributeValue("match-schema") ); - schemaSelection.setMatchTable( element.attributeValue("match-table") ); - - repository.addSchemaSelection(schemaSelection); - - } + private static void bindTableFilters( + ArrayList tableFilters, + OverrideRepository repository) { + for (Element element : tableFilters) { + TableFilter tableFilter = new TableFilter(); + tableFilter.setMatchCatalog(getAttribute(element, "match-catalog")); + tableFilter.setMatchSchema(getAttribute(element, "match-schema")); + tableFilter.setMatchName(getAttribute(element, "match-name")); + tableFilter.setExclude(Boolean.valueOf(getAttribute(element, "exclude"))); + tableFilter.setPackage(getAttribute(element, "package")); + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap()); + if (map != null && !map.isEmpty()) { + tableFilter.setMetaAttributes(map); + } else { + tableFilter.setMetaAttributes(null); + } + repository.addTableFilter(tableFilter); + } } - - private static void bindTables(List tables, OverrideRepository repository) { - Iterator iterator = tables.iterator(); - while ( iterator.hasNext() ) { - Element element = (Element) iterator.next(); + private static void bindTables( + ArrayList tables, + OverrideRepository repository) { + for (Element element : tables) { Table table = new Table(); - table.setCatalog( element.attributeValue("catalog") ); - table.setSchema( element.attributeValue("schema") ); - table.setName( element.attributeValue("name") ); - - String wantedClassName = element.attributeValue("class"); - - Element primaryKey = element.element("primary-key"); - bindPrimaryKey(primaryKey, table, repository); - List columns = element.elements("column"); - bindColumns(columns, table, repository); - - - List foreignKeys = element.elements("foreign-key"); - bindForeignKeys(foreignKeys, table, repository); - + table.setCatalog(getAttribute(element, "catalog")); + table.setSchema(getAttribute(element, "schema")); + table.setName(getAttribute(element, "name")); + ArrayList primaryKeys = getChildElements(element, "primary-key"); + if (primaryKeys.size() > 0) { + bindPrimaryKey(primaryKeys.get(0), table, repository); + } + bindColumns(getChildElements(element, "column"), table, repository); + bindForeignKeys(getChildElements(element, "foreign-key"), table, repository); bindMetaAttributes(element, table, repository); - - repository.addTable(table,wantedClassName); - - } - - } - - private static void bindMetaAttributes(Element element, Table table, OverrideRepository repository) { - MultiMap map = MetaAttributeBinder.loadAndMergeMetaMap( element, new MultiValueMap()); - if(map!=null && !map.isEmpty()) { - repository.addMetaAttributeInfo( table, map); - } + repository.addTable(table, getAttribute(element, "class")); + } } - - private static void bindPrimaryKey(Element identifier, Table table, OverrideRepository repository) { - if(identifier==null) return; - - String propertyName = identifier.attributeValue("property"); - String compositeIdName = identifier.attributeValue("id-class"); - - Element element = identifier.element("generator"); - if(element!=null) { - String identifierClass = element.attributeValue("class"); - + + private static void bindPrimaryKey( + Element element, + Table table, + OverrideRepository repository) { + String propertyName = getAttribute(element, "property"); + String compositeIdName = getAttribute(element, "id-class"); + ArrayList generators = getChildElements(element, "generator"); + if (generators.size() > 0) { + Element generator = generators.get(0); + String identifierClass = getAttribute(generator, "class"); Properties params = new Properties(); - Iterator iter = element.elementIterator( "param" ); - while ( iter.hasNext() ) { - Element childNode = (Element) iter.next(); - params.setProperty( childNode.attributeValue( "name" ), childNode.getText() ); + ArrayList parameterList = getChildElements(generator, "param"); + for (int i = 0; i < parameterList.size(); i++) { + Element parameter = parameterList.get(i); + params.setProperty(getAttribute(parameter, "name"), parameter.getTextContent()); } - repository.addTableIdentifierStrategy(table, identifierClass, params); } - - List boundColumnNames = bindColumns(identifier.elements("key-column"), table, repository); - + List boundColumnNames = bindColumns(getChildElements(element, "key-column"), table, repository); repository.addPrimaryKeyNamesForTable(table, boundColumnNames, propertyName, compositeIdName); - } - - private static void bindForeignKeys(List foreignKeys, Table table, OverrideRepository repository) { - Iterator iterator = foreignKeys.iterator(); - - while( iterator.hasNext() ) { - Element element = (Element) iterator.next(); - - String constraintName = element.attributeValue("constraint-name"); - - String foreignTableName = element.attributeValue("foreign-table"); - if(foreignTableName!=null) { + + private static List bindColumns( + ArrayList columns, + Table table, + OverrideRepository repository) { + List columnNames = new ArrayList(); + for (Element element : columns) { + Column column = new Column(); + column.setName(getAttribute(element, "name")); + String attributeValue = getAttribute(element, "jdbc-type"); + if (StringHelper.isNotEmpty(attributeValue)) { + column.setSqlTypeCode(Integer.valueOf(JdbcToHibernateTypeHelper.getJDBCType(attributeValue))); + } + TableIdentifier tableIdentifier = TableIdentifier.create(table); + if (table.getColumn(column) != null) { + throw new MappingException("Column " + column.getName() + " already exists in table " + tableIdentifier ); + } + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap()); + if(map!=null && !map.isEmpty()) { + repository.addMetaAttributeInfo( tableIdentifier, column.getName(), map); + } + table.addColumn(column); + columnNames.add(column.getName()); + repository.setTypeNameForColumn( + tableIdentifier, + column.getName(), + getAttribute(element, "type")); + repository.setPropertyNameForColumn( + tableIdentifier, + column.getName(), + getAttribute(element, "property")); + boolean excluded = Boolean.valueOf(element.getAttribute("exclude") ); + if(excluded) { + repository.setExcludedColumn(tableIdentifier, column.getName()); + } + if (element.hasAttribute("foreign-table")) { + String foreignTableName = element.getAttribute("foreign-table"); + List localColumns = new ArrayList(); + localColumns.add(column); + List foreignColumns = new ArrayList(); Table foreignTable = new Table(); foreignTable.setName(foreignTableName); - foreignTable.setCatalog(getValue(element.attributeValue( "foreign-catalog"), table.getCatalog()) ); - foreignTable.setSchema(getValue(element.attributeValue( "foreign-schema"), table.getSchema()) ); - + foreignTable.setCatalog( + element.hasAttribute("foreign-catalog") ? + element.getAttribute("foreign-catalog") : + table.getCatalog()); + foreignTable.setSchema( + element.hasAttribute("foreign-schema") ? + element.getAttribute("foreign-schema") : + table.getSchema()); + if (element.hasAttribute("foreign-column")) { + String foreignColumnName = element.getAttribute("foreign-column"); + Column foreignColumn = new Column(); + foreignColumn.setName(foreignColumnName); + foreignColumns.add(foreignColumn); + } else { + throw new MappingException("foreign-column is required when foreign-table is specified on " + column); + } + ForeignKey key = table.createForeignKey( + null, + localColumns, + foreignTableName, + null, + foreignColumns); + key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) + } + } + return columnNames; + } + + private static void bindForeignKeys( + ArrayList foreignKeys, + Table table, + OverrideRepository repository) { + for (Element element : foreignKeys) { + String constraintName = getAttribute(element, "constraint-name"); + String foreignTableName = getAttribute(element, "foreign-table"); + if (foreignTableName != null) { + Table foreignTable = new Table(); + foreignTable.setName(foreignTableName); + foreignTable.setCatalog( + element.hasAttribute("foreign-catalog") ? + element.getAttribute("foreign-catalog") : + table.getCatalog()); + foreignTable.setSchema( + element.hasAttribute("foreign-schema") ? + element.getAttribute("foreign-schema") : + table.getSchema()); List localColumns = new ArrayList(); List foreignColumns = new ArrayList(); - - Iterator columnRefs = element.elements("column-ref").iterator(); - while ( columnRefs.hasNext() ) { - Element columnRef = (Element) columnRefs.next(); - String localColumnName = columnRef.attributeValue("local-column"); - String foreignColumnName = columnRef.attributeValue("foreign-column"); - - Column localColumn = new Column(localColumnName); - Column foreignColumn = new Column(foreignColumnName); - - localColumns.add(localColumn); - foreignColumns.add(foreignColumn); + ArrayList columnRefs = getChildElements(element, "column-ref"); + for (Element columnRef : columnRefs) { + localColumns.add(new Column(columnRef.getAttribute("local-column"))); + foreignColumns.add(new Column(columnRef.getAttribute("foreign-column"))); } - - ForeignKey key = table.createForeignKey(constraintName, localColumns, foreignTableName, null, foreignColumns); + ForeignKey key = table.createForeignKey( + constraintName, + localColumns, + foreignTableName, + null, + foreignColumns); key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) } - - if(StringHelper.isNotEmpty(constraintName)) { - if (!validateFkAssociations(element)) + if (StringHelper.isNotEmpty(constraintName)) { + if (!validateFkAssociations(element)) { throw new IllegalArgumentException("you can't mix or with <(inverse-)one-to-one/> "); - - if(!bindManyToOneAndCollection(element, constraintName, repository)) { + } + if (!bindManyToOneAndCollection(element, constraintName, repository)) { bindOneToOne(element, constraintName, repository); - } + } } + } - } - + private static void bindOneToOne(Element element, String constraintName, OverrideRepository repository) { String oneToOneProperty = null; Boolean excludeOneToOne = null; - Element oneToOne = element.element("one-to-one"); - DefaulAssociationInfo associationInfo = null; - if(oneToOne!=null) { - oneToOneProperty = oneToOne.attributeValue("property"); - excludeOneToOne = BooleanValue(oneToOne.attributeValue("exclude")); + ArrayList oneToOnes = getChildElements(element, "one-to-one"); + Element oneToOne = null; + AssociationInfo associationInfo = null; + if(oneToOnes.size() > 0) { + oneToOne = oneToOnes.get(0); + oneToOneProperty = getAttribute(oneToOne, "property"); + excludeOneToOne = Boolean.valueOf(oneToOne.getAttribute("exclude")); associationInfo = extractAssociationInfo(oneToOne); } String inverseOneToOneProperty = null; Boolean excludeInverseOneToOne = null; - Element inverseOneToOne = element.element("inverse-one-to-one"); - DefaulAssociationInfo inverseAssociationInfo = null; - if(inverseOneToOne!=null) { - inverseOneToOneProperty = inverseOneToOne.attributeValue("property"); - excludeInverseOneToOne = BooleanValue(inverseOneToOne.attributeValue("exclude")); + ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); + Element inverseOneToOne = null; + AssociationInfo inverseAssociationInfo = null; + if(inverseOneToOnes.size() > 0) { + inverseOneToOne = inverseOneToOnes.get(0); + inverseOneToOneProperty = getAttribute(inverseOneToOne, "property"); + excludeInverseOneToOne = Boolean.valueOf(inverseOneToOne.getAttribute("exclude")); inverseAssociationInfo = extractAssociationInfo(inverseOneToOne); - } - + } // having oneToOne = null and inverseOneToOne != null doesn't make sense - // we cannot have the inverse side without the owning side in this case - + // we cannot have the inverse side without the owning side in this case if ( (oneToOne!=null) ) { - repository.addForeignKeyInfo(constraintName, oneToOneProperty, excludeOneToOne, inverseOneToOneProperty, excludeInverseOneToOne, associationInfo, inverseAssociationInfo); + repository.addForeignKeyInfo( + constraintName, + oneToOneProperty, + excludeOneToOne, + inverseOneToOneProperty, + excludeInverseOneToOne, + associationInfo, + inverseAssociationInfo); } } - private static DefaulAssociationInfo extractAssociationInfo(Element manyToOne) { - String attributeValue = manyToOne.attributeValue("cascade"); - DefaulAssociationInfo associationInfo = null; - if(attributeValue!=null) { - associationInfo = ensureInit(associationInfo); - associationInfo.setCascade(attributeValue); + private static boolean bindManyToOneAndCollection( + Element element, + String constraintName, + OverrideRepository repository) { + String manyToOneProperty = null; + Boolean excludeManyToOne = null; + AssociationInfo associationInfo = null; + AssociationInfo inverseAssociationInfo = null; + ArrayList manyToOnes = getChildElements(element, "many-to-one"); + Element manyToOne = null; + if (manyToOnes.size() > 0) { + manyToOne = manyToOnes.get(0); + manyToOneProperty = getAttribute(manyToOne, "property"); + excludeManyToOne = Boolean.valueOf(manyToOne.getAttribute("exclude")); + associationInfo = extractAssociationInfo(manyToOne); } - - - attributeValue = manyToOne.attributeValue("fetch"); - if(attributeValue!=null) { - associationInfo = ensureInit(associationInfo); - associationInfo.setFetch(attributeValue); - } - - - attributeValue = manyToOne.attributeValue("insert"); - if(attributeValue!=null) { - associationInfo = ensureInit(associationInfo); - associationInfo.setInsert(new Boolean(attributeValue)); - } - - - attributeValue = manyToOne.attributeValue("update"); - if(attributeValue!=null) { - associationInfo = ensureInit(associationInfo); - associationInfo.setUpdate(new Boolean(attributeValue)); + String collectionProperty = null; + Boolean excludeCollection = null; + ArrayList sets = getChildElements(element, "set"); + Element set = null; + if (sets.size() > 0) { + set = sets.get(0); + collectionProperty = getAttribute(set, "property"); + excludeCollection = Boolean.valueOf(set.getAttribute("exclude")); + inverseAssociationInfo = extractAssociationInfo(set); + } + if ( (manyToOne!=null) || (set!=null) ) { + repository.addForeignKeyInfo( + constraintName, + manyToOneProperty, + excludeManyToOne, + collectionProperty, + excludeCollection, + associationInfo, + inverseAssociationInfo); + return true; + } else { + return false; } - return associationInfo; } - - private static DefaulAssociationInfo ensureInit( - DefaulAssociationInfo associationInfo) { - return associationInfo==null?new DefaulAssociationInfo():associationInfo; + + private static AssociationInfo extractAssociationInfo(Element manyToOne) { + return RevengUtils.createAssociationInfo( + manyToOne.hasAttribute("cascade") ? manyToOne.getAttribute("cascade") : null, + manyToOne.hasAttribute("fetch") ? manyToOne.getAttribute("fetch") : null, + manyToOne.hasAttribute("insert") ? + Boolean.parseBoolean(manyToOne.getAttribute("insert")) : null, + manyToOne.hasAttribute("update") ? + Boolean.parseBoolean(manyToOne.getAttribute("update")) : null); } private static boolean validateFkAssociations(Element element){ - Element manyToOne = element.element("many-to-one"); - Element oneToOne = element.element("one-to-one"); - Element set = element.element("set"); - Element inverseOneToOne = element.element("inverse-one-to-one"); - - if((manyToOne != null) && ( (oneToOne != null) || (inverseOneToOne != null))) { + ArrayList manyToOnes = getChildElements(element, "many-to-one"); + ArrayList oneToOnes = getChildElements(element, "one-to-one"); + ArrayList sets = getChildElements(element, "set"); + ArrayList inverseOneToOnes = getChildElements(element, "inverse-one-to-one"); + if (manyToOnes.size() != 0 && + (oneToOnes.size() != 0 || inverseOneToOnes.size() != 0)) { return false; - } - - if((oneToOne != null) && (set != null)) { + if (oneToOnes.size() != 0 && sets.size() != 0) { return false; } - - if ((inverseOneToOne != null) && (set != null)) { + if (inverseOneToOnes.size() != 0 && sets.size() != 0) { return false; } - return true; } - private static Boolean BooleanValue(String string) { - if(string==null) return null; - return Boolean.valueOf(string); - } - - private static String getValue(String first, String second) { - if(first==null) { - return second; - } else { - return first; - } + private static void bindMetaAttributes( + Element element, + Table table, + OverrideRepository repository) { + MultiValuedMap map = + MetaAttributeHelper.loadAndMergeMetaMap( + element, + new HashSetValuedHashMap()); + if(map!=null && !map.isEmpty()) { + repository.addMetaAttributeInfo( table, map); + } } - - private static List bindColumns(List columns, Table table, OverrideRepository repository) { - Iterator iterator = columns.iterator(); - List columnNames = new ArrayList(); - while( iterator.hasNext() ) { - Element element = (Element) iterator.next(); - Column column = new Column(); - column.setName( element.attributeValue("name") ); - String attributeValue = element.attributeValue("jdbc-type"); - if(StringHelper.isNotEmpty(attributeValue)) { - column.setSqlTypeCode(new Integer(JDBCToHibernateTypeHelper.getJDBCType(attributeValue))); - } - - TableIdentifier tableIdentifier = TableIdentifier.create(table); - if(table.getColumn(column)!=null) { - throw new MappingException("Column " + column.getName() + " already exists in table " + tableIdentifier ); - } - - MultiMap map = MetaAttributeBinder.loadAndMergeMetaMap( element, new MultiValueMap()); - if(map!=null && !map.isEmpty()) { - repository.addMetaAttributeInfo( tableIdentifier, column.getName(), map); - } - - table.addColumn(column); - columnNames.add(column.getName()); - repository.setTypeNameForColumn(tableIdentifier, column.getName(), element.attributeValue("type")); - repository.setPropertyNameForColumn(tableIdentifier, column.getName(), element.attributeValue("property")); - - boolean excluded = booleanValue( element.attributeValue("exclude") ); - if(excluded) { - repository.setExcludedColumn(tableIdentifier, column.getName()); - } - - String foreignTableName = element.attributeValue("foreign-table"); - if(foreignTableName!=null) { - List localColumns = new ArrayList(); - localColumns.add(column); - List foreignColumns = new ArrayList(); - - Table foreignTable = new Table(); - foreignTable.setName(foreignTableName); - foreignTable.setCatalog(getValue(element.attributeValue( "foreign-catalog"),table.getCatalog()) ); - foreignTable.setSchema(getValue(element.attributeValue( "foreign-schema"), table.getSchema()) ); - - String foreignColumnName = element.attributeValue("foreign-column"); - if(foreignColumnName!=null) { - Column foreignColumn = new Column(); - foreignColumn.setName(foreignColumnName); - foreignColumns.add(foreignColumn); - } - else { - throw new MappingException("foreign-column is required when foreign-table is specified on " + column); - } - - ForeignKey key = table.createForeignKey(null, localColumns, foreignTableName, null, foreignColumns); - key.setReferencedTable(foreignTable); // only possible if foreignColumns is explicitly specified (workaround on aligncolumns) - } - - - - } - return columnNames; - } - - private static boolean booleanValue(String value) { - return Boolean.valueOf(value).booleanValue(); + private static void bindSchemaSelection( + Element schemaSelectionElement, + OverrideRepository repository) { + repository.addSchemaSelection( + new SchemaSelection() { + @Override + public String getMatchCatalog() { + return getAttribute(schemaSelectionElement, "match-catalog"); + } + @Override + public String getMatchSchema() { + return getAttribute(schemaSelectionElement, "match-schema"); + } + @Override + public String getMatchTable() { + return getAttribute(schemaSelectionElement, "match-table"); + } + + }); } - - private static void bindTableFilters(List filters, OverrideRepository respository) { - Iterator iterator = filters.iterator(); - - while(iterator.hasNext() ) { - Element element = (Element) iterator.next(); - TableFilter filter = new TableFilter(); - filter.setMatchCatalog(element.attributeValue("match-catalog") ); - filter.setMatchSchema(element.attributeValue("match-schema") ); - filter.setMatchName(element.attributeValue("match-name") ); - filter.setExclude(Boolean.valueOf(element.attributeValue("exclude") ) ); - filter.setPackage(element.attributeValue("package") ); - - MultiMap map = MetaAttributeBinder.loadAndMergeMetaMap( element, new MultiValueMap()); - if(map!=null && !map.isEmpty()) { - filter.setMetaAttributes( map ); - } else { - filter.setMetaAttributes( null ); - } - respository.addTableFilter(filter); + + private static void bindTypeMapping( + Element typeMapping, + OverrideRepository repository) { + ArrayList sqlTypes = getChildElements(typeMapping, "sql-type"); + for (int i = 0; i < sqlTypes.size(); i++) { + bindSqlType(sqlTypes.get(i), repository); } - } - - private static void bindTypeMappings(Element typeMapping, OverrideRepository repository) { - Iterator iterator = typeMapping.elements("sql-type").iterator(); - - while (iterator.hasNext() ) { - Element element = (Element) iterator.next(); - int jdbcType = JDBCToHibernateTypeHelper.getJDBCType(element.attributeValue("jdbc-type") ); - SQLTypeMapping mapping = new SQLTypeMapping(jdbcType ); - mapping.setHibernateType( getHibernateType( element ) ); - mapping.setLength(getInteger(element.attributeValue("length"), SQLTypeMapping.UNKNOWN_LENGTH) ); - mapping.setPrecision(getInteger(element.attributeValue("precision"), SQLTypeMapping.UNKNOWN_PRECISION) ); - mapping.setScale(getInteger(element.attributeValue("scale"), SQLTypeMapping.UNKNOWN_SCALE) ); - String notNull = element.attributeValue("not-null"); - if(notNull==null) { - mapping.setNullable(null); - } else { - boolean nullable = notNull.equals( "false" ); - mapping.setNullable( Boolean.valueOf(nullable) ); - } - - if(StringHelper.isEmpty(mapping.getHibernateType())) { - throw new MappingException("No hibernate-type specified for " + element.attributeValue("jdbc-type") + " at " + element.getUniquePath()); - } - repository.addTypeMapping(mapping); + + private static void bindSqlType(Element sqlType, OverrideRepository repository) { + int jdbcType = JdbcToHibernateTypeHelper.getJDBCType( + getAttribute(sqlType, "jdbc-type")); + SQLTypeMapping sqlTypeMapping = new SQLTypeMapping(jdbcType); + sqlTypeMapping.setHibernateType(getHibernateType(sqlType)); + sqlTypeMapping.setLength(getInteger( + getAttribute(sqlType, "length"), + SQLTypeMapping.UNKNOWN_LENGTH)); + sqlTypeMapping.setPrecision(getInteger( + getAttribute(sqlType, "precision"), + SQLTypeMapping.UNKNOWN_PRECISION)); + sqlTypeMapping.setScale(getInteger( + getAttribute(sqlType, "scale"), + SQLTypeMapping.UNKNOWN_SCALE)); + String notNull = getAttribute(sqlType, "not-null"); + if (StringHelper.isEmpty(notNull)) { + sqlTypeMapping.setNullable(null); + } else { + sqlTypeMapping.setNullable(notNull.equals("false")); } - + if (StringHelper.isEmpty(sqlTypeMapping.getHibernateType())) { + throw new MappingException( + "No hibernate-type specified for " + + sqlType.getAttribute("jdbc-type") + + " at " + + sqlType.getTagName()); + } + repository.addTypeMapping(sqlTypeMapping); } - + private static String getHibernateType(Element element) { - String attributeValue = element.attributeValue("hibernate-type"); - + String attributeValue = getAttribute(element, "hibernate-type"); if(StringHelper.isEmpty(attributeValue)) { - Element child = element.element("hibernate-type"); - if(child==null) { - return null; + ArrayList hibernateTypes = getChildElements(element, "hibernate-type"); + if (hibernateTypes.size() > 0) { + Element hibernateType = hibernateTypes.get(0); + if (hibernateType.hasAttribute("name")) { + return hibernateType.getAttribute("name"); + } } else { - return child.attributeValue("name"); + return null; } - } - return attributeValue; } - + private static int getInteger(String string, int defaultValue) { if(string==null) { return defaultValue; @@ -445,11 +432,27 @@ private static int getInteger(String string, int defaultValue) { return Integer.parseInt(string); } } - - String getMatchString(String input) { - return input.toUpperCase(); + + private static ArrayList getChildElements(Element parent, String tagName) { + ArrayList result = new ArrayList(); + NodeList nodeList = parent.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element) { + if (tagName.equals(((Element)node).getTagName())) { + result.add((Element)node); + } + } + } + return result; } - + private static String getAttribute(Element element, String attributeName) { + String result = null; + if (element.hasAttribute(attributeName)) { + result = element.getAttribute(attributeName); + } + return result; + } } diff --git a/main/src/main/java/org/hibernate/cfg/reveng/OverrideRepository.java b/main/src/main/java/org/hibernate/cfg/reveng/OverrideRepository.java index 7f6194e9c4..0642536209 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/OverrideRepository.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/OverrideRepository.java @@ -5,18 +5,24 @@ import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import org.apache.commons.collections.MultiMap; -import org.dom4j.Document; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.collections4.MapIterator; +import org.apache.commons.collections4.MultiValuedMap; import org.hibernate.MappingException; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper.SimpleMetaAttribute; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.xml.ErrorLogger; import org.hibernate.mapping.Column; @@ -24,14 +30,12 @@ import org.hibernate.mapping.MetaAttribute; import org.hibernate.mapping.Table; import org.hibernate.tool.util.TableNameQualifier; -import org.hibernate.tool.xml.XMLHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.InputSource; +import org.jboss.logging.Logger; +import org.w3c.dom.Document; public class OverrideRepository { - final private static Logger log = LoggerFactory.getLogger( OverrideRepository.class ); + final private static Logger log = Logger.getLogger( OverrideRepository.class ); final private Map> typeMappings; // from sqltypes to list of SQLTypeMapping @@ -71,9 +75,9 @@ public class OverrideRepository { final private Map foreignKeyToEntityInfo; final private Map foreignKeyToInverseEntityInfo; - final private Map tableMetaAttributes; // TI -> MultiMap of SimpleMetaAttributes + final private Map> tableMetaAttributes; // TI -> MultiMap of SimpleMetaAttributes - final private Map columnMetaAttributes; + final private Map> columnMetaAttributes; //private String defaultCatalog; //private String defaultSchema; @@ -99,8 +103,8 @@ public OverrideRepository() { foreignKeyToInverseName = new HashMap(); foreignKeyInverseExclude = new HashMap(); foreignKeyToOneExclude = new HashMap(); - tableMetaAttributes = new HashMap(); - columnMetaAttributes = new HashMap(); + tableMetaAttributes = new HashMap>(); + columnMetaAttributes = new HashMap>(); foreignKeyToEntityInfo = new HashMap(); foreignKeyToInverseEntityInfo = new HashMap(); } @@ -140,9 +144,12 @@ public OverrideRepository addResource(String path) throws MappingException { public OverrideRepository addInputStream(InputStream xmlInputStream) throws MappingException { try { ErrorLogger errorLogger = new ErrorLogger( "XML InputStream" ); - org.dom4j.Document doc = XMLHelper.createSAXReader( errorLogger).read( new InputSource( xmlInputStream ) ); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(errorLogger); + Document document = db.parse(xmlInputStream); if ( errorLogger.hasErrors() ) throw new MappingException( "invalid override definition", ( Throwable ) errorLogger.getErrors().get( 0 ) ); - add( doc ); + add( document ); return this; } catch ( MappingException me ) { @@ -162,6 +169,7 @@ public OverrideRepository addInputStream(InputStream xmlInputStream) throws Mapp } } + private OverrideRepository add(Document doc) { OverrideBinder.bindRoot(this, doc); return this; @@ -311,7 +319,7 @@ public List getSchemaSelections() { public String columnToHibernateTypeName(TableIdentifier table, String columnName, int sqlType, int length, int precision, int scale, boolean nullable, boolean generatedIdentifier) { String result = null; String location = ""; - String info = " t:" + JDBCToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; + String info = " t:" + JdbcToHibernateTypeHelper.getJDBCTypeName( sqlType ) + " l:" + length + " p:" + precision + " s:" + scale + " n:" + nullable + " id:" + generatedIdentifier; if(table!=null) { location = TableNameQualifier.qualify(table.getCatalog(), table.getSchema(), table.getName() ) + "." + columnName; } else { @@ -502,7 +510,7 @@ public AssociationInfo foreignKeyToAssociationInfo(ForeignKey foreignKey) { } protected Map columnToMetaAttributes(TableIdentifier tableIdentifier, String column) { - MultiMap specific = columnMetaAttributes.get( new TableColumnKey(tableIdentifier, column) ); + MultiValuedMap specific = columnMetaAttributes.get( new TableColumnKey(tableIdentifier, column) ); if(specific!=null && !specific.isEmpty()) { return toMetaAttributes(specific); } @@ -512,11 +520,11 @@ protected Map columnToMetaAttributes(TableIdentifier tabl // TODO: optimize protected Map tableToMetaAttributes(TableIdentifier identifier) { - MultiMap specific = tableMetaAttributes.get( identifier ); + MultiValuedMap specific = tableMetaAttributes.get( identifier ); if(specific!=null && !specific.isEmpty()) { return toMetaAttributes(specific); } - Map general = findGeneralAttributes( identifier ); + MultiValuedMap general = findGeneralAttributes( identifier ); if(general!=null && !general.isEmpty()) { return toMetaAttributes(general); } @@ -538,11 +546,11 @@ protected Map tableToMetaAttributes(TableIdentifier identi */ } - private Map findGeneralAttributes(TableIdentifier identifier) { + private MultiValuedMap findGeneralAttributes(TableIdentifier identifier) { Iterator iterator = tableFilters.iterator(); while(iterator.hasNext() ) { TableFilter tf = iterator.next(); - Map value = tf.getMetaAttributes(identifier); + MultiValuedMap value = tf.getMetaAttributes(identifier); if(value!=null) { return value; } @@ -550,20 +558,15 @@ private Map findGeneralAttributes(TableIdentifier identifier) { return null; } - private Map toMetaAttributes(Map value) { + private Map toMetaAttributes(MultiValuedMap mvm) { Map result = new HashMap(); - - Set set = value.entrySet(); - for (Iterator iter = set.iterator(); iter.hasNext();) { - Entry entry = (Entry)iter.next(); - String name = (String) entry.getKey(); - List values = (List) entry.getValue(); - - result.put(name, MetaAttributeBinder.toRealMetaAttribute(name, values)); + for (MapIterator iter = mvm.mapIterator(); iter.hasNext();) { + String key = iter.next(); + Collection values = mvm.get(key); + result.put(key, MetaAttributeHelper.toRealMetaAttribute(key, values)); } - return result; - } + } public ReverseEngineeringStrategy getReverseEngineeringStrategy() { return getReverseEngineeringStrategy(null); @@ -704,14 +707,19 @@ public void addForeignKeyInfo(String constraintName, String toOneProperty, Boole } - public void addMetaAttributeInfo(Table table, MultiMap map) { + public void addMetaAttributeInfo( + Table table, + MultiValuedMap map) { if(map!=null && !map.isEmpty()) { tableMetaAttributes.put(TableIdentifier.create(table), map); } } - public void addMetaAttributeInfo(TableIdentifier tableIdentifier, String name, MultiMap map) { + public void addMetaAttributeInfo( + TableIdentifier tableIdentifier, + String name, + MultiValuedMap map) { if(map!=null && !map.isEmpty()) { columnMetaAttributes.put(new TableColumnKey( tableIdentifier, name ), map); } diff --git a/main/src/main/java/org/hibernate/cfg/reveng/PrimaryKeyProcessor.java b/main/src/main/java/org/hibernate/cfg/reveng/PrimaryKeyProcessor.java index 2139b3fb1b..f48cd66fe1 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/PrimaryKeyProcessor.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/PrimaryKeyProcessor.java @@ -14,12 +14,11 @@ import org.hibernate.mapping.PrimaryKey; import org.hibernate.mapping.Table; import org.hibernate.sql.Alias; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class PrimaryKeyProcessor { - private static final Logger log = LoggerFactory.getLogger(PrimaryKeyProcessor.class); + private static final Logger log = Logger.getLogger(PrimaryKeyProcessor.class); public static void processPrimaryKey( MetaDataDialect metaDataDialect, diff --git a/main/src/main/java/org/hibernate/cfg/reveng/SimpleMetaAttribute.java b/main/src/main/java/org/hibernate/cfg/reveng/SimpleMetaAttribute.java deleted file mode 100644 index a5d6e00d68..0000000000 --- a/main/src/main/java/org/hibernate/cfg/reveng/SimpleMetaAttribute.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.hibernate.cfg.reveng; - -public class SimpleMetaAttribute { - String value; - boolean inheritable = true; - - public SimpleMetaAttribute(String value, boolean inherit) { - this.value = value; - this.inheritable = inherit; - } - - public String toString() { - return value; - } - -} - diff --git a/main/src/main/java/org/hibernate/cfg/reveng/TableFilter.java b/main/src/main/java/org/hibernate/cfg/reveng/TableFilter.java index d634cf1475..55fce363ca 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/TableFilter.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/TableFilter.java @@ -1,6 +1,7 @@ package org.hibernate.cfg.reveng; -import java.util.Map; +import org.apache.commons.collections4.MultiValuedMap; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper.SimpleMetaAttribute; /** @@ -73,7 +74,7 @@ public String toString() { private Matcher catalogMatcher; private Matcher schemaMatcher; private Matcher nameMatcher; - private Map metaAttributes; + private MultiValuedMap metaAttributes; @@ -147,11 +148,11 @@ public Boolean getExclude() { return exclude; } - public Map getMetaAttributes(TableIdentifier identifier) { + public MultiValuedMap getMetaAttributes(TableIdentifier identifier) { return isRelevantFor(identifier) ? metaAttributes : null; } - public void setMetaAttributes(Map metaAttributes) { + public void setMetaAttributes(MultiValuedMap metaAttributes) { this.metaAttributes = metaAttributes; } } diff --git a/main/src/main/java/org/hibernate/cfg/reveng/TableProcessor.java b/main/src/main/java/org/hibernate/cfg/reveng/TableProcessor.java index d8d5f5d6ba..d247fe3921 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/TableProcessor.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/TableProcessor.java @@ -11,12 +11,11 @@ import org.hibernate.cfg.reveng.dialect.MetaDataDialect; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Table; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class TableProcessor { - private static final Logger log = LoggerFactory.getLogger(TableProcessor.class); + private static final Logger log = Logger.getLogger(TableProcessor.class); public static Collection processTables( MetaDataDialect metaDataDialect, diff --git a/main/src/main/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java b/main/src/main/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java index 4bf846082b..d0af8d759a 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/dialect/AbstractMetaDataDialect.java @@ -14,8 +14,7 @@ import org.hibernate.cfg.JDBCBinderException; import org.hibernate.cfg.reveng.ReverseEngineeringRuntimeInfo; import org.hibernate.exception.spi.SQLExceptionConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; /** * abstract base class for the metadatadialects to hold the @@ -26,7 +25,7 @@ */ public abstract class AbstractMetaDataDialect implements MetaDataDialect { - protected final Logger log = LoggerFactory.getLogger(this.getClass()); + protected final Logger log = Logger.getLogger(this.getClass()); private Connection connection; private DatabaseMetaData metaData; diff --git a/main/src/main/java/org/hibernate/cfg/reveng/dialect/H2MetaDataDialect.java b/main/src/main/java/org/hibernate/cfg/reveng/dialect/H2MetaDataDialect.java index 663f27e600..729c578d5e 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/dialect/H2MetaDataDialect.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/dialect/H2MetaDataDialect.java @@ -7,7 +7,6 @@ import java.util.Iterator; import java.util.Map; -import org.hibernate.internal.util.StringHelper; import org.hibernate.tool.util.ReflectHelper; @@ -19,8 +18,44 @@ */ public class H2MetaDataDialect extends JDBCMetaDataDialect { + private static final String SPKSQ_H2_1_X = + "SELECT " + + " idx.TABLE_CATALOG TABLE_CAT, " + + " idx.TABLE_SCHEMA TABLE_SCHEM, " + + " idx.TABLE_NAME, " + + " idx.COLUMN_NAME " + + "FROM " + + " INFORMATION_SCHEMA.INDEXES idx, " + + " INFORMATION_SCHEMA.COLUMNS cols " + + "WHERE " + + " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + + " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + + " idx.TABLE_NAME = cols.TABLE_NAME AND " + + " idx.PRIMARY_KEY = TRUE AND " + + " cols.COLUMN_DEFAULT like '%NEXT VALUE FOR%' "; + + private static final String SPKSQ_H2_2_X = + "SELECT " + + " idx.TABLE_CATALOG TABLE_CAT, " + + " idx.TABLE_SCHEMA TABLE_SCHEM, " + + " idx.TABLE_NAME, " + + " cols.COLUMN_NAME " + + "FROM " + + " INFORMATION_SCHEMA.INDEXES idx, " + + " INFORMATION_SCHEMA.INDEX_COLUMNS idx_cols, " + + " INFORMATION_SCHEMA.COLUMNS cols " + + "WHERE " + + " idx.TABLE_CATALOG = cols.TABLE_CATALOG AND " + + " idx.TABLE_SCHEMA = cols.TABLE_SCHEMA AND " + + " idx.TABLE_NAME = cols.TABLE_NAME AND " + + " idx.INDEX_TYPE_NAME = 'PRIMARY KEY' AND " + + " cols.COLUMN_NAME = idx_cols.COLUMN_NAME AND " + + " cols.IS_IDENTITY = 'YES'"; + private static boolean understandsCatalogName = true; + private String suggested_primary_key_strategy_query = null; + public H2MetaDataDialect() { super(); try { @@ -29,12 +64,21 @@ public H2MetaDataDialect() { if ( build.intValue() < 55 ) { understandsCatalogName = false; } + suggested_primary_key_strategy_query = build.intValue() > 200 ? SPKSQ_H2_2_X : SPKSQ_H2_1_X; } catch( Throwable e ) { // ignore (probably H2 not in the classpath) } } + protected void putTableType(Map element, ResultSet tableRs) throws SQLException { + String tableType = tableRs.getString("TABLE_TYPE"); + if ("BASE TABLE".equals(tableType)) { + tableType = "TABLE"; + } + element.put("TABLE_TYPE", tableType); + } + protected void putTablePart(Map element, ResultSet tableRs) throws SQLException { super.putTablePart( element, tableRs ); if ( !understandsCatalogName ) { @@ -57,14 +101,7 @@ public Iterator> getSuggestedPrimaryKeyStrategyName(String c log.debug("geSuggestedPrimaryKeyStrategyName(" + catalog + "." + schema + "." + table + ")"); - String sql = "SELECT idx.TABLE_CATALOG TABLE_CAT, idx.TABLE_SCHEMA TABLE_SCHEM, idx.TABLE_NAME, idx.COLUMN_NAME, cols.COLUMN_DEFAULT COLUMN_DEFAULT FROM " + - "INFORMATION_SCHEMA.INDEXES idx, INFORMATION_SCHEMA.COLUMNS cols " + - "WHERE " + - "idx.TABLE_CATALOG = cols.TABLE_CATALOG " + - "and idx.TABLE_SCHEMA = cols.TABLE_SCHEMA " + - "and idx.TABLE_NAME = cols.TABLE_NAME " + - "AND idx.PRIMARY_KEY = TRUE " + - "AND COLUMN_DEFAULT like '%NEXT VALUE FOR%' "; + String sql = suggested_primary_key_strategy_query; if(catalog!=null) { sql += "AND idx.TABLE_CATALOG like '" + catalog + "' "; } @@ -83,8 +120,7 @@ public Iterator> getSuggestedPrimaryKeyStrategyName(String c protected Map convertRow(ResultSet tableRs) throws SQLException { element.clear(); putTablePart( element, tableRs ); - String string = tableRs.getString("COLUMN_DEFAULT"); - element.put("HIBERNATE_STRATEGY", StringHelper.isEmpty( string )?null:"identity"); + element.put("HIBERNATE_STRATEGY", "identity"); return element; } protected Throwable handleSQLException(SQLException e) { diff --git a/main/src/main/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java b/main/src/main/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java index bec184a2d5..1f10c5fdcb 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/dialect/JDBCMetaDataDialect.java @@ -32,7 +32,7 @@ public Iterator> getTables(String xcatalog, String xschema, S protected Map convertRow(ResultSet tableResultSet) throws SQLException { element.clear(); putTablePart( element, tableResultSet ); - element.put("TABLE_TYPE", tableResultSet.getString("TABLE_TYPE")); + putTableType(element, tableResultSet); element.put("REMARKS", tableResultSet.getString("REMARKS")); return element; } @@ -88,6 +88,10 @@ protected void putTablePart(Map element, ResultSet tableRs) thro element.put("TABLE_CAT", tableRs.getString("TABLE_CAT")); } + protected void putTableType(Map element, ResultSet tableRs) throws SQLException { + element.put("TABLE_TYPE", tableRs.getString("TABLE_TYPE")); + } + public Iterator> getColumns(final String xcatalog, final String xschema, final String xtable, String xcolumn) { try { final String catalog = caseForSearch( xcatalog ); diff --git a/main/src/main/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java b/main/src/main/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java index e0a7736b52..33b8dd8a8a 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/dialect/OracleMetaDataDialect.java @@ -17,6 +17,7 @@ * * @author David Channon * @author Eric Kershner (added preparedstatements HBX-817) + * @author Jacques Stadler (added HBX-1027) * */ @@ -30,9 +31,13 @@ public OracleMetaDataDialect() { /* ******* TABLE QUERIES ******* */ private static final String SQL_TABLE_BASE = - "select a.table_name, a.owner, b.comments, 'TABLE' " - + "from all_tables a left join all_tab_comments b " - + "on (a.owner=b.owner and a.table_name=b.table_name) "; + "select a.table_name, a.owner, " + + "(SELECT b.comments\n" + + " FROM all_tab_comments b\n" + + " WHERE a.owner = b.owner\n" + + " AND a.table_name = b.table_name) AS comments, " + + "'TABLE' " + + "from all_tables a "; private static final String SQL_TABLE_VIEW = " union all select view_name, owner, NULL, 'VIEW' from all_views "; @@ -45,9 +50,11 @@ public OracleMetaDataDialect() { private static final String SQL_TABLE_TABLE = SQL_TABLE_BASE + "where a.table_name like ?" + SQL_TABLE_VIEW + "where view_name like ?"; - private static final String SQL_TABLE_SCHEMA_AND_TABLE = SQL_TABLE_BASE - + "where a.owner like ? and a.table_name like ?" + SQL_TABLE_VIEW - + "where owner like ? and view_name like ?"; + private static final String SQL_TABLE_SCHEMA_AND_TABLE = + SQL_TABLE_BASE + + "where a.owner like ? and a.table_name like ?" + + SQL_TABLE_VIEW + + "where owner like ? and view_name like ?"; private PreparedStatement prepTableNone; @@ -60,13 +67,19 @@ public OracleMetaDataDialect() { /* ***************************** */ /* ******* INDEX QUERIES ******* */ /* ***************************** */ - private static final String SQL_INDEX_BASE = "select a.column_name, " - + "decode(b.uniqueness,'UNIQUE','false','true'), " - + "a.index_owner, a.index_name, a.table_name " - + "from all_ind_columns a left join all_indexes b on " - + "(a.table_name = b.table_name " - + " AND a.table_owner = b.table_owner " - + " AND a.index_name = b.index_name) "; + private static final String SQL_INDEX_BASE = + "SELECT a.column_name\n" + + " ,decode((SELECT b.uniqueness\n" + + " FROM all_indexes b\n" + + " WHERE a.table_name = b.table_name\n" + + " AND a.table_owner = b.table_owner\n" + + " AND a.index_name = b.index_name\n" + + " AND b.index_type NOT LIKE 'FUNCTION-BASED%'), 'UNIQUE', 'false', 'true') AS uniqueness\n" + + " ,a.index_owner\n" + + " ,a.index_name\n" + + " ,a.table_name\n" + + " FROM all_ind_columns a\n " + + " WHERE 1 = 1\n "; private static final String SQL_INDEX_ORDER = " order by a.table_name, a.column_position"; @@ -74,13 +87,13 @@ public OracleMetaDataDialect() { + SQL_INDEX_ORDER; private static final String SQL_INDEX_SCHEMA = SQL_INDEX_BASE - + "where a.table_owner like ? " + SQL_INDEX_ORDER; + + "and a.table_owner like ? " + SQL_INDEX_ORDER; private static final String SQL_INDEX_TABLE = SQL_INDEX_BASE - + "where a.table_name like ? " + SQL_INDEX_ORDER; + + "and a.table_name like ? " + SQL_INDEX_ORDER; private static final String SQL_INDEX_SCHEMA_AND_TABLE = SQL_INDEX_BASE - + "where a.table_owner like ? and a.table_name like ? " + SQL_INDEX_ORDER; + + "and a.table_owner like ? and a.table_name like ? " + SQL_INDEX_ORDER; private PreparedStatement prepIndexNone; @@ -91,20 +104,30 @@ public OracleMetaDataDialect() { private PreparedStatement prepIndexSchemaAndTable; /* ****** COLUMN QUERIES ******* */ - private static final String SQL_COLUMN_BASE = "select a.column_name as COLUMN_NAME, a.owner as TABLE_SCHEM, " - + "decode(a.nullable,'N',0,1) as NULLABLE, " - + "decode(a.data_type, 'FLOAT',decode(a.data_precision,null, " - + "a.data_length, a.data_precision), 'NUMBER', decode(a.data_precision,null, " - + "a.data_length, a.data_precision), a.data_length) as COLUMN_SIZE, " - + "decode(a.data_type,'CHAR',1, 'DATE',91, 'FLOAT',6, " - + "'LONG',-1, 'NUMBER',2, 'VARCHAR2',12, 'BFILE',-13, " - + "'BLOB',2004, 'CLOB',2005, 'MLSLABEL',1111, 'NCHAR',1, 'NCLOB',2005, 'NVARCHAR2',12, " - + "'RAW',-3, 'ROWID',1111, 'UROWID',1111, 'LONG RAW', -4, " - + "'TIMESTAMP', 93, 'TIMESTAMP(6)', 93, 'XMLTYPE',2005, 1111) as DATA_TYPE, " - + "a.table_name as TABLE_NAME, a.data_type as TYPE_NAME, " - + "decode(a.data_scale, null, 0 ,a.data_scale) as DECIMAL_DIGITS, b.comments " - + "from all_tab_columns a left join all_col_comments b on " - + "(a.owner=b.owner and a.table_name=b.table_name and a.column_name=b.column_name) "; + private static final String SQL_COLUMN_BASE = + "SELECT a.column_name AS COLUMN_NAME\n" + + " ,a.owner AS TABLE_SCHEM\n" + + " ,decode(a.nullable, 'N', 0, 1) AS NULLABLE\n" + + " ,decode(a.data_type, 'FLOAT', decode(a.data_precision, NULL, a.data_length, a.data_precision), 'NUMBER',\n" + + " decode(a.data_precision, NULL, a.data_length, a.data_precision), 'VARCHAR2', a.char_length, 'VARCHAR',\n" + + " a.char_length, 'NVARCHAR2', a.char_length, 'CHAR', a.char_length, 'NCHAR', a.char_length, a.data_length) AS COLUMN_SIZE\n" + + " ,CASE\n" + + " WHEN a.data_type LIKE 'TIMESTAMP%' THEN\n" + + " 93\n" + + " ELSE\n" + + " decode(a.data_type, 'CHAR', 1, 'DATE', 91, 'FLOAT', 6, 'LONG', -1, 'NUMBER', 2, 'VARCHAR2', 12, 'BFILE', -13,\n" + + " 'BLOB', 2004, 'CLOB', 2005, 'MLSLABEL', 1111, 'NCHAR', 1, 'NCLOB', 2005, 'NVARCHAR2', 12, 'RAW', -3,\n" + + " 'ROWID', 1111, 'UROWID', 1111, 'LONG RAW', -4, 'XMLTYPE', 2005, 1111)\n" + + " END AS DATA_TYPE\n" + + " ,a.table_name AS TABLE_NAME\n" + + " ,a.data_type AS TYPE_NAME\n" + + " ,decode(a.data_scale, NULL, 0, a.data_scale) AS DECIMAL_DIGITS\n" + + " ,(SELECT b.comments\n" + + " FROM all_col_comments b\n" + + " WHERE a.owner = b.owner\n" + + " AND a.table_name = b.table_name\n" + + " AND a.column_name = b.column_name) AS COMMENTS\n" + + " FROM all_tab_columns a\n"; private static final String SQL_COLUMN_ORDER = " order by column_id "; @@ -153,8 +176,9 @@ public OracleMetaDataDialect() { /* ***************************** */ /* ******** PK QUERIES ********* */ /* ***************************** */ - private static final String SQL_PK_BASE = "select c.table_name, c.column_name, c.position, c.constraint_name, " - + "c.owner from all_cons_columns c left join all_constraints k on " + private static final String SQL_PK_BASE = + "select c.table_name, c.column_name, c.position, c.constraint_name, " + + "c.owner from all_cons_columns c join all_constraints k on " + "(k.owner = c.owner AND k.table_name = c.table_name AND k.constraint_name = c.constraint_name) " + "where k.constraint_type = 'P' "; @@ -182,16 +206,37 @@ public OracleMetaDataDialect() { /* ***************************** */ /* ******** FK QUERIES ********* */ /* ***************************** */ - private static final String SQL_FK_BASE = "select p.table_name, p.owner, f.owner, f.table_name, " - + "fc.column_name, pc.column_name, f.constraint_name, fc.position " - + "from all_constraints p left join all_cons_columns pc on " - + "(pc.owner = p.owner and pc.constraint_name = p.constraint_name and pc.table_name = p.table_name) " - + "left join all_constraints f on (p.owner = f.r_owner and p.constraint_name = f.r_constraint_name) " - + "left join all_cons_columns fc on " - + "(fc.owner = f.owner and fc.constraint_name = f.constraint_name and fc.table_name = f.table_name and" - + " fc.position = pc.position) where f.constraint_type = 'R' AND p.constraint_type = 'P' "; - - private static final String SQL_FK_ORDER = " order by f.table_name, f.constraint_name, fc.position "; + private static final String SQL_FK_BASE = + "SELECT p.table_name as p_table_name\n" + + " ,p.owner as p_owner\n" + + " ,f.owner as f_owner\n" + + " ,f.table_name as f_table_name\n" + + " ,(SELECT fc.column_name\n" + + " FROM all_cons_columns fc\n" + + " WHERE fc.owner = f.owner\n" + + " AND fc.constraint_name = f.constraint_name\n" + + " AND fc.table_name = f.table_name\n" + + " AND fc.position = pc.position) AS fc_column_name\n" + + " ,pc.column_name as pc_column_name\n" + + " ,f.constraint_name\n" + + " ,(SELECT fc.position\n" + + " FROM all_cons_columns fc\n" + + " WHERE fc.owner = f.owner\n" + + " AND fc.constraint_name = f.constraint_name\n" + + " AND fc.table_name = f.table_name\n" + + " AND fc.position = pc.position) AS fc_position\n" + + " FROM all_constraints p\n" + + " JOIN all_cons_columns pc\n" + + " ON pc.owner = p.owner\n" + + " AND pc.constraint_name = p.constraint_name\n" + + " AND pc.table_name = p.table_name\n" + + " JOIN all_constraints f\n" + + " ON p.owner = f.r_owner\n" + + " AND p.constraint_name = f.r_constraint_name\n" + + " WHERE f.constraint_type = 'R'\n" + + " AND p.constraint_type = 'P'\n"; + + private static final String SQL_FK_ORDER = " order by f.table_name, f.constraint_name, position "; private static final String SQL_FK_NONE = SQL_FK_BASE + SQL_FK_ORDER; @@ -217,8 +262,7 @@ public Iterator> getTables(final String catalog, final String try { log.debug("getTables(" + catalog + "." + schema + "." + table + ")"); - ResultSet tableRs; - tableRs = getTableResultSet( schema, table ); + ResultSet tableRs = getTableResultSet( schema, table ); return new ResultSetIterator(null, tableRs, getSQLExceptionConverter()) { @@ -233,7 +277,7 @@ protected Map convertRow(ResultSet tableResultSet) element.put("TABLE_SCHEM", tableResultSet.getString(2)); element.put("TABLE_CAT", null); element.put("TABLE_TYPE", tableResultSet.getString(4)); - element.put("REMARKS", tableResultSet.getString(3)); + element.put("REMARKS", tableResultSet.getString(3)); log.info( element.toString() ); return element; } @@ -301,7 +345,7 @@ protected Throwable handleSQLException(SQLException e) { throw getSQLExceptionConverter().convert( e, "Exception while getting index info for " - + TableNameQualifier.qualify(catalog, schema, table), null); + + TableNameQualifier.qualify(catalog, schema, table) + ": " + e.getMessage(), null); } } @@ -401,8 +445,7 @@ public Iterator> getExportedKeys(final String catalog, final log.debug("getExportedKeys(" + catalog + "." + schema + "." + table + ")"); - ResultSet pExportRs; - pExportRs = getExportedKeysResultSet( schema, table ); + ResultSet pExportRs = getExportedKeysResultSet( schema, table ); return new ResultSetIterator(null, pExportRs, getSQLExceptionConverter()) { @@ -565,8 +608,7 @@ private ResultSet getExportedKeysResultSet(final String schema, final String tab prepFkNone = con .prepareStatement(SQL_FK_NONE); prepFkSchema = con.prepareStatement(SQL_FK_SCHEMA); prepFkTable = con.prepareStatement(SQL_FK_TABLE); - prepFkSchemaAndTable = con - .prepareStatement(SQL_FK_SCHEMA_AND_TABLE); + prepFkSchemaAndTable = con.prepareStatement(SQL_FK_SCHEMA_AND_TABLE); log.debug(" foreign key queries prepared!"); } diff --git a/main/src/main/java/org/hibernate/cfg/reveng/dialect/SQLServerMetaDataDialect.java b/main/src/main/java/org/hibernate/cfg/reveng/dialect/SQLServerMetaDataDialect.java index 0740b24c32..46ee0f08df 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/dialect/SQLServerMetaDataDialect.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/dialect/SQLServerMetaDataDialect.java @@ -26,7 +26,7 @@ public Iterator> getSuggestedPrimaryKeyStrategyName(String c sql = "SELECT a.TABLE_CATALOG, a.TABLE_SCHEMA, a.TABLE_NAME as table_name, c.DATA_TYPE as data_type, b.CONSTRAINT_TYPE, OBJECTPROPERTY(OBJECT_ID(a.TABLE_NAME),'TableHasIdentity') as hasIdentity " + "FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE a " + "INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS b on a.CONSTRAINT_NAME = b.CONSTRAINT_NAME " + - "INNER JOIN INFORMATION_SCHEMA.Columns c on a.TABLE_CATALOG = c.TABLE_CATALOG AND a.TABLE_SCHEMA = c.TABLE_SCHEMA AND a.TABLE_NAME = c.TABLE_NAME AND a.COLUMN_NAME = c.COLUMN_NAME " + + "INNER JOIN INFORMATION_SCHEMA.COLUMNS c on a.TABLE_CATALOG = c.TABLE_CATALOG AND a.TABLE_SCHEMA = c.TABLE_SCHEMA AND a.TABLE_NAME = c.TABLE_NAME AND a.COLUMN_NAME = c.COLUMN_NAME " + "WHERE a.TABLE_NAME='"+table+"' AND a.TABLE_SCHEMA='"+schema+"' AND a.TABLE_CATALOG='"+catalog+"' AND b.CONSTRAINT_TYPE = 'Primary key'"; PreparedStatement statement = getConnection().prepareStatement( sql ); diff --git a/main/src/main/java/org/hibernate/cfg/reveng/JDBCToHibernateTypeHelper.java b/main/src/main/java/org/hibernate/cfg/reveng/utils/JdbcToHibernateTypeHelper.java similarity index 53% rename from main/src/main/java/org/hibernate/cfg/reveng/JDBCToHibernateTypeHelper.java rename to main/src/main/java/org/hibernate/cfg/reveng/utils/JdbcToHibernateTypeHelper.java index b8c78aaf64..0d03569032 100644 --- a/main/src/main/java/org/hibernate/cfg/reveng/JDBCToHibernateTypeHelper.java +++ b/main/src/main/java/org/hibernate/cfg/reveng/utils/JdbcToHibernateTypeHelper.java @@ -1,4 +1,4 @@ -package org.hibernate.cfg.reveng; +package org.hibernate.cfg.reveng.utils; import java.lang.reflect.Field; import java.lang.reflect.Modifier; @@ -16,9 +16,9 @@ * @author max (based on parts from Sql2Java from Middlegen) * */ -public final class JDBCToHibernateTypeHelper { +public final class JdbcToHibernateTypeHelper { - private JDBCToHibernateTypeHelper() { + private JdbcToHibernateTypeHelper() { } @@ -26,28 +26,28 @@ private JDBCToHibernateTypeHelper() { private static final Map PREFERRED_HIBERNATETYPE_FOR_SQLTYPE = new HashMap(); static { - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.TINYINT), new String[] { "byte", Byte.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.SMALLINT), new String[] { "short", Short.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.INTEGER), new String[] { "int", Integer.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.BIGINT), new String[] { "long", Long.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.REAL), new String[] { "float", Float.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.FLOAT), new String[] { "double", Double.class.getName()} ); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.DOUBLE), new String[] { "double", Double.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.DECIMAL), new String[] { "big_decimal", "big_decimal" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.NUMERIC), new String[] { "big_decimal", "big_decimal" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.BIT), new String[] { "boolean", Boolean.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.BOOLEAN), new String[] { "boolean", Boolean.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.CHAR), new String[] { "char", Character.class.getName()}); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.VARCHAR), new String[] { "string", "string" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.LONGVARCHAR), new String[] { "string", "string" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.BINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.VARBINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.LONGVARBINARY), new String[] { "binary", "binary" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.DATE), new String[] { "date", "date" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.TIME), new String[] { "time", "time" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.TIMESTAMP), new String[] { "timestamp", "timestamp" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.CLOB), new String[] { "clob", "clob" }); - PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(new Integer(Types.BLOB), new String[] { "blob", "blob" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TINYINT), new String[] { "byte", Byte.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.SMALLINT), new String[] { "short", Short.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.INTEGER), new String[] { "int", Integer.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BIGINT), new String[] { "long", Long.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.REAL), new String[] { "float", Float.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.FLOAT), new String[] { "double", Double.class.getName()} ); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DOUBLE), new String[] { "double", Double.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DECIMAL), new String[] { "big_decimal", "big_decimal" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.NUMERIC), new String[] { "big_decimal", "big_decimal" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BIT), new String[] { "boolean", Boolean.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BOOLEAN), new String[] { "boolean", Boolean.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.CHAR), new String[] { "char", Character.class.getName()}); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.VARCHAR), new String[] { "string", "string" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.LONGVARCHAR), new String[] { "string", "string" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BINARY), new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.VARBINARY), new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.LONGVARBINARY), new String[] { "binary", "binary" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.DATE), new String[] { "date", "date" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TIME), new String[] { "time", "time" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.TIMESTAMP), new String[] { "timestamp", "timestamp" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.CLOB), new String[] { "clob", "clob" }); + PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.put(Integer.valueOf(Types.BLOB), new String[] { "blob", "blob" }); //Hibernate does not have any built-in Type for these: //preferredJavaTypeForSqlType.put(new Integer(Types.ARRAY), "java.sql.Array"); @@ -79,7 +79,7 @@ else if (precision < 19) { return returnNullable?Long.class.getName():"long"; } else { - return "big_decimal"; + return "big_integer"; } } @@ -87,7 +87,7 @@ else if (precision < 19) { return "string"; } - String[] result = (String[]) PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.get(new Integer(sqlType) ); + String[] result = (String[]) PREFERRED_HIBERNATETYPE_FOR_SQLTYPE.get(Integer.valueOf(sqlType) ); if(result==null) { return null; @@ -166,7 +166,7 @@ public static String getJDBCTypeName(int value) { } } - String name = (String) jdbcTypeValues.get(new Integer(value) ); + String name = (String) jdbcTypeValues.get(Integer.valueOf(value) ); if(name!=null) { return name; @@ -183,17 +183,25 @@ public static String getJDBCTypeName(int value) { * @throws SQLException */ - // scale and precision have numeric column - public static boolean typeHasScaleAndPrecision(int sqlType) { - return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC - || sqlType == Types.REAL || sqlType == Types.FLOAT || sqlType == Types.DOUBLE); - } - - // length is for string column - public static boolean typeHasLength(int sqlType) { - return (sqlType == Types.CHAR || sqlType == Types.DATE - || sqlType == Types.LONGVARCHAR || sqlType == Types.TIME || sqlType == Types.TIMESTAMP - || sqlType == Types.VARCHAR ); - } -} + // scale is for non floating point numeric columns + public static boolean typeHasScale(int sqlType) { + return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC); + } + + // precision is for numeric columns + public static boolean typeHasPrecision(int sqlType) { + return (sqlType == Types.DECIMAL || sqlType == Types.NUMERIC + || sqlType == Types.REAL || sqlType == Types.FLOAT || sqlType == Types.DOUBLE); + } + public static boolean typeHasScaleAndPrecision(int sqlType) { + return typeHasScale(sqlType) && typeHasPrecision(sqlType); + } + + // length is for string columns + public static boolean typeHasLength(int sqlType) { + return (sqlType == Types.CHAR || sqlType == Types.DATE + || sqlType == Types.LONGVARCHAR || sqlType == Types.TIME || sqlType == Types.TIMESTAMP + || sqlType == Types.VARCHAR ); + } +} diff --git a/main/src/main/java/org/hibernate/cfg/reveng/utils/MetaAttributeHelper.java b/main/src/main/java/org/hibernate/cfg/reveng/utils/MetaAttributeHelper.java new file mode 100644 index 0000000000..4f8fb0ad41 --- /dev/null +++ b/main/src/main/java/org/hibernate/cfg/reveng/utils/MetaAttributeHelper.java @@ -0,0 +1,131 @@ +package org.hibernate.cfg.reveng.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.collections4.MultiValuedMap; +import org.apache.commons.collections4.multimap.HashSetValuedHashMap; +import org.hibernate.mapping.MetaAttribute; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +public class MetaAttributeHelper { + + public static MetaAttribute toRealMetaAttribute(String name, Collection values) { + MetaAttribute attribute = new MetaAttribute(name); + for (Iterator iter = values.iterator(); iter.hasNext();) { + SimpleMetaAttribute element = (SimpleMetaAttribute) iter.next(); + attribute.addValue(element.value); + } + + return attribute; + } + + + public static MultiValuedMap loadAndMergeMetaMap( + Element classElement, + MultiValuedMap inheritedMeta) { + return MetaAttributeHelper.mergeMetaMaps( + loadMetaMap(classElement), + inheritedMeta); + } + + public static MultiValuedMap loadMetaMap(Element element) { + MultiValuedMap result = new HashSetValuedHashMap(); + List metaAttributeList = new ArrayList(); + ArrayList metaNodes = getChildElements(element, "meta"); + for (Element metaNode : metaNodes) { + metaAttributeList.add(metaNode); + } + for (Iterator iter = metaAttributeList.iterator(); iter.hasNext();) { + Element metaAttribute = iter.next(); + String attribute = metaAttribute.getAttribute("attribute"); + String value = metaAttribute.getTextContent(); + String inheritStr= null; + if (metaAttribute.hasAttribute("inherit")) { + inheritStr = metaAttribute.getAttribute("inherit"); + } + boolean inherit = true; + if(inheritStr!=null) { + inherit = Boolean.valueOf(inheritStr).booleanValue(); + } + SimpleMetaAttribute ma = new SimpleMetaAttribute(value, inherit); + result.put(attribute, ma); + } + return result; + } + + /** + * Merges a Multimap with inherited maps. + * Values specified always overrules/replaces the inherited values. + * + * @param specific + * @param general + * @return a MultiMap with all values from local and extra values + * from inherited + */ + private static MultiValuedMap mergeMetaMaps( + MultiValuedMap specific, + MultiValuedMap general) { + MultiValuedMap result = new HashSetValuedHashMap(); + copyMultiMap(result, specific); + if (general != null) { + for (Iterator iter = general.keySet().iterator();iter.hasNext();) { + String key = iter.next(); + if (!specific.containsKey(key) ) { + // inheriting a meta attribute only if it is inheritable + Collection ml = general.get(key); + for (Iterator iterator = ml.iterator(); iterator.hasNext();) { + SimpleMetaAttribute element = iterator.next(); + if (element.inheritable) { + result.put(key, element); + } + } + } + } + } + + return result; + + } + + private static void copyMultiMap( + MultiValuedMap destination, + MultiValuedMap specific) { + for (Iterator keyIterator = specific.keySet().iterator(); keyIterator.hasNext(); ) { + String key = keyIterator.next(); + Collection c = specific.get(key); + for (Iterator valueIterator = c.iterator(); valueIterator.hasNext(); ) + destination.put(key, valueIterator.next() ); + } + } + + private static ArrayList getChildElements(Element parent, String tagName) { + ArrayList result = new ArrayList(); + NodeList nodeList = parent.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node instanceof Element) { + if (tagName.equals(((Element)node).getTagName())) { + result.add((Element)node); + } + } + } + return result; + } + + public static class SimpleMetaAttribute { + String value; + boolean inheritable = true; + public SimpleMetaAttribute(String value, boolean inherit) { + this.value = value; + this.inheritable = inherit; + } + public String toString() { + return value; + } + } +} diff --git a/main/src/main/java/org/hibernate/cfg/reveng/utils/RevengUtils.java b/main/src/main/java/org/hibernate/cfg/reveng/utils/RevengUtils.java new file mode 100644 index 0000000000..0903bf9b07 --- /dev/null +++ b/main/src/main/java/org/hibernate/cfg/reveng/utils/RevengUtils.java @@ -0,0 +1,32 @@ +package org.hibernate.cfg.reveng.utils; + +import org.hibernate.cfg.reveng.AssociationInfo; + +public class RevengUtils { + + public static AssociationInfo createAssociationInfo( + String cascade, + String fetch, + Boolean insert, + Boolean update) { + return new AssociationInfo() { + @Override + public String getCascade() { + return cascade; + } + @Override + public String getFetch() { + return fetch; + } + @Override + public Boolean getUpdate() { + return update; + } + @Override + public Boolean getInsert() { + return insert; + } + + }; + } +} diff --git a/main/src/main/java/org/hibernate/tool/Version.java b/main/src/main/java/org/hibernate/tool/Version.java index 21e59a7dd0..12a0deb8cf 100644 --- a/main/src/main/java/org/hibernate/tool/Version.java +++ b/main/src/main/java/org/hibernate/tool/Version.java @@ -1,15 +1,14 @@ package org.hibernate.tool; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import java.util.logging.Logger; final public class Version { - public static final String VERSION = "6.0.0-SNAPSHOT"; - private static final Version instance = new Version(); - private static Log log = LogFactory.getLog( Version.class ); + public static final String VERSION = instance.versionString(); + + private static Logger log = Logger.getLogger( Version.class.getName() ); static { log.info( "Hibernate Tools " + VERSION ); @@ -23,6 +22,11 @@ public String getVersion() { return VERSION; } + public String versionString() { + // This implementation is replaced during the build with another one that returns the correct value. + return "UNKNOWN"; + } + public static Version getDefault() { return instance; } diff --git a/main/src/main/java/org/hibernate/tool/ant/HibernateToolTask.java b/main/src/main/java/org/hibernate/tool/ant/HibernateToolTask.java index 3b722c587b..d0251f6c95 100644 --- a/main/src/main/java/org/hibernate/tool/ant/HibernateToolTask.java +++ b/main/src/main/java/org/hibernate/tool/ant/HibernateToolTask.java @@ -305,7 +305,18 @@ public void addConfiguredPropertySet(PropertySet ps) { } public void addConfiguredProperty(Environment.Variable property) { - properties.put(property.getKey(), property.getValue()); + String key = property.getKey(); + String value = property.getValue(); + if (key==null) { + log( "Ignoring unnamed task property", Project.MSG_WARN ); + return; + } + if (value==null){ + //This is legal in ANT, make sure we warn properly: + log( "Ignoring task property '" +key+"' as no value was specified", Project.MSG_WARN ); + return; + } + properties.put( key, value ); } diff --git a/main/src/main/java/org/hibernate/tool/ant/JavaFormatterTask.java b/main/src/main/java/org/hibernate/tool/ant/JavaFormatterTask.java index 2bc3f93580..dc17ff7170 100644 --- a/main/src/main/java/org/hibernate/tool/ant/JavaFormatterTask.java +++ b/main/src/main/java/org/hibernate/tool/ant/JavaFormatterTask.java @@ -17,7 +17,7 @@ import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.hibernate.tool.hbm2x.ExporterException; -import org.hibernate.tool.ide.formatting.JavaFormatter; +import org.hibernate.tool.ide.formatting.DefaultJavaPrettyPrinterStrategy; public class JavaFormatterTask extends Task { @@ -72,7 +72,7 @@ public void execute() throws BuildException { if(files.length>0) { - JavaFormatter formatter = new JavaFormatter(settings); + DefaultJavaPrettyPrinterStrategy formatter = new DefaultJavaPrettyPrinterStrategy(settings); for (int i = 0; i < files.length; i++) { File file = files[i]; try { diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/AbstractExporter.java b/main/src/main/java/org/hibernate/tool/hbm2x/AbstractExporter.java index b52b64616f..0a84f87d6e 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/AbstractExporter.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/AbstractExporter.java @@ -12,8 +12,7 @@ import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.StringHelper; import org.hibernate.tool.api.metadata.MetadataDescriptor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; /** * Base exporter for the template and direct output generation. @@ -24,7 +23,7 @@ */ public abstract class AbstractExporter implements Exporter { - protected Logger log = LoggerFactory.getLogger(this.getClass()); + protected Logger log = Logger.getLogger(this.getClass()); private File outputdir; private String[] templatePaths = new String[0]; diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/Cfg2JavaTool.java b/main/src/main/java/org/hibernate/tool/hbm2x/Cfg2JavaTool.java index 21f0fac6cc..b75a57e2e0 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/Cfg2JavaTool.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/Cfg2JavaTool.java @@ -31,11 +31,9 @@ import org.hibernate.tool.hbm2x.pojo.POJOClass; import org.hibernate.tool.hbm2x.visitor.JavaTypeFromValueVisitor; import org.hibernate.type.BasicTypeRegistry; -import org.hibernate.type.PrimitiveType; import org.hibernate.type.Type; -import org.hibernate.type.TypeResolver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.hibernate.type.spi.TypeConfiguration; +import org.jboss.logging.Logger; /** * Helper methods for javacode generation. @@ -46,7 +44,7 @@ */ public class Cfg2JavaTool { - private static final Logger log = LoggerFactory.getLogger( Cfg2JavaTool.class ); + private static final Logger log = Logger.getLogger( Cfg2JavaTool.class ); public Cfg2JavaTool() { @@ -343,7 +341,9 @@ public String asFinderArgumentList(Map parameterTypes, ImportCont Type type = null; if(entry.getValue() instanceof String) { try { - type = new TypeResolver().heuristicType((String) entry.getValue()); + type = new TypeConfiguration() + .getBasicTypeRegistry() + .getRegisteredType((String) entry.getValue()); } catch(Throwable t) { type = null; typename = (String) entry.getValue(); @@ -351,14 +351,7 @@ public String asFinderArgumentList(Map parameterTypes, ImportCont } if(type!=null) { - Class typeClass; - if ( type instanceof PrimitiveType ) { - typeClass = ( (PrimitiveType) type ).getPrimitiveClass(); - } - else { - typeClass = type.getReturnedClass(); - } - typename = typeClass.getName(); + typename = type.getReturnedClass().getName(); } buf.append( ctx.importType( typename )) .append( " " ) diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/ConfigurationNavigator.java b/main/src/main/java/org/hibernate/tool/hbm2x/ConfigurationNavigator.java index 5e6ab355c9..82c8f49777 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/ConfigurationNavigator.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/ConfigurationNavigator.java @@ -12,15 +12,14 @@ import org.hibernate.mapping.Property; import org.hibernate.tool.hbm2x.pojo.ComponentPOJOClass; import org.hibernate.tool.hbm2x.pojo.POJOClass; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; /** * @author max and david */ public class ConfigurationNavigator { - private static final Logger log = LoggerFactory.getLogger(POJOExporter.class); + private static final Logger log = Logger.getLogger(POJOExporter.class); /** * @param clazz diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/DocExporter.java b/main/src/main/java/org/hibernate/tool/hbm2x/DocExporter.java index 63d4709b00..d31ea20adf 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/DocExporter.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/DocExporter.java @@ -177,12 +177,12 @@ private boolean generateDot() { File entityGraphDot = new File(getOutputDirectory(), "entities/entitygraph.dot"); dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.png").toString()); dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.svg").toString()); - dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.cmap").toString()); + dotToFile( cmd, entityGraphDot.toString(), new File(getOutputDirectory(), "entities/entitygraph.cmapx").toString()); File tableGraphDot = new File(getOutputDirectory(), "tables/tablegraph.dot"); dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.png").toString()); dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.svg").toString()); - dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.cmap").toString()); + dotToFile( cmd, tableGraphDot.toString(), new File(getOutputDirectory(), "tables/tablegraph.cmapx").toString()); return true; @@ -343,7 +343,7 @@ public void generateTablesSummary(boolean graphsGenerated) { parameters.put( "graphsGenerated", Boolean.valueOf( graphsGenerated ) ); if(graphsGenerated) { StringBuffer sb = new StringBuffer(); - String fileName = "tables/tablegraph.cmap"; + String fileName = "tables/tablegraph.cmapx"; appendFile( sb, fileName ); parameters.put( "tablegrapharea", sb ); } @@ -386,7 +386,7 @@ public void generatePackageSummary(boolean graphsGenerated){ parameters.put( "graphsGenerated", Boolean.valueOf( graphsGenerated ) ); if(graphsGenerated) { StringBuffer sb = new StringBuffer(); - String fileName = "entities/entitygraph.cmap"; + String fileName = "entities/entitygraph.cmapx"; appendFile( sb, fileName ); parameters.put( "entitygrapharea", sb ); } diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/MetaAttributeHelper.java b/main/src/main/java/org/hibernate/tool/hbm2x/MetaAttributeHelper.java index 83c6c47252..4567c4ee2c 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/MetaAttributeHelper.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/MetaAttributeHelper.java @@ -3,7 +3,8 @@ import java.util.Collection; import java.util.Iterator; -import org.apache.commons.collections.MultiMap; +import org.apache.commons.collections4.MultiValuedMap; +import org.hibernate.cfg.reveng.utils.MetaAttributeHelper.SimpleMetaAttribute; import org.hibernate.mapping.MetaAttribute; /** @@ -62,27 +63,18 @@ static String getMetaAsString(Collection c) { return getMetaAsString(c, ""); } - /** - * Copies all the values from one MultiMap to another. - * This method is needed because the (undocumented) behaviour of - * MultiHashMap.putAll in versions of Commons Collections prior to 3.0 - * was to replace the collection in the destination, whereas in 3.0 - * it adds the collection from the source as an _element_ of the collection - * in the destination. This method makes no assumptions about the implementation - * of the MultiMap, and should work with all versions. - * - * @param destination - * @param specific - */ - public static void copyMultiMap(MultiMap destination, MultiMap specific) { - for (Iterator keyIterator = specific.keySet().iterator(); keyIterator.hasNext(); ) { - Object key = keyIterator.next(); - Collection c = (Collection)specific.get(key); - for (Iterator valueIterator = c.iterator(); valueIterator.hasNext(); ) + public static void copyMultiMap( + MultiValuedMap destination, + MultiValuedMap specific) { + for (Iterator keyIterator = specific.keySet().iterator(); keyIterator.hasNext(); ) { + String key = keyIterator.next(); + Collection c = specific.get(key); + for (Iterator valueIterator = c.iterator(); valueIterator.hasNext();) { destination.put(key, valueIterator.next() ); + } } } - + public static boolean getMetaAsBool(org.hibernate.mapping.MetaAttribute metaAttribute, boolean defaultValue) { return getMetaAsBool(metaAttribute==null?null:metaAttribute.getValues(), defaultValue); } diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/TemplateHelper.java b/main/src/main/java/org/hibernate/tool/hbm2x/TemplateHelper.java index b0d931eafd..ea45e6b728 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/TemplateHelper.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/TemplateHelper.java @@ -17,8 +17,7 @@ import java.util.List; import org.hibernate.tool.Version; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.FileTemplateLoader; @@ -45,7 +44,7 @@ */ public class TemplateHelper { - static final Logger log = LoggerFactory.getLogger(TemplateHelper.class); + static final Logger log = Logger.getLogger(TemplateHelper.class); private String templatePrefix; private File outputDirectory; diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/TemplateProducer.java b/main/src/main/java/org/hibernate/tool/hbm2x/TemplateProducer.java index 50799eac08..5ef28015cb 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/TemplateProducer.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/TemplateProducer.java @@ -9,13 +9,12 @@ import java.util.Map; import java.util.Map.Entry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jboss.logging.Logger; public class TemplateProducer { - private static final Logger log = LoggerFactory.getLogger(TemplateProducer.class); + private static final Logger log = Logger.getLogger(TemplateProducer.class); private final TemplateHelper th; private ArtifactCollector ac; diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/pojo/BasicPOJOClass.java b/main/src/main/java/org/hibernate/tool/hbm2x/pojo/BasicPOJOClass.java index 76eceba71a..27437cd54e 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/pojo/BasicPOJOClass.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/pojo/BasicPOJOClass.java @@ -825,7 +825,9 @@ protected boolean isRequiredInConstructor(Property field) { return false; } if(field.getValue()!=null) { - if (!field.isOptional() && (field.getValueGenerationStrategy() == null || field.getValueGenerationStrategy().getGenerationTiming().equals(GenerationTiming.NEVER))) { + if (!(field.isOptional() || field.getValue().isNullable()) && + (field.getValueGenerationStrategy() == null || + field.getValueGenerationStrategy().getGenerationTiming().equals(GenerationTiming.NEVER))) { return true; } else if (field.getValue() instanceof Component) { Component c = (Component) field.getValue(); diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java b/main/src/main/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java index 9d701e1045..feab4cb949 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/pojo/EntityPOJOClass.java @@ -257,14 +257,14 @@ else if ( "sequence".equals( strategy ) ) { else if ( TableGenerator.class.getName().equals( strategy ) ) { builder.resetAnnotation( importType("javax.persistence.GeneratedValue") ) .addAttribute( "strategy", staticImport("javax.persistence.GenerationType", "TABLE" ) ) - .addQuotedAttribute( "generator", "generator" ); + .addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); idResult.append(builder.getResult()); buildAnnTableGenerator( wholeString, properties ); } else { isGenericGenerator = true; builder.resetAnnotation( importType("javax.persistence.GeneratedValue") ); - builder.addQuotedAttribute( "generator", "generator" ); + builder.addQuotedAttribute( "generator", clazz.getClassName()+"IdGenerator" ); idResult.append(builder.getResult()); } } else { @@ -274,7 +274,7 @@ else if ( TableGenerator.class.getName().equals( strategy ) ) { } if ( isGenericGenerator ) { builder.resetAnnotation( importType("org.hibernate.annotations.GenericGenerator") ) - .addQuotedAttribute( "name", "generator" ) + .addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ) .addQuotedAttribute( "strategy", strategy); List params = new ArrayList(); @@ -301,7 +301,7 @@ else if ( TableGenerator.class.getName().equals( strategy ) ) { private void buildAnnTableGenerator(StringBuffer wholeString, Properties properties) { AnnotationBuilder builder = AnnotationBuilder.createAnnotation( importType("javax.persistence.TableGenerator") ); - builder.addQuotedAttribute( "name", "generator" ); + builder.addQuotedAttribute( "name", clazz.getClassName()+"IdGenerator" ); builder.addQuotedAttribute( "table", properties.getProperty( "generatorTableName", "hibernate_sequences" ) ); if ( ! isPropertyDefault( PersistentIdentifierGenerator.CATALOG, properties ) ) { builder.addQuotedAttribute( "catalog", properties.getProperty( PersistentIdentifierGenerator.CATALOG, "") ); diff --git a/main/src/main/java/org/hibernate/tool/hbm2x/xml/AbstractXMLPrettyPrinterStrategy.java b/main/src/main/java/org/hibernate/tool/hbm2x/xml/AbstractXMLPrettyPrinterStrategy.java index e73fa3adab..7016d9df05 100644 --- a/main/src/main/java/org/hibernate/tool/hbm2x/xml/AbstractXMLPrettyPrinterStrategy.java +++ b/main/src/main/java/org/hibernate/tool/hbm2x/xml/AbstractXMLPrettyPrinterStrategy.java @@ -19,7 +19,9 @@ public abstract class AbstractXMLPrettyPrinterStrategy implements XMLPrettyPrinterStrategy { protected Document newDocument(String xml, String encoding) throws SAXException, IOException, ParserConfigurationException { - final Document document = DocumentBuilderFactory.newInstance() + final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + final Document document = dbf .newDocumentBuilder() .parse(new InputSource(new ByteArrayInputStream(xml.getBytes(encoding)))); document.normalize(); diff --git a/main/src/main/java/org/hibernate/tool/hbmlint/detector/InstrumentationDetector.java b/main/src/main/java/org/hibernate/tool/hbmlint/detector/InstrumentationDetector.java index bf4a71ddf7..3286375247 100644 --- a/main/src/main/java/org/hibernate/tool/hbmlint/detector/InstrumentationDetector.java +++ b/main/src/main/java/org/hibernate/tool/hbmlint/detector/InstrumentationDetector.java @@ -2,8 +2,9 @@ import org.hibernate.MappingException; import org.hibernate.boot.Metadata; -import org.hibernate.bytecode.internal.javassist.BytecodeProviderImpl; +import org.hibernate.bytecode.spi.BytecodeProvider; import org.hibernate.cfg.Environment; +import org.hibernate.engine.spi.Managed; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.tool.hbmlint.Issue; @@ -15,13 +16,14 @@ public String getName() { return "instrument"; } - private boolean javassistEnabled; + private boolean enhanceEnabled; public void initialize(Metadata metadata) { super.initialize(metadata); - if(Environment.getBytecodeProvider() instanceof BytecodeProviderImpl) { - javassistEnabled = true; - } + BytecodeProvider bytecodeProvider = Environment.buildBytecodeProvider(Environment.getProperties()); + if(bytecodeProvider instanceof org.hibernate.bytecode.internal.bytebuddy.BytecodeProviderImpl) { + enhanceEnabled = true; + } } protected void visit(PersistentClass clazz, IssueCollector collector) { @@ -45,17 +47,17 @@ protected void visit(PersistentClass clazz, IssueCollector collector) { return; } - } else if(javassistEnabled){ + } else if(enhanceEnabled){ Class[] interfaces = mappedClass.getInterfaces(); - boolean javaassist = false; + boolean enhanced = false; for (int i = 0; i < interfaces.length; i++) { - Class intface = interfaces[i]; - if(intface.getName().equals( "org.hibernate.bytecode.internal.javassist.FieldHandled" )) { - javaassist = true; + Class intface = interfaces[i]; + if(intface.getName().equals(Managed.class.getName())) { + enhanced = true; } } - if (javassistEnabled && !javaassist) { + if (enhanceEnabled && !enhanced) { collector.reportIssue( new Issue("LAZY_NOT_INSTRUMENTED", Issue.HIGH_PRIORITY, "'" + clazz.getEntityName() + "' has lazy='false', but its class '" + mappedClass.getName() + "' has not been instrumented with javaassist") ); return; } else { diff --git a/main/src/main/java/org/hibernate/tool/hbmlint/detector/SchemaByMetaDataDetector.java b/main/src/main/java/org/hibernate/tool/hbmlint/detector/SchemaByMetaDataDetector.java index d9074051ed..dee75fade1 100644 --- a/main/src/main/java/org/hibernate/tool/hbmlint/detector/SchemaByMetaDataDetector.java +++ b/main/src/main/java/org/hibernate/tool/hbmlint/detector/SchemaByMetaDataDetector.java @@ -3,7 +3,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import java.util.Properties; import java.util.Set; import java.util.TreeMap; @@ -11,20 +10,22 @@ import org.hibernate.MappingException; import org.hibernate.boot.Metadata; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.cfg.JDBCReaderFactory; import org.hibernate.cfg.reveng.DatabaseCollector; import org.hibernate.cfg.reveng.DefaultDatabaseCollector; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; import org.hibernate.cfg.reveng.JDBCReader; -import org.hibernate.cfg.reveng.JDBCToHibernateTypeHelper; import org.hibernate.cfg.reveng.SchemaSelection; +import org.hibernate.cfg.reveng.utils.JdbcToHibernateTypeHelper; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.Mapping; import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator; +import org.hibernate.id.enhanced.SequenceStyleGenerator; +import org.hibernate.id.enhanced.TableGenerator; +import org.hibernate.id.factory.IdentifierGeneratorFactory; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; @@ -88,7 +89,7 @@ public void visitGenerators(IssueCollector collector) { // TODO: move this check into something that could check per class or collection instead. while ( iter.hasNext() ) { PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next(); - Object key = generator.generatorKey(); + Object key = getGeneratorKey(generator); if ( !isSequence(key, sequences) && !isTable( key ) ) { collector.reportIssue( new Issue( "MISSING_ID_GENERATOR", Issue.HIGH_PRIORITY, "Missing sequence or table: " + key)); } @@ -200,7 +201,7 @@ public void visit( pc.reportIssue( new Issue( "SCHEMA_COLUMN_TYPE_MISMATCH", Issue.NORMAL_PRIORITY, table(table) + " has a wrong column type for " + col.getName() + ", expected: " - + JDBCToHibernateTypeHelper.getJDBCTypeName(modelTypeCode) + " but was " + JDBCToHibernateTypeHelper.getJDBCTypeName(dbTypeCode) + " in db") ); + + JdbcToHibernateTypeHelper.getJDBCTypeName(modelTypeCode) + " but was " + JdbcToHibernateTypeHelper.getJDBCTypeName(dbTypeCode) + " in db") ); } } } @@ -218,15 +219,10 @@ private void setSchemaSelection(Table table) { * @return iterator over all the IdentifierGenerator's found in the entitymodel and return a list of unique IdentifierGenerators * @throws MappingException */ - @SuppressWarnings("deprecation") private Iterator iterateGenerators() throws MappingException { TreeMap generators = new TreeMap(); - StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); - Properties properties = (Properties)builder.getSettings(); - String defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG); - String defaultSchema = properties.getProperty(AvailableSettings.DEFAULT_SCHEMA); Iterator persistentClassIterator = getMetadata().getEntityBindings().iterator(); while ( persistentClassIterator.hasNext() ) { @@ -236,15 +232,13 @@ private Iterator iterateGenerators() throws MappingExceptio IdentifierGenerator ig = pc.getIdentifier() .createIdentifierGenerator( - getMetadata().getIdentifierGeneratorFactory(), + getIdentifierGeneratorFactory(), dialect, - defaultCatalog, - defaultSchema, (RootClass) pc ); if ( ig instanceof PersistentIdentifierGenerator ) { - generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig ); + generators.put( getGeneratorKey( (PersistentIdentifierGenerator) ig ), ig ); } } @@ -258,15 +252,13 @@ private Iterator iterateGenerators() throws MappingExceptio IdentifierGenerator ig = ( (IdentifierCollection) collection ).getIdentifier() .createIdentifierGenerator( - getMetadata().getIdentifierGeneratorFactory(), + getIdentifierGeneratorFactory(), dialect, - defaultCatalog, - defaultSchema, null ); if ( ig instanceof PersistentIdentifierGenerator ) { - generators.put( ( (PersistentIdentifierGenerator) ig ).generatorKey(), ig ); + generators.put( getGeneratorKey( (PersistentIdentifierGenerator) ig ), ig ); } } @@ -274,5 +266,28 @@ private Iterator iterateGenerators() throws MappingExceptio return generators.values().iterator(); } + + @SuppressWarnings("deprecation") + private IdentifierGeneratorFactory getIdentifierGeneratorFactory() { + return ((Mapping)getMetadata()).getIdentifierGeneratorFactory(); + } + + private String getGeneratorKey(PersistentIdentifierGenerator ig) { + String result = null; + if (ig instanceof SequenceStyleGenerator) { + result = getKeyForSequenceStyleGenerator((SequenceStyleGenerator)ig); + } else if (ig instanceof TableGenerator) { + result = getKeyForTableGenerator((TableGenerator)ig); + } + return result; + } + + private String getKeyForSequenceStyleGenerator(SequenceStyleGenerator ig) { + return ig.getDatabaseStructure().getPhysicalName().render(); + } + + private String getKeyForTableGenerator(TableGenerator ig) { + return ig.getTableName(); + } } diff --git a/main/src/main/java/org/hibernate/tool/ide/formatting/DefaultJavaPrettyPrinterStrategy.java b/main/src/main/java/org/hibernate/tool/ide/formatting/DefaultJavaPrettyPrinterStrategy.java new file mode 100644 index 0000000000..2971d808d0 --- /dev/null +++ b/main/src/main/java/org/hibernate/tool/ide/formatting/DefaultJavaPrettyPrinterStrategy.java @@ -0,0 +1,27 @@ +package org.hibernate.tool.ide.formatting; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; + +import com.google.googlejavaformat.java.Formatter; +import com.google.googlejavaformat.java.FormatterException; + +public class DefaultJavaPrettyPrinterStrategy { + + public DefaultJavaPrettyPrinterStrategy(Map settings) {} + + public boolean formatFile(File file) { + try { + Formatter formatter = new Formatter(); + String toFormat = new String(Files.readAllBytes(file.toPath())); + String toWrite = formatter.formatSource(toFormat); + Files.write(file.toPath(), toWrite.getBytes()); + return true; + } catch (IOException | FormatterException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/main/src/main/java/org/hibernate/tool/ide/formatting/JavaFormatter.java b/main/src/main/java/org/hibernate/tool/ide/formatting/JavaFormatter.java deleted file mode 100644 index ec67e7053e..0000000000 --- a/main/src/main/java/org/hibernate/tool/ide/formatting/JavaFormatter.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.hibernate.tool.ide.formatting; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.ToolFactory; -import org.eclipse.jdt.core.formatter.CodeFormatter; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.text.edits.TextEdit; -import org.hibernate.tool.hbm2x.ExporterException; - - -public class JavaFormatter { - - private CodeFormatter codeFormatter; - - public JavaFormatter(Map settings) { - if(settings==null) { - // if no settings run with jdk 5 as default - settings = new HashMap(); - settings.put( JavaCore.COMPILER_SOURCE, "1.5"); - settings.put( JavaCore.COMPILER_COMPLIANCE, "1.5"); - settings.put( JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, "1.5"); - } - - this.codeFormatter = ToolFactory.createCodeFormatter(settings); - } - - /** - * Throws exception if not possible to read or write the file. - * Returns true if formatting went ok; returns false if the formatting could not finish because of errors in the input. - * - * @param file - * @param codeFormatter - * @return - */ - public boolean formatFile(File file) throws ExporterException { - IDocument doc = new Document(); - try { - String contents = new String(org.eclipse.jdt.internal.compiler.util.Util.getFileCharContent(file, null)); - doc.set(contents); - TextEdit edit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, contents, 0, contents.length(), 0, null); - if (edit != null) { - edit.apply(doc); - } else { - return false; // most likely syntax errror - } - - // write the file - final BufferedWriter out = new BufferedWriter(new FileWriter(file)); - try { - out.write(doc.get()); - out.flush(); - } finally { - try { - out.close(); - } catch (IOException e) { - /* ignore */ - } - } - return true; - } catch (IOException e) { - throw new ExporterException("Could not format " + file, e); - } catch (BadLocationException e) { - throw new ExporterException("Could not format " + file, e); - } - } - -} diff --git a/main/src/main/java/org/hibernate/tool/internal/metadata/JdbcMetadataDescriptor.java b/main/src/main/java/org/hibernate/tool/internal/metadata/JdbcMetadataDescriptor.java index a12997f1d2..d996484e78 100644 --- a/main/src/main/java/org/hibernate/tool/internal/metadata/JdbcMetadataDescriptor.java +++ b/main/src/main/java/org/hibernate/tool/internal/metadata/JdbcMetadataDescriptor.java @@ -4,37 +4,26 @@ import org.hibernate.MappingException; import org.hibernate.boot.Metadata; -import org.hibernate.boot.internal.ClassLoaderAccessImpl; +import org.hibernate.boot.internal.BootstrapContextImpl; import org.hibernate.boot.internal.InFlightMetadataCollectorImpl; import org.hibernate.boot.internal.MetadataBuilderImpl.MetadataBuildingOptionsImpl; import org.hibernate.boot.internal.MetadataBuildingContextRootImpl; -import org.hibernate.boot.model.TypeContributions; -import org.hibernate.boot.model.TypeContributor; +import org.hibernate.boot.internal.MetadataImpl; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; -import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.boot.spi.BasicTypeRegistration; -import org.hibernate.boot.spi.ClassLoaderAccess; +import org.hibernate.boot.spi.BootstrapContext; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingOptions; import org.hibernate.cfg.Environment; import org.hibernate.cfg.JDBCBinder; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; -import org.hibernate.dialect.Dialect; -import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.Mapping; import org.hibernate.id.factory.IdentifierGeneratorFactory; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.tool.api.metadata.MetadataDescriptor; -import org.hibernate.type.BasicType; -import org.hibernate.type.BasicTypeRegistry; import org.hibernate.type.Type; -import org.hibernate.type.TypeFactory; -import org.hibernate.type.TypeResolver; -import org.hibernate.usertype.CompositeUserType; -import org.hibernate.usertype.UserType; public class JdbcMetadataDescriptor implements MetadataDescriptor { @@ -66,19 +55,24 @@ public Metadata createMetadata() { StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(getProperties()) .build(); - MetadataBuildingOptions metadataBuildingOptions = + MetadataBuildingOptionsImpl metadataBuildingOptions = new MetadataBuildingOptionsImpl( serviceRegistry ); + BootstrapContextImpl bootstrapContext = new BootstrapContextImpl( + serviceRegistry, + metadataBuildingOptions); + metadataBuildingOptions.setBootstrapContext(bootstrapContext); InFlightMetadataCollectorImpl metadataCollector = - getMetadataCollector(metadataBuildingOptions); - ClassLoaderAccess classLoaderAccess = - getClassLoaderAccess(metadataBuildingOptions); + getMetadataCollector( + bootstrapContext, + metadataBuildingOptions); MetadataBuildingContext metadataBuildingContext = new MetadataBuildingContextRootImpl( + bootstrapContext, metadataBuildingOptions, - classLoaderAccess, metadataCollector); - Metadata metadata = metadataCollector + MetadataImpl metadata = metadataCollector .buildMetadataInstance(metadataBuildingContext); + metadata.getTypeConfiguration().scope(metadataBuildingContext); JDBCBinder binder = new JDBCBinder( serviceRegistry, getProperties(), @@ -93,66 +87,11 @@ public Metadata createMetadata() { } private InFlightMetadataCollectorImpl getMetadataCollector( + BootstrapContext bootstrapContext, MetadataBuildingOptions metadataBuildingOptions) { - BasicTypeRegistry basicTypeRegistry = handleTypes( metadataBuildingOptions ); return new InFlightMetadataCollectorImpl( - metadataBuildingOptions, - new TypeResolver( basicTypeRegistry, new TypeFactory() ) - ); - } - - private BasicTypeRegistry handleTypes(MetadataBuildingOptions options) { - final ClassLoaderService classLoaderService = options.getServiceRegistry().getService( ClassLoaderService.class ); - - // ultimately this needs to change a little bit to account for HHH-7792 - final BasicTypeRegistry basicTypeRegistry = new BasicTypeRegistry(); - - final TypeContributions typeContributions = new TypeContributions() { - public void contributeType(BasicType type) { - basicTypeRegistry.register( type ); - } - - public void contributeType(BasicType type, String... keys) { - basicTypeRegistry.register( type, keys ); - } - - public void contributeType(UserType type, String... keys) { - basicTypeRegistry.register( type, keys ); - } - - public void contributeType(CompositeUserType type, String... keys) { - basicTypeRegistry.register( type, keys ); - } - }; - - // add Dialect contributed types - final Dialect dialect = options.getServiceRegistry().getService( JdbcServices.class ).getDialect(); - dialect.contributeTypes( typeContributions, options.getServiceRegistry() ); - - // add TypeContributor contributed types. - for ( TypeContributor contributor : classLoaderService.loadJavaServices( TypeContributor.class ) ) { - contributor.contribute( typeContributions, options.getServiceRegistry() ); - } - - // add explicit application registered types - for ( BasicTypeRegistration basicTypeRegistration : options.getBasicTypeRegistrations() ) { - basicTypeRegistry.register( - basicTypeRegistration.getBasicType(), - basicTypeRegistration.getRegistrationKeys() - ); - } - - return basicTypeRegistry; - } - - private ClassLoaderAccess getClassLoaderAccess( - MetadataBuildingOptions metadataBuildingOptions) { - ClassLoaderService classLoaderService = - metadataBuildingOptions.getServiceRegistry().getService( - ClassLoaderService.class ); - return new ClassLoaderAccessImpl( - metadataBuildingOptions.getTempClassLoader(), - classLoaderService); + bootstrapContext, + metadataBuildingOptions); } private Mapping buildMapping(final Metadata metadata) { diff --git a/main/src/main/java/org/hibernate/tool/stat/StatisticsTreeModel.java b/main/src/main/java/org/hibernate/tool/stat/StatisticsTreeModel.java index 542fabb709..957f576b8e 100644 --- a/main/src/main/java/org/hibernate/tool/stat/StatisticsTreeModel.java +++ b/main/src/main/java/org/hibernate/tool/stat/StatisticsTreeModel.java @@ -1,10 +1,11 @@ package org.hibernate.tool.stat; +import java.util.Collections; import java.util.Map; -import org.hibernate.stat.SecondLevelCacheStatistics; -import org.hibernate.stat.Statistics; import org.hibernate.internal.util.collections.IdentityMap; +import org.hibernate.stat.CacheRegionStatistics; +import org.hibernate.stat.Statistics; public class StatisticsTreeModel extends AbstractTreeModel { @@ -36,10 +37,9 @@ public Object getChild(Object parent, int index) { } else if(parent==queries) { return stats.getQueryStatistics(stats.getQueries()[index]); } else if(parent==secondlevelcache) { - return stats.getSecondLevelCacheStatistics( stats.getSecondLevelCacheRegionNames()[index]); - } else if(parent instanceof SecondLevelCacheStatistics) { - SecondLevelCacheStatistics slcs = (SecondLevelCacheStatistics) parent; - return slcs.getEntries(); + return stats.getCacheRegionStatistics(stats.getSecondLevelCacheRegionNames()[index]); + } else if (parent instanceof CacheRegionStatistics) { + return Collections.emptyMap(); } return null; } @@ -55,9 +55,8 @@ public int getChildCount(Object parent) { return stats.getQueries().length; } else if(parent==secondlevelcache) { return stats.getSecondLevelCacheRegionNames().length; - } else if(parent instanceof SecondLevelCacheStatistics) { - /*SecondLevelCacheStatistics stats = (SecondLevelCacheStatistics) parent; - return stats.getEntries().size();*/ + } else if(parent instanceof CacheRegionStatistics) { + return 0; } return 0; } diff --git a/main/src/main/java/org/hibernate/tool/xml/XMLHelper.java b/main/src/main/java/org/hibernate/tool/xml/XMLHelper.java deleted file mode 100644 index 1813f26068..0000000000 --- a/main/src/main/java/org/hibernate/tool/xml/XMLHelper.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.tool.xml; - -import org.dom4j.io.SAXReader; -import org.xml.sax.ErrorHandler; - -public final class XMLHelper { - - public static SAXReader createSAXReader(ErrorHandler errorHandler) { - SAXReader saxReader = resolveSAXReader(); - saxReader.setErrorHandler( errorHandler ); - return saxReader; - } - - private static SAXReader resolveSAXReader() { - SAXReader saxReader = new SAXReader(); - saxReader.setMergeAdjacentText( true ); - saxReader.setValidation( true ); - return saxReader; - } - -} diff --git a/main/src/main/resources/dao/daohome.ftl b/main/src/main/resources/dao/daohome.ftl index 37d0f55816..d8766bd719 100644 --- a/main/src/main/resources/dao/daohome.ftl +++ b/main/src/main/resources/dao/daohome.ftl @@ -12,58 +12,58 @@ ${pojo.getPackageDeclaration()} public class ${declarationName}Home { - private static final ${pojo.importType("org.apache.commons.logging.Log")} log = ${pojo.importType("org.apache.commons.logging.LogFactory")}.getLog(${pojo.getDeclarationName()}Home.class); + private static final ${pojo.importType("java.util.logging.Logger")} logger = ${pojo.importType("Logger")}.getLogger(${pojo.getDeclarationName()}Home.class.getName()); <#if ejb3> @${pojo.importType("javax.persistence.PersistenceContext")} private ${pojo.importType("javax.persistence.EntityManager")} entityManager; public void persist(${declarationName} transientInstance) { - log.debug("persisting ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persisting ${declarationName} instance"); try { entityManager.persist(transientInstance); - log.debug("persist successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persist successful"); } catch (RuntimeException re) { - log.error("persist failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "persist failed", re); throw re; } } public void remove(${declarationName} persistentInstance) { - log.debug("removing ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "removing ${declarationName} instance"); try { entityManager.remove(persistentInstance); - log.debug("remove successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "remove successful"); } catch (RuntimeException re) { - log.error("remove failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "remove failed", re); throw re; } } public ${declarationName} merge(${declarationName} detachedInstance) { - log.debug("merging ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merging ${declarationName} instance"); try { ${declarationName} result = entityManager.merge(detachedInstance); - log.debug("merge successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merge successful"); return result; } catch (RuntimeException re) { - log.error("merge failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "merge failed", re); throw re; } } <#if clazz.identifierProperty?has_content> public ${declarationName} findById( ${pojo.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { - log.debug("getting ${declarationName} instance with id: " + id); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance with id: " + id); try { ${declarationName} instance = entityManager.find(${pojo.getDeclarationName()}.class, id); - log.debug("get successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful"); return instance; } catch (RuntimeException re) { - log.error("get failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "get failed", re); throw re; } } @@ -76,89 +76,89 @@ public class ${declarationName}Home { return (${pojo.importType("org.hibernate.SessionFactory")}) new ${pojo.importType("javax.naming.InitialContext")}().lookup("${sessionFactoryName}"); } catch (Exception e) { - log.error("Could not locate SessionFactory in JNDI", e); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "Could not locate SessionFactory in JNDI", e); throw new IllegalStateException("Could not locate SessionFactory in JNDI"); } } public void persist(${declarationName} transientInstance) { - log.debug("persisting ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persisting ${declarationName} instance"); try { sessionFactory.getCurrentSession().persist(transientInstance); - log.debug("persist successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persist successful"); } catch (RuntimeException re) { - log.error("persist failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "persist failed", re); throw re; } } public void attachDirty(${declarationName} instance) { - log.debug("attaching dirty ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attaching dirty ${declarationName} instance"); try { sessionFactory.getCurrentSession().saveOrUpdate(instance); - log.debug("attach successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attach successful"); } catch (RuntimeException re) { - log.error("attach failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "attach failed", re); throw re; } } public void attachClean(${declarationName} instance) { - log.debug("attaching clean ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attaching clean ${declarationName} instance"); try { sessionFactory.getCurrentSession().lock(instance, ${pojo.importType("org.hibernate.LockMode")}.NONE); - log.debug("attach successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attach successful"); } catch (RuntimeException re) { - log.error("attach failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "attach failed", re); throw re; } } public void delete(${declarationName} persistentInstance) { - log.debug("deleting ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "deleting ${declarationName} instance"); try { sessionFactory.getCurrentSession().delete(persistentInstance); - log.debug("delete successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "delete successful"); } catch (RuntimeException re) { - log.error("delete failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "delete failed", re); throw re; } } public ${declarationName} merge(${declarationName} detachedInstance) { - log.debug("merging ${declarationName} instance"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merging ${declarationName} instance"); try { ${declarationName} result = (${declarationName}) sessionFactory.getCurrentSession() .merge(detachedInstance); - log.debug("merge successful"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merge successful"); return result; } catch (RuntimeException re) { - log.error("merge failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "merge failed", re); throw re; } } <#if clazz.identifierProperty?has_content> public ${declarationName} findById( ${c2j.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { - log.debug("getting ${declarationName} instance with id: " + id); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance with id: " + id); try { ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession() .get("${clazz.entityName}", id); if (instance==null) { - log.debug("get successful, no instance found"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, no instance found"); } else { - log.debug("get successful, instance found"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, instance found"); } return instance; } catch (RuntimeException re) { - log.error("get failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "get failed", re); throw re; } } @@ -166,7 +166,7 @@ public class ${declarationName}Home { <#if clazz.hasNaturalId()> public ${declarationName} findByNaturalId(${c2j.asNaturalIdParameterList(clazz)}) { - log.debug("getting ${declarationName} instance by natural id"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance by natural id"); try { ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession() .createCriteria("${clazz.entityName}") @@ -183,15 +183,15 @@ public class ${declarationName}Home { ) .uniqueResult(); if (instance==null) { - log.debug("get successful, no instance found"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, no instance found"); } else { - log.debug("get successful, instance found"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, instance found"); } return instance; } catch (RuntimeException re) { - log.error("query failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "query failed", re); throw re; } } @@ -201,7 +201,7 @@ public class ${declarationName}Home { <#else> public ${pojo.importType("java.util.List")} findByExample(${declarationName} instance) { - log.debug("finding ${declarationName} instance by example"); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "finding ${declarationName} instance by example"); try { <#if jdk5> ${pojo.importType("java.util.List")}<${declarationName}> results = (List<${declarationName}>) sessionFactory.getCurrentSession() @@ -215,11 +215,11 @@ public class ${declarationName}Home { .add(${pojo.importType("org.hibernate.criterion.Example")}.create(instance)) .list(); - log.debug("find by example successful, result size: " + results.size()); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { - log.error("find by example failed", re); + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "find by example failed", re); throw re; } } diff --git a/main/src/main/resources/hbm/generalhbm.hbm.ftl b/main/src/main/resources/hbm/generalhbm.hbm.ftl index bf73afd337..5d9d8e982c 100644 --- a/main/src/main/resources/hbm/generalhbm.hbm.ftl +++ b/main/src/main/resources/hbm/generalhbm.hbm.ftl @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <#if hmgs?exists && hmgs.hasNonDefaultSettings()> diff --git a/main/src/main/resources/hbm/many-to-one.hbm.ftl b/main/src/main/resources/hbm/many-to-one.hbm.ftl index 11fd1805b2..3a0cff5978 100644 --- a/main/src/main/resources/hbm/many-to-one.hbm.ftl +++ b/main/src/main/resources/hbm/many-to-one.hbm.ftl @@ -23,12 +23,6 @@ <#if !property.optimisticLocked> optimistic-lock="false" - -<#if property.value.hasFormula()> -<#assign formula = c2h.getFormulaForProperty(property)> -<#if formula?exists> - formula="${formula.text}" - > <#assign metaattributable=property> diff --git a/main/src/main/resources/hbm/persistentclass.hbm.ftl b/main/src/main/resources/hbm/persistentclass.hbm.ftl index 623b74104e..6fa0c0ac9f 100644 --- a/main/src/main/resources/hbm/persistentclass.hbm.ftl +++ b/main/src/main/resources/hbm/persistentclass.hbm.ftl @@ -65,24 +65,6 @@ <#if clazz.table.comment?exists && clazz.table.comment?trim?length!=0> ${clazz.table.comment} -<#foreach join in clazz.joinIterator> - - table="${join.table.name}" - > - <#if join.table.comment?exists && join.table.comment?trim?length!=0> - ${comment} - - - <#foreach column in join.key.columnIterator> - <#include "column.hbm.ftl"> - - - <#foreach property in join.propertyIterator> - <#include "${c2h.getTag(property)}.hbm.ftl"/> - - - <#-- TODO: move this to id.hbm.ftl --> <#if !c2h.isSubclass(clazz)> <#if clazz.hasIdentifierProperty()> @@ -141,4 +123,23 @@ +<#foreach join in clazz.joinIterator> + + table="${join.table.name}" + > + <#if join.table.comment?exists && join.table.comment?trim?length!=0> + ${comment} + + + <#foreach column in join.key.columnIterator> + <#include "column.hbm.ftl"> + + + <#foreach property in join.propertyIterator> + <#include "${c2h.getTag(property)}.hbm.ftl"/> + + + + diff --git a/main/src/main/resources/pojo/PojoPropertyAccessors.ftl b/main/src/main/resources/pojo/PojoPropertyAccessors.ftl index 74f66a35f7..167e8515fb 100644 --- a/main/src/main/resources/pojo/PojoPropertyAccessors.ftl +++ b/main/src/main/resources/pojo/PojoPropertyAccessors.ftl @@ -3,7 +3,7 @@ <#if pojo.getMetaAttribAsBool(property, "gen-property", true)> <#if pojo.hasFieldJavaDoc(property)> /** - * ${pojo.getFieldJavaDoc(property, 4)} + ${pojo.getFieldJavaDoc(property, 4)} */ <#include "GetPropertyAnnotation.ftl"/> diff --git a/maven-plugin/README.md b/maven-plugin/README.md new file mode 100644 index 0000000000..c67ae15843 --- /dev/null +++ b/maven-plugin/README.md @@ -0,0 +1,187 @@ + + +[![Hibernate](https://static.jboss.org/hibernate/images/hibernate_200x150.png)](https://tools.hibernate.org) + +# Hibernate Tools Maven Plugin + +This [Maven](http://maven.apache.org/) plugin brings the power of the [Hibernate Tools API](../orm) to your Maven build. + +## 5 Minute Tutorial + +The best way to get to know the Hibernate Tools Maven plugin is to start to use it. Hence we will provide a quick tutorial that gives you the first taste of it. In this example we will create a simple database containing one table and use the plugin to reverse engineer a JPA entity from it. + +### Create a Maven Project + +Use a command line tool or your preferred IDE to create a basic Maven project. + +``` + + + 4.0.0 + + org.acme + bar + 0.0.1-SNAPSHOT + + ... + + +``` + +### Create a Simple Database + +We will use the [H2 database engine](https://www.h2database.com/html/main.html) and the [SQL Maven plugin](https://www.mojohaus.org/sql-maven-plugin/) to create a simple database. +Modify your pom file to contain a build section as shown below. + +``` + + + ... + + + 1.4.200 + 1.5 + ... + + + + + + org.codehaus.mojo + sql-maven-plugin + ${sql.version} + + + com.h2database + h2 + ${h2.version} + + + + + create-database + initialize + + execute + + + org.h2.Driver + jdbc:h2:${project.build.directory}/database/bardb + sa + + true + create table foo (id int not null primary key, baz varchar(256)) + + + + + + ... + + + + + +``` + +Issuing `mvn clean initialize` on the command line in the root of your project will now create the 'bardb' database in the folder 'target/database'. We are now ready to reverse engineer the database table to an entity class. + +### Generate entities + +To properly generate our entity, we need to do two more things. The first is of course add a new plugin section to the pom file that configures the use of the Hibernate Tools Maven plugin. + +``` + + + ... + + + ... + 5.4.13-SNAPSHOT + + + + + + ... + + + org.hibernate + hibernate-tools-maven-plugin + ${hibernate.version} + + + org.hibernate + hibernate-tools + ${hibernate.version} + + + com.h2database + h2 + ${h2.version} + + + + + entity-generation + generate-sources + + hbm2java + + + true + + + + + + + + +``` + +In principle, we are now ready to generate the entity, but issuing `mvn clean generate-sources` will result in an error, complaining about the fact that a 'hiberate.properties' file could not be found. +By default the plugin looks in the folder 'src/main/resources' for this file. So it is for now sufficient to add a 'hibernate.properties' file in that location with the contents specified below. + +``` +hibernate.dialect=H2 +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:./target/database/bardb +hibernate.connection.username=sa +hibernate.connection.password= +``` + +Now we are ready. Executing `mvn clean generate-sources` will create a 'Foo.java' entity in the default location, which is 'target/generated-sources'. + + + + + + diff --git a/maven-plugin/pom.xml b/maven-plugin/pom.xml new file mode 100644 index 0000000000..7569905f80 --- /dev/null +++ b/maven-plugin/pom.xml @@ -0,0 +1,160 @@ + + 4.0.0 + + + org.hibernate + hibernate-tools-parent + 5.6.16-SNAPSHOT + + + hibernate-tools-maven-plugin + + maven-plugin + + Hibernate Tools Maven Plugin + Maven plugin to provide hibernate-tools reverse engineering and code/schema generation abilities. + https://hibernate.github.io/hibernate-tools/ + + + JIRA + http://hibernate.onjira.com/browse/HBX + + + + scm:git:git://github.com/hibernate/hibernate-tools.git + scm:git:git@github.com:hibernate/hibernate-tools.git + http://github.com/hibernate/hibernate-tools + + + + Hibernate + http://www.hibernate.org + + + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl-2.1.html + + + + + + stadler + Jacques Stadler + jacques.stadler+github@gmail.com + + + + + 3.0 + + + + + false + false + + 3.5 + 3.5.2 + 3.9.9 + + + 2.9 + 3.7 + 0.12 + + + + + + org.hibernate + hibernate-tools + + + + org.apache.maven + maven-plugin-api + ${maven-plugin-api.version} + provided + + + org.apache.maven + maven-core + ${maven-core.version} + provided + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${maven-plugin-annotations.version} + provided + + + + + + + + maven-project-info-reports-plugin + ${maven-project-info-reports-plugin.version} + + + maven-site-plugin + ${maven-site-plugin.version} + + true + + + + + + + + maven-plugin-plugin + + + default-descriptor + process-classes + + + help-goal + + helpmojo + + + + + + com.github.github + site-maven-plugin + ${site-maven-plugin.version} + + + + site + + site-deploy + + github + Creating site for ${project.version} + + + + + + + + + + + maven-project-info-reports-plugin + + + maven-plugin-plugin + + + + + diff --git a/maven-plugin/readme.txt b/maven-plugin/readme.txt new file mode 100644 index 0000000000..fca41775d7 --- /dev/null +++ b/maven-plugin/readme.txt @@ -0,0 +1,109 @@ +Hibernate Tools Maven Plugin +============================ +Version: 6.0.0, January 2016 + +What is it +---------- +A Maven Plugin to generate JPA Entities from an existing database using hibernate-tools. + +Development status +------------------ +Currently the plugin allows database reverse engineering configurations (JDBCMetaDataConfiguration) +to export JPA Entities (hbm2java) and Schema Files (hbm2ddl). + +History +------- +The hibernate-tools-maven-plugin was originally developed by Jacques Stadler +in the following repository and was based on version 1.1.0: +https://github.com/stadler/hibernate-tools-maven-plugin + +Licensing +--------- +This software is distributed under the terms of the FSF Lesser Gnu Public +License (see lgpl.txt). + +Maven Plugin Site +----------------- +TODO: To be migrated... +https://stadler.github.io/hibernate-tools-maven-plugin/ + +Usage +----- +TODO: To be migrated... +An example project using this plugin can be found here: +https://github.com/stadler/hibernate-tools-maven-plugin-sample + +The plugin declaration may look as follows: +``` + + com.github.stadler + hibernate-tools-maven-plugin + ${hibernate-tools-maven-plugin.version} + + + Display Help + validate + + help + + + + Entity generation + generate-sources + + hbm2java + + + ${project.basedir}/src/main/resources/templates/ + + ${project.build.directory}/generated-sources/ + false + false + + + + Schema generation + generate-resources + + hbm2ddl + + + + + SCRIPT + STDOUT + DATABASE + + + ${project.build.directory}/generated-resources/ + + CREATE + schema.ddl + ; + true + true + + + + + ${project.basedir}/src/main/hibernate/hibernate.reveng.xml + + + ${project.basedir}/src/main/hibernate/hibernate.cfg.xml + true + true + true + true + true + + + + + com.h2database + h2 + ${h2.version} + + + + +``` diff --git a/maven-plugin/src/main/java/org/hibernate/mvn/AbstractHbm2xMojo.java b/maven-plugin/src/main/java/org/hibernate/mvn/AbstractHbm2xMojo.java new file mode 100644 index 0000000000..a1dd133fc4 --- /dev/null +++ b/maven-plugin/src/main/java/org/hibernate/mvn/AbstractHbm2xMojo.java @@ -0,0 +1,152 @@ +package org.hibernate.mvn; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Properties; + +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.tools.ant.BuildException; +import org.hibernate.cfg.reveng.OverrideRepository; +import org.hibernate.cfg.reveng.ReverseEngineeringSettings; +import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; + +public abstract class AbstractHbm2xMojo extends AbstractMojo { + + // For reveng strategy + /** The default package name to use when mappings for classes are created. */ + @Parameter + private String packageName; + + /** The name of a property file, e.g. hibernate.properties. */ + @Parameter + private File revengFile; + + /** The class name of the reverse engineering strategy to use. + * Extend the DefaultReverseEngineeringStrategy and override the corresponding methods, e.g. + * to adapt the generate class names or to provide custom type mappings. */ + @Parameter(defaultValue = "org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy") + private String revengStrategy; + + /** If true, tables which are pure many-to-many link tables will be mapped as such. + * A pure many-to-many table is one which primary-key contains exactly two foreign-keys pointing + * to other entity tables and has no other columns. */ + @Parameter(defaultValue = "true") + private boolean detectManyToMany; + + /** If true, a one-to-one association will be created for each foreignkey found. */ + @Parameter(defaultValue = "true") + private boolean detectOneToOne; + + /** If true, columns named VERSION or TIMESTAMP with appropriate types will be mapped with the appropriate + * optimistic locking corresponding to <version> or <timestamp>. */ + @Parameter(defaultValue = "true") + private boolean detectOptimisticLock; + + /** If true, a collection will be mapped for each foreignkey. */ + @Parameter(defaultValue = "true") + private boolean createCollectionForForeignKey; + + /** If true, a many-to-one association will be created for each foreignkey found. */ + @Parameter(defaultValue = "true") + private boolean createManyToOneForForeignKey; + + // For configuration + /** The name of a property file, e.g. hibernate.properties. */ + @Parameter(defaultValue = "${project.basedir}/src/main/resources/hibernate.properties") + private File propertyFile; + + // Not exposed for now + private boolean preferBasicCompositeIds = true; + + @Parameter(defaultValue = "${project}", readonly = true, required = true) + private MavenProject project; + + public void execute() { + ClassLoader original = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(createExporterClassLoader(original)); + getLog().info("Starting " + this.getClass().getSimpleName() + "..."); + ReverseEngineeringStrategy strategy = setupReverseEngineeringStrategy(); + if (propertyFile.exists()) { + executeExporter(createJdbcDescriptor(strategy, loadPropertiesFile())); + } else { + getLog().info("Property file '" + propertyFile + "' cannot be found, aborting..."); + } + getLog().info("Finished " + this.getClass().getSimpleName() + "!"); + } finally { + Thread.currentThread().setContextClassLoader(original); + } + } + + private ReverseEngineeringStrategy setupReverseEngineeringStrategy() { + ReverseEngineeringStrategy strategy; + try { + strategy = ReverseEngineeringStrategy.class.cast(Class.forName(revengStrategy).newInstance()); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | ClassCastException e) { + throw new BuildException(revengStrategy + " not instanced.", e); + } + + if (revengFile != null) { + OverrideRepository override = new OverrideRepository(); + override.addFile(revengFile); + strategy = override.getReverseEngineeringStrategy(strategy); + } + + ReverseEngineeringSettings settings = + new ReverseEngineeringSettings(strategy) + .setDefaultPackageName(packageName) + .setDetectManyToMany(detectManyToMany) + .setDetectOneToOne(detectOneToOne) + .setDetectOptimisticLock(detectOptimisticLock) + .setCreateCollectionForForeignKey(createCollectionForForeignKey) + .setCreateManyToOneForForeignKey(createManyToOneForForeignKey); + + strategy.setSettings(settings); + return strategy; + } + + private Properties loadPropertiesFile() { + try (FileInputStream is = new FileInputStream(propertyFile)) { + Properties result = new Properties(); + result.load(is); + return result; + } catch (FileNotFoundException e) { + throw new BuildException(propertyFile + " not found.", e); + } catch (IOException e) { + throw new BuildException("Problem while loading " + propertyFile, e); + } + } + + private MetadataDescriptor createJdbcDescriptor(ReverseEngineeringStrategy strategy, Properties properties) { + return MetadataDescriptorFactory + .createJdbcDescriptor( + strategy, + properties, + preferBasicCompositeIds); + } + + private ClassLoader createExporterClassLoader(ClassLoader parent) { + ArrayList urls = new ArrayList(); + try { + for (String cpe : project.getRuntimeClasspathElements()) { + urls.add(new File(cpe).toURI().toURL()); + } + } catch (DependencyResolutionRequiredException | MalformedURLException e) { + throw new RuntimeException("Problem while constructing project classloader", e); + } + return new URLClassLoader(urls.toArray(new URL[0]), parent); + } + + protected abstract void executeExporter(MetadataDescriptor metadataDescriptor); +} diff --git a/maven-plugin/src/main/java/org/hibernate/mvn/GenerateDaoMojo.java b/maven-plugin/src/main/java/org/hibernate/mvn/GenerateDaoMojo.java new file mode 100644 index 0000000000..c7cb63f599 --- /dev/null +++ b/maven-plugin/src/main/java/org/hibernate/mvn/GenerateDaoMojo.java @@ -0,0 +1,75 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2016-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.mvn; + +import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES; + +import java.io.File; + +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.hbm2x.DAOExporter; + +/** + * Mojo to generate Data Access Objects (DAOs) from an existing database. + *

+ * See: https://docs.jboss.org/tools/latest/en/hibernatetools/html_single/#d0e4821 + */ +@Mojo( + name = "hbm2dao", + defaultPhase = GENERATE_SOURCES, + requiresDependencyResolution = ResolutionScope.RUNTIME) +public class GenerateDaoMojo extends AbstractHbm2xMojo { + + /** The directory into which the DAOs will be generated. */ + @Parameter(defaultValue = "${project.build.directory}/generated-sources/") + private File outputDirectory; + + /** Code will contain EJB 3 features, e.g. using annotations from javax.persistence + * and org.hibernate.annotations. */ + @Parameter(defaultValue = "false") + private boolean ejb3; + + /** Code will contain JDK 5 constructs such as generics and static imports. */ + @Parameter(defaultValue = "false") + private boolean jdk5; + + /** A path used for looking up user-edited templates. */ + @Parameter + private String templatePath; + + protected void executeExporter(MetadataDescriptor metadataDescriptor) { + DAOExporter daoExporter = new DAOExporter(); + daoExporter.setMetadataDescriptor(metadataDescriptor); + daoExporter.setOutputDirectory(outputDirectory); + if (templatePath != null) { + getLog().info("Setting template path to: " + templatePath); + daoExporter.setTemplatePath(new String[]{templatePath}); + } + daoExporter.getProperties().setProperty("ejb3", String.valueOf(ejb3)); + daoExporter.getProperties().setProperty("jdk5", String.valueOf(jdk5)); + getLog().info("Starting DAO export to directory: " + outputDirectory + "..."); + daoExporter.start(); + } + + +} diff --git a/maven-plugin/src/main/java/org/hibernate/mvn/GenerateHbmMojo.java b/maven-plugin/src/main/java/org/hibernate/mvn/GenerateHbmMojo.java new file mode 100644 index 0000000000..2a2b368efd --- /dev/null +++ b/maven-plugin/src/main/java/org/hibernate/mvn/GenerateHbmMojo.java @@ -0,0 +1,67 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2016-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.mvn; + +import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES; + +import java.io.File; + +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.hbm2x.HibernateMappingExporter; + +/** + * Mojo to generate hbm.xml files from an existing database. + *

+ * See: https://docs.jboss.org/tools/latest/en/hibernatetools/html_single/#d0e4821 + */ +@Mojo( + name = "generateHbm", + defaultPhase = GENERATE_SOURCES, + requiresDependencyResolution = ResolutionScope.RUNTIME) +public class GenerateHbmMojo extends AbstractHbm2xMojo { + + /** The directory into which the DAOs will be generated. */ + @Parameter(defaultValue = "${project.basedir}/src/main/resources") + private File outputDirectory; + + @Parameter + private String templatePath; + + protected void executeExporter(MetadataDescriptor metadataDescriptor) { + try { + HibernateMappingExporter hbmExporter = new HibernateMappingExporter(); + hbmExporter.setMetadataDescriptor(metadataDescriptor); + hbmExporter.setOutputDirectory(outputDirectory); + if (templatePath != null) { + getLog().info("Setting template path to: " + templatePath); + hbmExporter.setTemplatePath(new String[] {templatePath}); + } + getLog().info("Starting HBM export to directory: " + outputDirectory + "..."); + hbmExporter.start(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + +} diff --git a/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2DdlMojo.java b/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2DdlMojo.java new file mode 100644 index 0000000000..1eec0618d0 --- /dev/null +++ b/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2DdlMojo.java @@ -0,0 +1,81 @@ +package org.hibernate.mvn; + +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.hibernate.boot.Metadata; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.hbm2ddl.SchemaExport; +import org.hibernate.tool.schema.TargetType; + +import java.io.File; +import java.util.EnumSet; +import java.util.Set; + +import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_RESOURCES; + +/** + * Mojo to generate DDL Scripts from an existing database. + *

+ * See https://docs.jboss.org/tools/latest/en/hibernatetools/html_single/#d0e4651 + */ +@Mojo( + name = "hbm2ddl", + defaultPhase = GENERATE_RESOURCES, + requiresDependencyResolution = ResolutionScope.RUNTIME) +public class Hbm2DdlMojo extends AbstractHbm2xMojo { + + /** The directory into which the DDLs will be generated. */ + @Parameter(defaultValue = "${project.build.directory}/generated-resources/") + private File outputDirectory; + + /** The default filename of the generated DDL script. */ + @Parameter(defaultValue = "schema.ddl") + private String outputFileName; + + /** The type of output to produce. + *

    + *
  • DATABASE: Export to the database.
  • + *
  • SCRIPT (default): Write to a script file.
  • + *
  • STDOUT: Write to {@link System#out}.
  • + *
*/ + @Parameter(defaultValue = "SCRIPT") + private Set targetTypes; + + /** + * The DDLs statements to create. + *
    + *
  • NONE: None - duh :P.
  • + *
  • CREATE (default): Create only.
  • + *
  • DROP: Drop only.
  • + *
  • BOTH: Drop and then create.
  • + *
+ */ + @Parameter(defaultValue = "CREATE") + private SchemaExport.Action schemaExportAction; + + /** Set the end of statement delimiter. */ + @Parameter(defaultValue = ";") + private String delimiter; + + /** Should we format the sql strings? */ + @Parameter(defaultValue = "true") + private boolean format; + + /** Should we stop once an error occurs? */ + @Parameter(defaultValue = "true") + private boolean haltOnError; + + + @Override + protected void executeExporter(MetadataDescriptor metadataDescriptor) { + Metadata metadata = metadataDescriptor.createMetadata(); + + SchemaExport export = new SchemaExport(); + export.setOutputFile(new File(outputDirectory, outputFileName).toString()); + export.setDelimiter(delimiter); + export.setHaltOnError(haltOnError); + export.setFormat(format); + export.execute(EnumSet.copyOf(this.targetTypes), schemaExportAction, metadata); + } +} diff --git a/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2JavaMojo.java b/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2JavaMojo.java new file mode 100644 index 0000000000..5037804569 --- /dev/null +++ b/maven-plugin/src/main/java/org/hibernate/mvn/Hbm2JavaMojo.java @@ -0,0 +1,56 @@ +package org.hibernate.mvn; + +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.hbm2x.POJOExporter; + +import java.io.File; + +import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES; + +/** + * Mojo to generate Java JPA Entities from an existing database. + *

+ * See: https://docs.jboss.org/tools/latest/en/hibernatetools/html_single/#d0e4821 + */ +@Mojo( + name = "hbm2java", + defaultPhase = GENERATE_SOURCES, + requiresDependencyResolution = ResolutionScope.RUNTIME) +public class Hbm2JavaMojo extends AbstractHbm2xMojo { + + /** The directory into which the JPA entities will be generated. */ + @Parameter(defaultValue = "${project.build.directory}/generated-sources/") + private File outputDirectory; + + /** Code will contain EJB 3 features, e.g. using annotations from javax.persistence + * and org.hibernate.annotations. */ + @Parameter(defaultValue = "false") + private boolean ejb3; + + /** Code will contain JDK 5 constructs such as generics and static imports. */ + @Parameter(defaultValue = "false") + private boolean jdk5; + + /** A path used for looking up user-edited templates. */ + @Parameter + private String templatePath; + + protected void executeExporter(MetadataDescriptor metadataDescriptor) { + POJOExporter pojoExporter = new POJOExporter(); + pojoExporter.setMetadataDescriptor(metadataDescriptor); + pojoExporter.setOutputDirectory(outputDirectory); + if (templatePath != null) { + getLog().info("Setting template path to: " + templatePath); + pojoExporter.setTemplatePath(new String[]{templatePath}); + } + pojoExporter.getProperties().setProperty("ejb3", String.valueOf(ejb3)); + pojoExporter.getProperties().setProperty("jdk5", String.valueOf(jdk5)); + getLog().info("Starting POJO export to directory: " + outputDirectory + "..."); + pojoExporter.start(); + } + + +} diff --git a/maven-plugin/src/site/site.xml b/maven-plugin/src/site/site.xml new file mode 100644 index 0000000000..44e762a10c --- /dev/null +++ b/maven-plugin/src/site/site.xml @@ -0,0 +1,29 @@ + + + + + org.apache.maven.skins + maven-fluido-skin + 1.7 + + + + + + apache/maven-skins + right + gray + + + + + +

+ + + + + + diff --git a/pom.xml b/pom.xml index 8ac0164d04..4f6b77ad36 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,19 @@ + + + + To build this project JDK ${jdk.min.version} (or greater) is required. Please install it. + ${jdk.min.version} + + + + + + + + + + + + release + + + performRelease + true + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + ${local.staging.releases.repo.id}::${local.staging.releases.repo.url} + + + + + + + diff --git a/readme.txt b/readme.txt deleted file mode 100644 index 48068ef272..0000000000 --- a/readme.txt +++ /dev/null @@ -1,16 +0,0 @@ -Development ------------ -The project is developed under the form of a hierarchical multimodule Maven project. -After cloning the git repository to your local machine you can import it as such into -your favorite IDE. -However in order to compile and run the tests one additional step is required: you need -to download the Oracle JDBC driver (currently we are using ojdbc8.jar) and use the Maven -command to install it into your local repository: - - mvn install:install-file - -Dfile=/path/to/local/ojdbc8.jar - -DgroupId=com.oracle.jdbc - -DartifactId=ojdbc8 - -Dversion=12.2.0.1 - -Dpackaging=jar - \ No newline at end of file diff --git a/test/common/pom.xml b/test/common/pom.xml index 240a47d15e..4ebd1644c5 100644 --- a/test/common/pom.xml +++ b/test/common/pom.xml @@ -8,7 +8,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-common @@ -24,13 +24,10 @@ org.hibernate hibernate-tools-tests-utils - - junit - junit - - jaxen - jaxen + org.junit.jupiter + junit-jupiter-engine + compile diff --git a/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/AnyKindOfUserType.java b/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/AnyKindOfUserType.java index 13095b4851..7c6e906642 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/AnyKindOfUserType.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/AnyKindOfUserType.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.AntHibernateTool; import java.io.Serializable; import java.sql.PreparedStatement; diff --git a/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/TestCase.java index d850663cf7..48ab99e46b 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/AntHibernateTool/TestCase.java @@ -1,36 +1,59 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.AntHibernateTool; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -51,36 +74,36 @@ public void testHbm2DDLLogic() throws Exception { File dropAndCreate = new File(destinationDir, "dropandcreate.sql"); File update = new File(destinationDir, "update.sql"); - Assert.assertFalse(topDown.exists()); - Assert.assertFalse(onlyDrop.exists()); - Assert.assertFalse(onlyCreate.exists()); - Assert.assertFalse(dropAndCreate.exists()); - Assert.assertFalse(update.exists()); + assertFalse(topDown.exists()); + assertFalse(onlyDrop.exists()); + assertFalse(onlyCreate.exists()); + assertFalse(dropAndCreate.exists()); + assertFalse(update.exists()); project.executeTarget("testHbm2DDLLogic"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(topDown.exists()); + assertTrue(topDown.exists()); - Assert.assertTrue(onlyDrop.exists()); - Assert.assertNull(FileUtil.findFirstString("create", onlyDrop)); - Assert.assertNotNull(FileUtil.findFirstString("drop", onlyDrop)); + assertTrue(onlyDrop.exists()); + assertNull(FileUtil.findFirstString("create", onlyDrop)); + assertNotNull(FileUtil.findFirstString("drop", onlyDrop)); - Assert.assertTrue(onlyCreate.exists()); - Assert.assertNull(FileUtil.findFirstString("drop", onlyCreate)); - Assert.assertNotNull(FileUtil.findFirstString("create", onlyCreate)); - Assert.assertNotNull(FileUtil.findFirstString("---", onlyCreate)); + assertTrue(onlyCreate.exists()); + assertNull(FileUtil.findFirstString("drop", onlyCreate)); + assertNotNull(FileUtil.findFirstString("create", onlyCreate)); + assertNotNull(FileUtil.findFirstString("---", onlyCreate)); - Assert.assertTrue(dropAndCreate.exists()); - Assert.assertNotNull(FileUtil.findFirstString("drop", dropAndCreate)); - Assert.assertNotNull(FileUtil.findFirstString("create", dropAndCreate)); - Assert.assertNotNull(FileUtil.findFirstString("---", dropAndCreate)); + assertTrue(dropAndCreate.exists()); + assertNotNull(FileUtil.findFirstString("drop", dropAndCreate)); + assertNotNull(FileUtil.findFirstString("create", dropAndCreate)); + assertNotNull(FileUtil.findFirstString("---", dropAndCreate)); - Assert.assertTrue(update.exists()); - Assert.assertNotNull(FileUtil.findFirstString("create", update)); - Assert.assertNotNull(FileUtil.findFirstString("---", update)); + assertTrue(update.exists()); + assertNotNull(FileUtil.findFirstString("create", update)); + assertNotNull(FileUtil.findFirstString("---", update)); } @@ -99,22 +122,22 @@ public void testHbm2DDLUpdateExecution() { File update1 = new File(destinationDir, "update1.sql"); File update2 = new File(destinationDir, "update2.sql"); - Assert.assertFalse(topDown.exists()); - Assert.assertFalse(onlyDrop.exists()); - Assert.assertFalse(update1.exists()); - Assert.assertFalse(update2.exists()); + assertFalse(topDown.exists()); + assertFalse(onlyDrop.exists()); + assertFalse(update1.exists()); + assertFalse(update2.exists()); project.executeTarget("testantcfgUpdateExecuted"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(topDown.exists()); - Assert.assertTrue(onlyDrop.exists()); - Assert.assertTrue(update1.exists()); - Assert.assertNotNull(FileUtil.findFirstString("create", update1)); - Assert.assertTrue(update2.exists()); - Assert.assertEquals(0, update2.length()); + assertTrue(topDown.exists()); + assertTrue(onlyDrop.exists()); + assertTrue(update1.exists()); + assertNotNull(FileUtil.findFirstString("create", update1)); + assertTrue(update2.exists()); + assertEquals(0, update2.length()); } @@ -132,20 +155,20 @@ public void testHbm2DDLExportExecution() throws Exception { File update = new File(destinationDir, "update.sql"); File onlydrop = new File(destinationDir, "onlydrop.sql"); - Assert.assertFalse(export.exists()); - Assert.assertFalse(update.exists()); - Assert.assertFalse(onlydrop.exists()); + assertFalse(export.exists()); + assertFalse(update.exists()); + assertFalse(onlydrop.exists()); project.executeTarget("testantcfgExportExecuted"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(export.exists()); - Assert.assertTrue(update.exists()); - Assert.assertNotNull(FileUtil.findFirstString("create", export)); + assertTrue(export.exists()); + assertTrue(update.exists()); + assertNotNull(FileUtil.findFirstString("create", export)); // if export is executed, update should be empty - Assert.assertEquals(0, update.length()); + assertEquals(0, update.length()); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmNoError/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmNoError/TestCase.java index 538874672f..58e0b2bbd9 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmNoError/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmNoError/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmNoError; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,12 +68,12 @@ public void testCfg2HbmNoError() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hbmxml = new File(destinationDir, "VerySimpleTable.hbm.xml"); - Assert.assertFalse(hbmxml.exists()); + assertFalse(hbmxml.exists()); project.executeTarget("testCfg2HbmNoError"); - Assert.assertTrue(hbmxml.exists()); - Assert.assertTrue(FileUtil + assertTrue(hbmxml.exists()); + assertTrue(FileUtil .findFirstString("class", hbmxml) .contains("VerySimpleTable")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/Strategy.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/Strategy.java index 65210dc5dd..3e60a7c301 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/Strategy.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/Strategy.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithCustomReverseNamingStrategy; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/TestCase.java index 64bb5901ae..a3996ed461 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithCustomReverseNamingStrategy; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,12 +68,12 @@ public void testCfg2HbmWithCustomReverseNamingStrategy() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hbmxml = new File(destinationDir, "foo/Bar.hbm.xml"); - Assert.assertFalse(hbmxml.exists()); + assertFalse(hbmxml.exists()); project.executeTarget("testCfg2HbmWithCustomReverseNamingStrategy"); - Assert.assertTrue(hbmxml.exists()); - Assert.assertTrue(FileUtil + assertTrue(hbmxml.exists()); + assertTrue(FileUtil .findFirstString("class", hbmxml) .contains("foo.Bar")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithInvalidReverseNamingStrategy/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithInvalidReverseNamingStrategy/TestCase.java index 40e84739a2..94ae1e8749 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithInvalidReverseNamingStrategy/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithInvalidReverseNamingStrategy/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithInvalidReverseNamingStrategy; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -50,11 +70,11 @@ public void testCfg2HbmWithInvalidReverseNamingStrategy() { try { project.executeTarget("testCfg2HbmWithInvalidReverseNamingStrategy"); - Assert.fail("A BuildException should happen!"); + fail("A BuildException should happen!"); } catch (BuildException e) { - Assert.assertTrue(e + assertTrue(e .getMessage() .contains("Could not create or find invalid.Strategy")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageName/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageName/TestCase.java index f70f6fa191..eaab0018dd 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageName/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageName/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithPackageName; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,12 +68,12 @@ public void testCfg2HbmWithPackageName() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hbmxml = new File(destinationDir, "foo/bar/VerySimpleTable.hbm.xml"); - Assert.assertFalse(hbmxml.exists()); + assertFalse(hbmxml.exists()); project.executeTarget("testCfg2HbmWithPackageName"); - Assert.assertTrue(hbmxml.exists()); - Assert.assertTrue(FileUtil + assertTrue(hbmxml.exists()); + assertTrue(FileUtil .findFirstString("class", hbmxml) .contains("foo.bar.VerySimpleTable")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/Strategy.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/Strategy.java index 8b0ec9f45e..fef4ea8386 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/Strategy.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/Strategy.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithPackageNameAndReverseNamingStrategy; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/TestCase.java index 49ae729b08..4a561f39cf 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/TestCase.java @@ -1,35 +1,54 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Cfg2HbmWithPackageNameAndReverseNamingStrategy; +import static org.junit.jupiter.api.Assertions.assertFalse; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -47,7 +66,7 @@ public void testCfg2HbmWithPackageNameAndReverseNamingStrategy() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hbmxml = new File(destinationDir, "foo/Bar.hbm.xml"); - Assert.assertFalse(hbmxml.exists()); + assertFalse(hbmxml.exists()); project.executeTarget("testCfg2HbmWithPackageNameAndReverseNamingStrategy"); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/EJB3Configuration/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/EJB3Configuration/TestCase.java index 2944b7b434..c315f68ee7 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/EJB3Configuration/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/EJB3Configuration/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.EJB3Configuration; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,12 +69,12 @@ public void testEJB3ConfigurationFailureExpected() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File ejb3 = new File(destinationDir, "ejb3.sql"); - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); project.executeTarget("testEJB3Configuration"); - Assert.assertTrue(ejb3.exists()); - Assert.assertNotNull(FileUtil.findFirstString("create", ejb3)); + assertTrue(ejb3.exists()); + assertNotNull(FileUtil.findFirstString("create", ejb3)); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/GenericExport/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/GenericExport/TestCase.java index 83b37c2f2a..b860a3685d 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/GenericExport/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/GenericExport/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.GenericExport; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,36 +68,36 @@ public void testGenericExport() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File xTopDownJava = new File(destinationDir, "Xorg/hibernate/tool/hbm2x/ant/TopDown.java"); - Assert.assertFalse(xTopDownJava.exists()); + assertFalse(xTopDownJava.exists()); File topDownJava = new File(destinationDir, "org/hibernate/tool/hbm2x/ant/TopDown.java"); - Assert.assertFalse(topDownJava.exists()); + assertFalse(topDownJava.exists()); File topDownQuote = new File(destinationDir, "org/hibernate/tool/hbm2x/ant/TopDown.quote"); - Assert.assertFalse(topDownQuote.exists()); + assertFalse(topDownQuote.exists()); File topDownPojo = new File(destinationDir, "org/hibernate/tool/hbm2x/ant/TopDown.pojo"); - Assert.assertFalse(topDownPojo.exists()); + assertFalse(topDownPojo.exists()); project.executeTarget("testGenericExport"); - Assert.assertTrue(xTopDownJava.exists()); - Assert.assertTrue(FileUtil + assertTrue(xTopDownJava.exists()); + assertTrue(FileUtil .findFirstString("TopDown", xTopDownJava) .contains("TopDown generated by hbm2java")); - Assert.assertTrue(topDownJava.exists()); - Assert.assertTrue(FileUtil + assertTrue(topDownJava.exists()); + assertTrue(FileUtil .findFirstString("TopDown", topDownJava) .contains("TopDown generated by hbm2java")); - Assert.assertTrue(topDownQuote.exists()); - Assert.assertTrue(FileUtil + assertTrue(topDownQuote.exists()); + assertTrue(FileUtil .findFirstString("TopDown", topDownQuote) .contains("pojo=TopDown")); - Assert.assertTrue(topDownPojo.exists()); - Assert.assertTrue(FileUtil + assertTrue(topDownPojo.exists()); + assertTrue(FileUtil .findFirstString("TopDown", topDownPojo) .contains("TopDown generated by hbm2java")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaConfiguration/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaConfiguration/TestCase.java index 5782a6f696..f1875d6276 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaConfiguration/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaConfiguration/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Hbm2JavaConfiguration; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,15 +69,15 @@ public void testHbm2JavaConfiguration() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File someClass = new File(destinationDir, "SomeClass.java"); - Assert.assertFalse(someClass.exists()); + assertFalse(someClass.exists()); project.executeTarget("testHbm2JavaConfiguration"); - Assert.assertTrue(someClass.exists()); - Assert.assertTrue(FileUtil + assertTrue(someClass.exists()); + assertTrue(FileUtil .findFirstString("SomeClass", someClass) .contains("SomeClass generated by hbm2java")); - Assert.assertNull(FileUtil.findFirstString("@Entity", someClass)); + assertNull(FileUtil.findFirstString("@Entity", someClass)); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/TestCase.java index 26aab4c1b5..f82798fa86 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Hbm2JavaEJB3Configuration; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,15 +69,15 @@ public void testHbm2JavaConfiguration() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File someClass = new File(destinationDir, "SomeClass.java"); - Assert.assertFalse(someClass.exists()); + assertFalse(someClass.exists()); project.executeTarget("testHbm2JavaEJB3Configuration"); - Assert.assertTrue(someClass.exists()); - Assert.assertTrue(FileUtil + assertTrue(someClass.exists()); + assertTrue(FileUtil .findFirstString("SomeClass", someClass) .contains("SomeClass generated by hbm2java")); - Assert.assertNotNull(FileUtil.findFirstString("@Entity", someClass)); + assertNotNull(FileUtil.findFirstString("@Entity", someClass)); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/HbmLint/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/HbmLint/TestCase.java index d9479d51a6..68548877e8 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/HbmLint/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/HbmLint/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.HbmLint; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,37 +68,37 @@ public void testHbmLint() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hbmLintResult = new File(destinationDir, "hbmlint-result.txt"); - Assert.assertFalse(hbmLintResult.exists()); + assertFalse(hbmLintResult.exists()); project.executeTarget("testHbmLint"); - Assert.assertTrue(hbmLintResult.exists()); + assertTrue(hbmLintResult.exists()); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("BadType", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("Category", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("Column", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("does_not_exist", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("hilo_table", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("MissingTable", hbmLintResult) .contains("SCHEMA_TABLE_MISSING")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("MISSING_ID_GENERATOR", hbmLintResult) .contains("does_not_exist")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/TestCase.java index 8cdba6814d..3eb3f71ed0 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JDBCConfigWithRevEngXml; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,18 +68,18 @@ public void testJDBCConfigWithRevEngXml() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File bottomUp = new File(destinationDir, "foo/BottomUp.java"); - Assert.assertFalse(bottomUp.exists()); + assertFalse(bottomUp.exists()); project.executeTarget("testJDBCConfigWithRevEngXml"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(bottomUp.exists()); - Assert.assertTrue(FileUtil + assertTrue(bottomUp.exists()); + assertTrue(FileUtil .findFirstString("good", bottomUp) .contains("Boolean")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("something", bottomUp) .contains("SomeUserType")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfiguration/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfiguration/TestCase.java index 339aeba7e4..237cc35e73 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfiguration/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/JDBCConfiguration/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JDBCConfiguration; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -56,27 +76,27 @@ public void testJDBCConfiguration() { File withTemplate = new File(destinationDir, "with-template/BottomUp.java"); File cfgxml = new File(destinationDir, "cfgxml/hibernate.cfg.xml"); - Assert.assertFalse(noTemplate.exists()); - Assert.assertFalse(withTemplate.exists()); - Assert.assertFalse(cfgxml.exists()); + assertFalse(noTemplate.exists()); + assertFalse(withTemplate.exists()); + assertFalse(cfgxml.exists()); project.executeTarget("testJDBCConfiguration"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(noTemplate.exists()); - Assert.assertTrue(FileUtil + assertTrue(noTemplate.exists()); + assertTrue(FileUtil .findFirstString("public", noTemplate) .contains("BottomUp")); - Assert.assertTrue(withTemplate.exists()); - Assert.assertTrue(FileUtil + assertTrue(withTemplate.exists()); + assertTrue(FileUtil .findFirstString("template", withTemplate) .contains("/** Made by a template in your neighborhood */")); - Assert.assertTrue(cfgxml.exists()); - Assert.assertTrue(FileUtil + assertTrue(cfgxml.exists()); + assertTrue(FileUtil .findFirstString("mapping", cfgxml) .contains("BottomUp.hbm.xml")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/JPABogusPUnit/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/JPABogusPUnit/TestCase.java index 88308fdcce..325f68e068 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/JPABogusPUnit/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/JPABogusPUnit/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JPABogusPUnit; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,17 +69,17 @@ public void testJPABogusPUnit() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File ejb3 = new File(destinationDir, "ejb3.sql"); - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); try { project.executeTarget("testJPABogusPUnit"); - Assert.fail("The Bogus unit was accepted"); + fail("The Bogus unit was accepted"); } catch (BuildException e) { String log = AntUtil.getLog(project); - Assert.assertTrue(log, log.contains("Persistence unit not found: 'shouldnotbethere'")); + assertTrue(log.contains("Persistence unit not found: 'shouldnotbethere'"), log); } - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/JPAPUnit/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/JPAPUnit/TestCase.java index eab81f2871..0efbf88c22 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/JPAPUnit/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/JPAPUnit/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JPAPUnit; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,12 +69,12 @@ public void testJPAPUnit() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File ejb3 = new File(destinationDir, "ejb3.sql"); - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); project.executeTarget("testJPAPUnit"); - Assert.assertTrue(ejb3.exists()); - Assert.assertNotNull(FileUtil.findFirstString("create", ejb3)); + assertTrue(ejb3.exists()); + assertNotNull(FileUtil.findFirstString("create", ejb3)); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/TestCase.java index 6053a3466b..c12d81b2ae 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JPAPropertyOverridesPUnit; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,17 +69,17 @@ public void testJPAPUnit() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File ejb3 = new File(destinationDir, "ejb3.sql"); - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); try { project.executeTarget("testJPAPropertyOverridesPUnit"); - Assert.fail("property overrides not accepted"); + fail("property overrides not accepted"); } catch (BuildException e) { // should happen - Assert.assertTrue(e.getMessage().contains("FAKEDialect")); + assertTrue(e.getMessage().contains("FAKEDialect")); } - Assert.assertFalse(ejb3.exists()); + assertFalse(ejb3.exists()); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Properties/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Properties/TestCase.java index 90a0aa38aa..d737b0557c 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Properties/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Properties/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Properties; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -53,31 +73,31 @@ public void testProperties() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File file = new File(destinationDir, "SomeClass.java"); - Assert.assertFalse(file.exists()); + assertFalse(file.exists()); project.executeTarget("testProperties"); String log = AntUtil.getLog(project); - Assert.assertTrue(log, !log.contains("Exception")); + assertTrue(!log.contains("Exception"), log); - Assert.assertTrue(file.exists()); + assertTrue(file.exists()); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("hbm2java.weirdAl", file) .contains("foo3")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("ant.project.name", file) .contains("PropertiesTest")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("foo.weirdAl", file) .contains("does not exist")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("bar", file) .contains("foo2")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("file", file) .contains("some.file")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("value", file) .contains("some value")); diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Query/ObjectResult.java b/test/common/src/main/java/org/hibernate/tool/ant/Query/ObjectResult.java index b0e04ed065..08bdf143fd 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Query/ObjectResult.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Query/ObjectResult.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Query; public class ObjectResult { diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Query/SerializableResult.java b/test/common/src/main/java/org/hibernate/tool/ant/Query/SerializableResult.java index 171e7b2fab..9361ae14ca 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Query/SerializableResult.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Query/SerializableResult.java @@ -1,7 +1,27 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Query; import java.io.Serializable; +@SuppressWarnings("serial") public class SerializableResult implements Serializable { public String id; diff --git a/test/common/src/main/java/org/hibernate/tool/ant/Query/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/Query/TestCase.java index bf09e3e9d1..bd08591034 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/Query/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/Query/TestCase.java @@ -1,36 +1,57 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Query; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -48,25 +69,25 @@ public void testQuery() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File hqlQuery = new File(destinationDir, "hqlQuery.txt"); - Assert.assertFalse(hqlQuery.exists()); + assertFalse(hqlQuery.exists()); File textQuery = new File(destinationDir, "textQuery.txt"); - Assert.assertFalse(textQuery.exists()); + assertFalse(textQuery.exists()); project.executeTarget("testQuery"); - Assert.assertTrue(hqlQuery.exists()); - Assert.assertTrue(FileUtil + assertTrue(hqlQuery.exists()); + assertTrue(FileUtil .findFirstString("First", hqlQuery) .contains("SerializableResult(id:First,length:1023)")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("Third", hqlQuery) .contains("ObjectResult(id:Third,length:4095)")); - Assert.assertTrue(textQuery.exists()); - Assert.assertTrue(FileUtil + assertTrue(textQuery.exists()); + assertTrue(FileUtil .findFirstString("First", textQuery) .contains("SerializableResult(id:First,length:1023)")); - Assert.assertNull(FileUtil.findFirstString("Third", textQuery)); + assertNull(FileUtil.findFirstString("Third", textQuery)); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/SchemaExportWarning/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/SchemaExportWarning/TestCase.java index a3abfd42e8..caa54354f0 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/SchemaExportWarning/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/SchemaExportWarning/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.SchemaExportWarning; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -47,17 +67,17 @@ public void testSchemaExport() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File schemaExport = new File(destinationDir, "schemaexport.sql"); - Assert.assertFalse(schemaExport.exists()); + assertFalse(schemaExport.exists()); project.executeTarget("testSchemaExportWarning"); - Assert.assertTrue(schemaExport.exists()); - Assert.assertTrue(FileUtil + assertTrue(schemaExport.exists()); + assertTrue(FileUtil .findFirstString("drop", schemaExport) .contains("TopDown")); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); } diff --git a/test/common/src/main/java/org/hibernate/tool/ant/SchemaUpdateWarning/TestCase.java b/test/common/src/main/java/org/hibernate/tool/ant/SchemaUpdateWarning/TestCase.java index f2e1c021ac..e88bac6cbe 100644 --- a/test/common/src/main/java/org/hibernate/tool/ant/SchemaUpdateWarning/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/ant/SchemaUpdateWarning/TestCase.java @@ -1,36 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.SchemaUpdateWarning; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -47,19 +67,19 @@ public void testSchemaUpdateWarning() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File schemaUpdate = new File(destinationDir, "schemaupdate.sql"); - Assert.assertFalse(schemaUpdate.exists()); + assertFalse(schemaUpdate.exists()); project.executeTarget("testSchemaUpdateWarning"); - Assert.assertTrue(schemaUpdate.exists()); - Assert.assertTrue(FileUtil + assertTrue(schemaUpdate.exists()); + assertTrue(FileUtil .findFirstString("create", schemaUpdate) .contains("TopDown")); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); - Assert.assertTrue(log.contains("Hibernate Core SchemaUpdate")); - Assert.assertTrue(log.contains("tools.hibernate.org")); + assertFalse(log.contains("Exception")); + assertTrue(log.contains("Hibernate Core SchemaUpdate")); + assertTrue(log.contains("tools.hibernate.org")); } diff --git a/test/common/src/main/java/org/hibernate/tool/cfg/DriverMetaData/TestCase.java b/test/common/src/main/java/org/hibernate/tool/cfg/DriverMetaData/TestCase.java index 648c276d26..32715ccc47 100644 --- a/test/common/src/main/java/org/hibernate/tool/cfg/DriverMetaData/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/cfg/DriverMetaData/TestCase.java @@ -4,6 +4,9 @@ */ package org.hibernate.tool.cfg.DriverMetaData; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.Map; import java.util.Properties; @@ -21,10 +24,9 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -35,7 +37,7 @@ public class TestCase { private Properties properties = null; private ServiceRegistry serviceRegistry; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); properties = Environment.getProperties(); @@ -43,7 +45,7 @@ public void setUp() { serviceRegistry = ssrb.build(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -86,10 +88,10 @@ public void testExportedKeys() { exportedKeys.next(); cnt++; } - Assert.assertEquals(1,cnt); + assertEquals(1,cnt); } } - Assert.assertTrue(foundMaster); + assertTrue(foundMaster); } @Test diff --git a/test/common/src/main/java/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/TestCase.java b/test/common/src/main/java/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/TestCase.java index 403d490328..cd6bd1d892 100644 --- a/test/common/src/main/java/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/TestCase.java @@ -1,13 +1,33 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.cfg.JDBCMetaDataConfiguration; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.hibernate.boot.Metadata; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -15,12 +35,12 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -30,15 +50,15 @@ public void testReadFromJDBC() throws Exception { Metadata metadata = MetadataDescriptorFactory .createJdbcDescriptor(null, null, true) .createMetadata(); - Assert.assertNotNull("WithRealTimestamp", metadata.getEntityBinding("WithRealTimestamp")); - Assert.assertNotNull("NoVersion", metadata.getEntityBinding("NoVersion")); - Assert.assertNotNull("WithFakeTimestamp", metadata.getEntityBinding("WithFakeTimestamp")); - Assert.assertNotNull("WithVersion", metadata.getEntityBinding("WithVersion")); + assertNotNull(metadata.getEntityBinding("WithRealTimestamp"), "WithRealTimestamp"); + assertNotNull(metadata.getEntityBinding("NoVersion"), "NoVersion"); + assertNotNull(metadata.getEntityBinding("WithFakeTimestamp"), "WithFakeTimestamp"); + assertNotNull(metadata.getEntityBinding("WithVersion"), "WithVersion"); } @Test public void testGetTable() throws Exception { - Assert.assertNotNull( + assertNotNull( HibernateUtil.getTable( MetadataDescriptorFactory .createJdbcDescriptor(null, null, true) diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/CachedMetaData/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/CachedMetaData/TestCase.java index 1e67ca4f62..effef1004f 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/CachedMetaData/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/CachedMetaData/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.CachedMetaData; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.Iterator; import java.util.Map; import java.util.Properties; @@ -25,12 +44,9 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -121,12 +137,12 @@ public Iterator> getSuggestedPrimaryKeyStrategyName(String c } - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -178,15 +194,15 @@ private void validate(DatabaseCollector dc) { child = table; master = iterator.next(); } else { - Assert.fail("Only tables named 'MASTER' and 'CHILD' should exist"); + fail("Only tables named 'MASTER' and 'CHILD' should exist"); } - Assert.assertNotNull(child); - Assert.assertNotNull(master); + assertNotNull(child); + assertNotNull(master); iterator = dc.iterateTables(); - Assert.assertNotNull(iterator.next()); - Assert.assertNotNull(iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertNotNull(iterator.next()); + assertNotNull(iterator.next()); + assertFalse(iterator.hasNext()); JUnitUtil.assertIteratorContainsExactly( "should have recorded one foreignkey to child table", diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java index 64bbf918f0..b227e1858b 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java @@ -1,15 +1,29 @@ -/******************************************************************************* - * Copyright (c) 2010 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * Contributor: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.DefaultDatabaseCollector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -35,10 +49,9 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author Dmitry Geraskov @@ -46,12 +59,12 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -64,7 +77,7 @@ public void testReadOnlySpecificSchema() { List
tables = getTables(MetadataDescriptorFactory .createJdbcDescriptor(res, null, true) .createMetadata()); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("cat.master")) { @@ -73,8 +86,8 @@ public void testReadOnlySpecificSchema() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals(new TableIdentifier(null, "cat.cat", "cat.child"), childid); - Assert.assertEquals(new TableIdentifier(null, "cat.cat", "cat.master"), masterid); + assertEquals(new TableIdentifier(null, "cat.cat", "cat.child"), childid); + assertEquals(new TableIdentifier(null, "cat.cat", "cat.master"), masterid); } @Test @@ -84,9 +97,9 @@ public void testNeedQuote() { ssrb.applySettings(properties); ServiceRegistry serviceRegistry = ssrb.build(); MetaDataDialect realMetaData = MetaDataDialectFactory.createMetaDataDialect( serviceRegistry.getService(JdbcServices.class).getDialect(), properties ); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.cat")); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.child")); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.master")); + assertTrue(realMetaData.needQuote("cat.cat"), "The name must be quoted!"); + assertTrue(realMetaData.needQuote("cat.child"), "The name must be quoted!"); + assertTrue(realMetaData.needQuote("cat.master"), "The name must be quoted!"); } /** @@ -111,11 +124,11 @@ properties, new DefaultReverseEngineeringStrategy(), DatabaseCollector dc = new DefaultDatabaseCollector(reader.getMetaDataDialect()); reader.readDatabaseSchema( dc, null, "cat.cat" ); String defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG); - Assert.assertNotNull("The table should be found", dc.getTable("cat.cat", defaultCatalog, "cat.child")); - Assert.assertNotNull("The table should be found", dc.getTable("cat.cat", defaultCatalog, "cat.master")); - Assert.assertNull("Quoted names should not return the table", dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.child"))); - Assert.assertNull("Quoted names should not return the table", dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.master"))); - Assert.assertEquals("Foreign key 'masterref' was filtered!", 1, dc.getOneToManyCandidates().size()); + assertNotNull(dc.getTable("cat.cat", defaultCatalog, "cat.child"), "The table should be found"); + assertNotNull(dc.getTable("cat.cat", defaultCatalog, "cat.master"), "The table should be found"); + assertNull(dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.child")), "Quoted names should not return the table"); + assertNull(dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.master")), "Quoted names should not return the table"); + assertEquals(1, dc.getOneToManyCandidates().size(), "Foreign key 'masterref' was filtered!"); } private static String quote(String name) { diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java index d7a019d80c..0c351227d8 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.DefaultSchemaCatalog; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -21,12 +39,9 @@ import org.hibernate.mapping.Table; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -34,12 +49,12 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -52,7 +67,7 @@ public void testReadOnlySpecificSchema() { List
tables = getTables(MetadataDescriptorFactory .createJdbcDescriptor(res, null, true) .createMetadata()); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("CATMASTER")) { @@ -61,8 +76,8 @@ public void testReadOnlySpecificSchema() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals(new TableIdentifier(null, "OVRTEST", "CATMASTER"), masterid); - Assert.assertEquals(new TableIdentifier(null, "OVRTEST", "CATCHILD"), childid); + assertEquals(new TableIdentifier(null, "OVRTEST", "CATMASTER"), masterid); + assertEquals(new TableIdentifier(null, "OVRTEST", "CATCHILD"), childid); } @Test @@ -82,9 +97,9 @@ public void testOverlapping() { Table element = iter.next(); boolean added = tables.add(TableIdentifier.create(element)); if(!added) - Assert.fail("duplicate table found for " + element); + fail("duplicate table found for " + element); } - Assert.assertEquals(4,tables.size()); + assertEquals(4,tables.size()); } @Test @@ -95,7 +110,7 @@ public void testUseDefault() { List
tables = getTables(MetadataDescriptorFactory .createJdbcDescriptor(null, properties, true) .createMetadata()); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("CATMASTER")) { @@ -104,8 +119,8 @@ public void testUseDefault() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals("jdbcreader has not nulled out according to default schema", new TableIdentifier(null, null, "CATMASTER"), masterid); - Assert.assertEquals("jdbcreader has not nulled out according to default schema", new TableIdentifier(null, null, "CATCHILD"), childid); + assertEquals(new TableIdentifier(null, null, "CATMASTER"), masterid, "jdbcreader has not nulled out according to default schema"); + assertEquals(new TableIdentifier(null, null, "CATCHILD"), childid, "jdbcreader has not nulled out according to default schema"); } private List
getTables(Metadata metadata) { diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBC/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBC/TestCase.java index 6a824134ca..cf563534d2 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBC/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBC/TestCase.java @@ -1,20 +1,39 @@ /* - * Created on 07-Dec-2004 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.GenerateFromJDBC; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.sql.SQLException; import java.util.Iterator; -import java.util.List; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.boot.Metadata; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; import org.hibernate.cfg.reveng.ReverseEngineeringSettings; @@ -29,12 +48,13 @@ import org.hibernate.tool.hbm2x.POJOExporter; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; /** * @author max @@ -42,23 +62,21 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputDir = new File("output"); private MetadataDescriptor metadataDescriptor = null; - private File outputDir = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); - outputDir = temporaryFolder.getRoot(); DefaultReverseEngineeringStrategy configurableNamingStrategy = new DefaultReverseEngineeringStrategy(); configurableNamingStrategy.setSettings(new ReverseEngineeringSettings(configurableNamingStrategy).setDefaultPackageName("org.reveng").setCreateCollectionForForeignKey(false)); metadataDescriptor = MetadataDescriptorFactory .createJdbcDescriptor(configurableNamingStrategy, null, true); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -84,44 +102,46 @@ public void testGenerateMappings() { exporter.start(); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/reveng/Child.hbm.xml")); File file = new File(outputDir, "GeneralHbmSettings.hbm.xml"); - Assert.assertTrue(file + " should not exist", !file.exists() ); + assertTrue(!file.exists(), file + " should not exist" ); File[] files = new File[2]; files[0] = new File(outputDir, "org/reveng/Child.hbm.xml"); files[1] = new File(outputDir, "org/reveng/Master.hbm.xml"); Metadata metadata = MetadataDescriptorFactory .createNativeDescriptor(null, files, null) .createMetadata(); - Assert.assertNotNull(metadata.getEntityBinding("org.reveng.Child") ); - Assert.assertNotNull(metadata.getEntityBinding("org.reveng.Master") ); + assertNotNull(metadata.getEntityBinding("org.reveng.Child") ); + assertNotNull(metadata.getEntityBinding("org.reveng.Master") ); } @Test - public void testGenerateCfgXml() throws DocumentException { + public void testGenerateCfgXml() throws Exception { Exporter exporter = new HibernateConfigurationExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(outputDir); exporter.start(); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "hibernate.cfg.xml")); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(new File(outputDir, "hibernate.cfg.xml")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(outputDir, "hibernate.cfg.xml")); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and it has no arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-configuration/session-factory/mapping"); - List list = xpath.selectNodes(document); - Element[] elements = new Element[list.size()]; - for (int i = 0; i < list.size(); i++) { - elements[i] = (Element)list.get(i); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-configuration/session-factory/mapping") + .evaluate(document, XPathConstants.NODESET); + Node[] elements = new Node[nodeList.getLength()]; + for (int i = 0; i < nodeList.getLength(); i++) { + elements[i] = (Node)nodeList.item(i); } - Assert.assertEquals(2,elements.length); + assertEquals(2, elements.length); for (int i = 0; i < elements.length; i++) { - Element element = elements[i]; - Assert.assertNotNull(element.attributeValue("resource")); - Assert.assertNull(element.attributeValue("class")); + Node element = elements[i]; + assertNotNull(element.getAttributes().getNamedItem("resource")); + assertNull(element.getAttributes().getNamedItem("class")); } } @Test - public void testGenerateAnnotationCfgXml() throws DocumentException { + public void testGenerateAnnotationCfgXml() throws Exception { HibernateConfigurationExporter exporter = new HibernateConfigurationExporter(); exporter.setMetadataDescriptor(metadataDescriptor); @@ -129,21 +149,23 @@ public void testGenerateAnnotationCfgXml() throws DocumentException { exporter.getProperties().setProperty("ejb3", "true"); exporter.start(); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "hibernate.cfg.xml")); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(new File(outputDir, "hibernate.cfg.xml")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(outputDir, "hibernate.cfg.xml")); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and it has no arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-configuration/session-factory/mapping"); - List list = xpath.selectNodes(document); - Element[] elements = new Element[list.size()]; - for (int i = 0; i < list.size(); i++) { - elements[i] = (Element)list.get(i); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-configuration/session-factory/mapping") + .evaluate(document, XPathConstants.NODESET); + Node[] elements = new Node[nodeList.getLength()]; + for (int i = 0; i < nodeList.getLength(); i++) { + elements[i] = (Node)nodeList.item(i); } - Assert.assertEquals(2, elements.length); + assertEquals(2, elements.length); for (int i = 0; i < elements.length; i++) { - Element element = elements[i]; - Assert.assertNull(element.attributeValue("resource")); - Assert.assertNotNull(element.attributeValue("class")); + Node element = elements[i]; + assertNull(element.getAttributes().getNamedItem("resource")); + assertNotNull(element.getAttributes().getNamedItem("class")); } } @@ -164,7 +186,7 @@ public void testPackageNames() { .iterator(); while (iter.hasNext() ) { PersistentClass element = iter.next(); - Assert.assertEquals("org.reveng", StringHelper.qualifier(element.getClassName() ) ); + assertEquals("org.reveng", StringHelper.qualifier(element.getClassName() ) ); } } } diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/TestCase.java index 4b735ce9f5..9b092756b7 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/TestCase.java @@ -1,5 +1,27 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.GenerateFromJDBCWithJavaKeyword; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; @@ -17,12 +39,10 @@ import org.hibernate.tool.hbm2x.POJOExporter; import org.hibernate.tools.test.util.JavaUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author koen@hibernate.org @@ -32,7 +52,7 @@ public class TestCase { private static String REVENG_XML = "\n"+ + " 'http://hibernate.org/dtd/hibernate-reverse-engineering-3.0.dtd'> \n"+ " \n"+ "
\n"+ " \n"+ " "; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private File outputDir = null; + @TempDir + public File outputDir = new File("output"); - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); - outputDir = temporaryFolder.getRoot(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -67,19 +84,19 @@ public void testGenerateJava() throws Exception { exporter.setOutputDirectory(outputDir); exporter.start(); File myReturn = new File(outputDir, "org/reveng/MyReturn.java"); - Assert.assertTrue(myReturn.exists()); + assertTrue(myReturn.exists()); File myReturnHistory = new File(outputDir, "org/reveng/MyReturnHistory.java"); - Assert.assertTrue(myReturnHistory.exists()); + assertTrue(myReturnHistory.exists()); JavaUtil.compile(outputDir); URLClassLoader loader = new URLClassLoader(new URL[] { outputDir.toURI().toURL() } ); Class returnClass = loader.loadClass("org.reveng.MyReturn"); - Assert.assertNotNull(returnClass); + assertNotNull(returnClass); Class returnHistoryClass = loader.loadClass("org.reveng.MyReturnHistory"); - Assert.assertNotNull(returnHistoryClass); + assertNotNull(returnHistoryClass); Field returnField = returnHistoryClass.getDeclaredField("return_"); - Assert.assertNotNull(returnField); + assertNotNull(returnField); Method returnSetter = returnHistoryClass.getMethod("setReturn", new Class[] { returnClass }); - Assert.assertNotNull(returnSetter); + assertNotNull(returnSetter); loader.close(); } diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/IncrementalSchemaReading/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/IncrementalSchemaReading/TestCase.java index 936fb95e2b..7e23a6943f 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/IncrementalSchemaReading/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/IncrementalSchemaReading/TestCase.java @@ -1,35 +1,58 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.IncrementalSchemaReading; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Properties; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; import org.hibernate.cfg.JDBCReaderFactory; +import org.hibernate.cfg.MetaDataDialectFactory; import org.hibernate.cfg.reveng.DatabaseCollector; import org.hibernate.cfg.reveng.DefaultDatabaseCollector; import org.hibernate.cfg.reveng.DefaultReverseEngineeringStrategy; import org.hibernate.cfg.reveng.JDBCReader; import org.hibernate.cfg.reveng.SchemaSelection; -import org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect; +import org.hibernate.cfg.reveng.dialect.MetaDataDialect; +import org.hibernate.dialect.Dialect; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.mapping.Table; import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.hbmlint.detector.TableSelectorStrategy; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -40,19 +63,9 @@ public class TestCase { private Properties properties = null; private String defaultSchema = null; private String defaultCatalog = null; + private List gottenTables = new ArrayList(); - public class MockedMetaDataDialect extends JDBCMetaDataDialect { - List gottenTables = new ArrayList(); - public Iterator> getTables(String catalog, String schema, String table) { - gottenTables.add(table); - return super.getTables( catalog, schema, table == null ? "%" : table ); - } - public Iterator> getColumns(String catalog, String schema, String table, String column) { - return super.getColumns(catalog, schema, table == null ? "%" : table, column == null ? "%" : column); - } - } - - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); properties = Environment.getProperties(); @@ -60,7 +73,7 @@ public void setUp() { defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -71,7 +84,9 @@ public void testReadSchemaIncremental() { builder.applySettings(properties); ServiceRegistry serviceRegistry = builder.build(); TableSelectorStrategy tss = new TableSelectorStrategy(new DefaultReverseEngineeringStrategy()); - MockedMetaDataDialect mockedMetaDataDialect = new MockedMetaDataDialect(); + Dialect dialect = serviceRegistry.getService(JdbcServices.class).getDialect(); + MetaDataDialect mockedMetaDataDialect = createMockedMetaDataDialect( + MetaDataDialectFactory.fromDialect(dialect)); JDBCReader reader = JDBCReaderFactory.newJDBCReader( properties, tss, mockedMetaDataDialect, serviceRegistry); tss.addSchemaSelection( new SchemaSelection(null,null, "CHILD") ); @@ -79,33 +94,33 @@ public void testReadSchemaIncremental() { DatabaseCollector dc = new DefaultDatabaseCollector(reader.getMetaDataDialect()); reader.readDatabaseSchema( dc, null, null ); - Assert.assertEquals(mockedMetaDataDialect.gottenTables.size(),1); - Assert.assertEquals(mockedMetaDataDialect.gottenTables.get(0),"CHILD"); + assertEquals(gottenTables.size(),1); + assertEquals(gottenTables.get(0),"CHILD"); Iterator
iterator = dc.iterateTables(); Table firstChild = iterator.next(); - Assert.assertEquals(firstChild.getName(), "CHILD"); - Assert.assertFalse(iterator.hasNext()); + assertEquals(firstChild.getName(), "CHILD"); + assertFalse(iterator.hasNext()); - Assert.assertFalse("should not record foreignkey to table it doesn't know about yet",firstChild.getForeignKeyIterator().hasNext()); + assertFalse(firstChild.getForeignKeyIterator().hasNext(), "should not record foreignkey to table it doesn't know about yet"); tss.clearSchemaSelections(); tss.addSchemaSelection( new SchemaSelection(null, null, "MASTER") ); - mockedMetaDataDialect.gottenTables.clear(); + gottenTables.clear(); reader.readDatabaseSchema( dc, null, null ); - Assert.assertEquals(mockedMetaDataDialect.gottenTables.size(),1); - Assert.assertEquals(mockedMetaDataDialect.gottenTables.get(0),"MASTER"); + assertEquals(gottenTables.size(),1); + assertEquals(gottenTables.get(0),"MASTER"); iterator = dc.iterateTables(); - Assert.assertNotNull(iterator.next()); - Assert.assertNotNull(iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertNotNull(iterator.next()); + assertNotNull(iterator.next()); + assertFalse(iterator.hasNext()); Table table = dc.getTable( defaultSchema, defaultCatalog, "CHILD" ); - Assert.assertSame( firstChild, table ); + assertSame( firstChild, table ); JUnitUtil.assertIteratorContainsExactly( "should have recorded one foreignkey to child table", @@ -118,7 +133,7 @@ public void testReadSchemaIncremental() { Table finalMaster = dc.getTable( defaultSchema, defaultCatalog, "MASTER" ); - Assert.assertSame(firstChild, dc.getTable( defaultSchema, defaultCatalog, "CHILD" )); + assertSame(firstChild, dc.getTable( defaultSchema, defaultCatalog, "CHILD" )); JUnitUtil.assertIteratorContainsExactly( null, firstChild.getForeignKeyIterator(), @@ -129,4 +144,31 @@ public void testReadSchemaIncremental() { 0); } + private MetaDataDialect createMockedMetaDataDialect(MetaDataDialect delegate) { + return (MetaDataDialect)Proxy.newProxyInstance( + getClass().getClassLoader(), + new Class[] { MetaDataDialect.class }, + new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if ("getTables".equals(method.getName())) { + gottenTables.add((String)args[2]); + return delegate.getTables( + (String)args[0], + (String)args[1], + args[2] == null ? "%" : (String)args[2]); + } else if ("getColumns".equals(method.getName())) { + return delegate.getColumns( + (String)args[0], + (String)args[1], + args[2] == null ? "%" : (String)args[2], + args[3] == null ? "%" : (String)args[3]); + } else { + return method.invoke(delegate, args); + + } + } + }); + } + } diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/TestCase.java index 342a328420..bf832ab16a 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.JdbcHbm2JavaEjb3; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -16,12 +34,10 @@ import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -30,15 +46,12 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputDir = new File("output"); - private File outputDir = null; - - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); - outputDir = temporaryFolder.getRoot(); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(MetadataDescriptorFactory .createJdbcDescriptor(null, null, true)); @@ -49,7 +62,7 @@ public void setUp() { exporter.start(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -61,13 +74,13 @@ public void testFileExistence() { @Test public void testUniqueConstraints() { - Assert.assertEquals(null, FileUtil.findFirstString( "uniqueConstraints", new File(outputDir,"Master.java") )); - Assert.assertNotNull(FileUtil.findFirstString( "uniqueConstraints", new File(outputDir,"Uniquemaster.java") )); + assertEquals(null, FileUtil.findFirstString( "uniqueConstraints", new File(outputDir,"Master.java") )); + assertNotNull(FileUtil.findFirstString( "uniqueConstraints", new File(outputDir,"Uniquemaster.java") )); } @Test public void testCompile() { - File destination = new File(temporaryFolder.getRoot(), "destination"); + File destination = new File(outputDir, "destination"); destination.mkdir(); List jars = new ArrayList(); jars.add(JavaUtil.resolvePathToJarFileFor(Persistence.class)); // for jpa api diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/Group.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/Group.java index 3c2159210f..073ff271c1 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/Group.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/Group.java @@ -1,4 +1,22 @@ -//$Id: Group.java 7085 2005-06-08 17:59:47Z oneovthafew $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.query.QueryExporterTest; import java.io.ObjectStreamClass; diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/TestCase.java index b026a29e54..c64b1a6f76 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/TestCase.java @@ -1,5 +1,26 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.query.QueryExporterTest; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.util.ArrayList; import java.util.EnumSet; @@ -19,28 +40,26 @@ import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); private File destinationDir = null; private File resourcesDir = null; private File userGroupHbmXmlFile = null; - @Before + @BeforeEach public void setUp() throws Exception { JdbcUtil.createDatabase(this); - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(temporaryFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(temporaryFolder, "resources"); resourcesDir.mkdir(); String[] resources = { "UserGroup.hbm.xml" }; ResourceUtil.createResources(this, resources, resourcesDir); @@ -77,14 +96,14 @@ public void testQueryExporter() throws Exception { JUnitUtil.assertIsNonEmptyFile(new File(destinationDir, "queryresult.txt")); } - @After + @AfterEach public void tearDown() throws Exception { SchemaExport export = new SchemaExport(); final EnumSet targetTypes = EnumSet.noneOf( TargetType.class ); targetTypes.add( TargetType.DATABASE ); export.drop(targetTypes, createMetadata()); if (export.getExceptions() != null && export.getExceptions().size() > 0){ - Assert.fail("Schema export failed"); + fail("Schema export failed"); } JdbcUtil.dropDatabase(this); } diff --git a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/User.java b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/User.java index 0aa90c4996..41e98986dd 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/User.java +++ b/test/common/src/main/java/org/hibernate/tool/hbm2x/query/QueryExporterTest/User.java @@ -1,4 +1,22 @@ -//$Id: User.java 7085 2005-06-08 17:59:47Z oneovthafew $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.query.QueryExporterTest; import java.io.ObjectStreamClass; diff --git a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenLazy.java b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenLazy.java index 50f29a821d..f0a6f4dd07 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenLazy.java +++ b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenLazy.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbmlint.HbmLintTest; public class BrokenLazy { diff --git a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenNonLazy.java b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenNonLazy.java index 4dcf47dcdc..c918bc510e 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenNonLazy.java +++ b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/BrokenNonLazy.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbmlint.HbmLintTest; public class BrokenNonLazy { diff --git a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/TestCase.java index 508b38fe52..643d5f5cb1 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbmlint/HbmLintTest/TestCase.java @@ -1,5 +1,26 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbmlint.HbmLintTest; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import org.hibernate.tool.api.metadata.MetadataDescriptor; @@ -10,11 +31,9 @@ import org.hibernate.tool.hbmlint.detector.InstrumentationDetector; import org.hibernate.tool.hbmlint.detector.ShadowedIdentifierDetector; import org.hibernate.tools.test.util.HibernateUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { @@ -24,19 +43,19 @@ public class TestCase { "BrokenLazy.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); private File outputDir = null; private File resourcesDir = null; private MetadataDescriptor metadataDescriptor = null; - @Before + @BeforeEach public void setUp() { - outputDir = new File(temporaryFolder.getRoot(), "output"); + outputDir = new File(temporaryFolder, "output"); outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(temporaryFolder, "resources"); resourcesDir.mkdir(); metadataDescriptor = HibernateUtil.initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); } @@ -53,21 +72,21 @@ public void testExporter() { public void testValidateCache() { HbmLint analyzer = new HbmLint(new Detector[] { new BadCachingDetector() }); analyzer.analyze(metadataDescriptor.createMetadata()); - Assert.assertEquals(1,analyzer.getResults().size()); + assertEquals(1,analyzer.getResults().size()); } @Test public void testValidateIdentifier() { HbmLint analyzer = new HbmLint(new Detector[] { new ShadowedIdentifierDetector() }); analyzer.analyze(metadataDescriptor.createMetadata()); - Assert.assertEquals(1,analyzer.getResults().size()); + assertEquals(1,analyzer.getResults().size()); } @Test public void testBytecodeRestrictions() { HbmLint analyzer = new HbmLint(new Detector[] { new InstrumentationDetector() }); analyzer.analyze(metadataDescriptor.createMetadata()); - Assert.assertEquals(analyzer.getResults().toString(), 2,analyzer.getResults().size()); + assertEquals(2,analyzer.getResults().size(), analyzer.getResults().toString()); } } diff --git a/test/common/src/main/java/org/hibernate/tool/hbmlint/SchemaAnalyzer/TestCase.java b/test/common/src/main/java/org/hibernate/tool/hbmlint/SchemaAnalyzer/TestCase.java index 80eeed373c..531d33adb3 100644 --- a/test/common/src/main/java/org/hibernate/tool/hbmlint/SchemaAnalyzer/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/hbmlint/SchemaAnalyzer/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbmlint.SchemaAnalyzer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -15,27 +34,25 @@ import org.hibernate.tool.hbmlint.IssueCollector; import org.hibernate.tool.hbmlint.detector.SchemaByMetaDataDetector; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author koen */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -59,27 +76,27 @@ public void testSchemaAnalyzer() { if(table.getName().equalsIgnoreCase( "MISSING_TABLE" )) { analyzer.visit(table, mc ); - Assert.assertEquals(mc.problems.size(),1); + assertEquals(mc.problems.size(),1); Issue ap = (Issue) mc.problems.get( 0 ); - Assert.assertTrue(ap.getDescription().indexOf( "Missing table" ) >=0); + assertTrue(ap.getDescription().indexOf( "Missing table" ) >=0); } else if(table.getName().equalsIgnoreCase( "CATEGORY" )) { analyzer.visit(table, mc ); - Assert.assertEquals(mc.problems.size(),1); + assertEquals(mc.problems.size(),1); Issue ap = (Issue) mc.problems.get( 0 ); - Assert.assertTrue(ap.getDescription().indexOf( "missing column: name" ) >=0); + assertTrue(ap.getDescription().indexOf( "missing column: name" ) >=0); } else if(table.getName().equalsIgnoreCase( "BAD_TYPE" )) { analyzer.visit(table, mc ); - Assert.assertEquals(mc.problems.size(),1); + assertEquals(mc.problems.size(),1); Issue ap = (Issue) mc.problems.get( 0 ); - Assert.assertTrue(ap.getDescription().indexOf( "wrong column type for name" ) >=0); + assertTrue(ap.getDescription().indexOf( "wrong column type for name" ) >=0); } } MockCollector mc = new MockCollector(); analyzer.visitGenerators(mc); - Assert.assertEquals(1,mc.problems.size()); + assertEquals(1,mc.problems.size()); Issue issue = (Issue) mc.problems.get( 0 ); - Assert.assertTrue(issue.getDescription().indexOf( "does_not_exist" ) >=0); + assertTrue(issue.getDescription().indexOf( "does_not_exist" ) >=0); } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/AutoQuote/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/AutoQuote/TestCase.java index 71276d8cd4..c97395f6e1 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/AutoQuote/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/AutoQuote/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-11-24 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.AutoQuote; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.hibernate.boot.Metadata; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; @@ -11,10 +30,9 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -24,7 +42,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -32,7 +50,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -40,13 +58,13 @@ public void tearDown() { @Test public void testForQuotes() { Table table = HibernateUtil.getTable(metadata, "us-ers"); - Assert.assertNotNull(table); - Assert.assertTrue(table.isQuoted()); - Assert.assertEquals(2, table.getColumnSpan()); + assertNotNull(table); + assertTrue(table.isQuoted()); + assertEquals(2, table.getColumnSpan()); PersistentClass classMapping = metadata.getEntityBinding("Worklogs"); - Assert.assertNotNull(classMapping); + assertNotNull(classMapping); Property property = classMapping.getProperty("usErs"); - Assert.assertNotNull(property); + assertNotNull(property); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Basic/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Basic/TestCase.java index fc6a338ef0..7474541885 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Basic/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Basic/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Basic; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -14,10 +34,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -27,7 +46,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -35,7 +54,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -49,20 +68,20 @@ public void testBasic() throws SQLException { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "BASIC")); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "BASIC"), JdbcUtil.toIdentifier(this, table.getName())); - Assert.assertEquals(2, table.getColumnSpan()); + assertEquals(2, table.getColumnSpan()); Column basicColumn = table.getColumn(0); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "A"), JdbcUtil.toIdentifier(this, basicColumn.getName())); PrimaryKey key = table.getPrimaryKey(); - Assert.assertNotNull("There should be a primary key!", key); - Assert.assertEquals(key.getColumnSpan(), 1); + assertNotNull(key, "There should be a primary key!"); + assertEquals(key.getColumnSpan(), 1); Column column = key.getColumn(0); - Assert.assertTrue(column.isUnique()); - Assert.assertSame(basicColumn, column); + assertTrue(column.isUnique()); + assertSame(basicColumn, column); } @Test @@ -71,9 +90,9 @@ public void testScalePrecisionLength() { metadata, JdbcUtil.toIdentifier(this, "BASIC")); Column nameCol = table.getColumn(new Column(JdbcUtil.toIdentifier(this, "NAME"))); - Assert.assertEquals(nameCol.getLength(), 20); - Assert.assertEquals(nameCol.getPrecision(), Column.DEFAULT_PRECISION); - Assert.assertEquals(nameCol.getScale(), Column.DEFAULT_SCALE); + assertEquals(nameCol.getLength(), 20); + assertEquals(nameCol.getPrecision(), Column.DEFAULT_PRECISION); + assertEquals(nameCol.getScale(), Column.DEFAULT_SCALE); } @Test @@ -82,7 +101,7 @@ public void testCompositeKeys() { metadata, JdbcUtil.toIdentifier(this, "MULTIKEYED")); PrimaryKey primaryKey = table.getPrimaryKey(); - Assert.assertEquals(2, primaryKey.getColumnSpan()); + assertEquals(2, primaryKey.getColumnSpan()); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/TestCase.java index 9741c425fa..9d2a56d14b 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.BasicMultiSchema; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -14,10 +34,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -27,7 +46,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -35,7 +54,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -52,29 +71,24 @@ public void testBasic() throws SQLException { metadata, JdbcUtil.toIdentifier(this, "BASIC" ) ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "BASIC"), JdbcUtil.toIdentifier(this, table.getName()) ); - Assert.assertEquals( 2, table.getColumnSpan() ); + assertEquals( 2, table.getColumnSpan() ); Column basicColumn = table.getColumn( 0 ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "A"), JdbcUtil.toIdentifier(this, basicColumn.getName() )); - - // TODO: we cannot call getSqlType(dialect,cfg) without a - // MappingassertEquals("INTEGER", basicColumn.getSqlType() ); // at - // least on hsqldb - // assertEquals(22, basicColumn.getLength() ); // at least on oracle PrimaryKey key = table.getPrimaryKey(); - Assert.assertNotNull( "There should be a primary key!", key ); - Assert.assertEquals( key.getColumnSpan(), 1 ); + assertNotNull(key, "There should be a primary key!" ); + assertEquals( key.getColumnSpan(), 1 ); Column column = key.getColumn( 0 ); - Assert.assertTrue( column.isUnique() ); + assertTrue( column.isUnique() ); - Assert.assertSame( basicColumn, column ); + assertSame( basicColumn, column ); } @@ -84,59 +98,18 @@ public void testScalePrecisionLength() { metadata, JdbcUtil.toIdentifier(this, "BASIC" ) ); Column nameCol = table.getColumn( new Column( JdbcUtil.toIdentifier(this, "NAME" ) ) ); - Assert.assertEquals( nameCol.getLength(), 20 ); - Assert.assertEquals( nameCol.getPrecision(), Column.DEFAULT_PRECISION ); - Assert.assertEquals( nameCol.getScale(), Column.DEFAULT_SCALE ); + assertEquals( nameCol.getLength(), 20 ); + assertEquals( nameCol.getPrecision(), Column.DEFAULT_PRECISION ); + assertEquals( nameCol.getScale(), Column.DEFAULT_SCALE ); } - -/* public void testAutoDetectSingleSchema() { - - //read single schema without default schema: result = no schema info in tables. - JDBCMetaDataConfiguration mycfg = new JDBCMetaDataConfiguration(); - mycfg.setReverseEngineeringStrategy(new DelegatingReverseEngineeringStrategy(new DefaultReverseEngineeringStrategy()) { - public boolean excludeTable(TableIdentifier ti) { - return !"PUBLIC".equals(ti.getSchema()); - } - }); - mycfg.getProperties().remove(org.hibernate.cfg.Environment.DEFAULT_SCHEMA); - mycfg.readFromJDBC(); - - Table table = getTable(mycfg, identifier("otherschema")); - assertNull("rev.eng.strategy should have excluded this table",table); - - table = getTable(mycfg, identifier("basic")); - assertNotNull(table); - assertNull(table.getSchema()); - - - //read single schema with default schema: result = no schema info in tables. - - //read other single schema than default schema: result = schema info in tables. - - }*/ - - /* - * public void testGetTables() { - * - * Table table = new Table(); table.setName("dummy"); cfg.addTable(table); - * - * Table foundTable = cfg.getTable(null,null,"dummy"); - * - * assertSame(table,foundTable); - * - * foundTable = cfg.getTable(null,"dschema", "dummy"); - * - * assertNotSame(table, foundTable); } - */ - @Test public void testCompositeKeys() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "MULTIKEYED")); PrimaryKey primaryKey = table.getPrimaryKey(); - Assert.assertEquals( 2, primaryKey.getColumnSpan() ); + assertEquals( 2, primaryKey.getColumnSpan() ); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeId/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeId/TestCase.java index ae6a91a905..08fb245e6d 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeId/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeId/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 13-Jan-2005 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.CompositeId; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.net.URL; import java.net.URLClassLoader; @@ -31,12 +52,10 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -47,10 +66,10 @@ public class TestCase { private MetadataDescriptor metadataDescriptor = null; private ReverseEngineeringStrategy reverseEngineeringStrategy = null; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); reverseEngineeringStrategy = new DefaultReverseEngineeringStrategy(); @@ -58,7 +77,7 @@ public void setUp() { .createJdbcDescriptor(reverseEngineeringStrategy, null, true); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this);; } @@ -69,39 +88,39 @@ public void testMultiColumnForeignKeys() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "LINE_ITEM") ); - Assert.assertNotNull(table); + assertNotNull(table); ForeignKey foreignKey = HibernateUtil.getForeignKey( table, JdbcUtil.toIdentifier(this, "TO_CUSTOMER_ORDER") ); - Assert.assertNotNull(foreignKey); - Assert.assertEquals( + assertNotNull(foreignKey); + assertEquals( reverseEngineeringStrategy.tableToClassName( new TableIdentifier( null, null, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER"))), foreignKey.getReferencedEntityName() ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "LINE_ITEM"), foreignKey.getTable().getName() ); - Assert.assertEquals(2,foreignKey.getColumnSpan() ); - Assert.assertEquals(foreignKey.getColumn(0).getName(), "CUSTOMER_ID_REF"); - Assert.assertEquals(foreignKey.getColumn(1).getName(), "ORDER_NUMBER"); + assertEquals(2,foreignKey.getColumnSpan() ); + assertEquals(foreignKey.getColumn(0).getName(), "CUSTOMER_ID_REF"); + assertEquals(foreignKey.getColumn(1).getName(), "ORDER_NUMBER"); Table tab = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER")); - Assert.assertEquals(tab.getPrimaryKey().getColumn(0).getName(), "CUSTOMER_ID"); - Assert.assertEquals(tab.getPrimaryKey().getColumn(1).getName(), "ORDER_NUMBER"); + assertEquals(tab.getPrimaryKey().getColumn(0).getName(), "CUSTOMER_ID"); + assertEquals(tab.getPrimaryKey().getColumn(1).getName(), "ORDER_NUMBER"); PersistentClass lineMapping = metadata.getEntityBinding( reverseEngineeringStrategy.tableToClassName( new TableIdentifier( null, null, JdbcUtil.toIdentifier(this, "LINE_ITEM")))); - Assert.assertEquals(4,lineMapping.getIdentifier().getColumnSpan() ); + assertEquals(4,lineMapping.getIdentifier().getColumnSpan() ); Iterator columnIterator = lineMapping.getIdentifier().getColumnIterator(); - Assert.assertEquals(((Column)(columnIterator.next())).getName(), "CUSTOMER_ID_REF"); - Assert.assertEquals(((Column)(columnIterator.next())).getName(), "ORDER_NUMBER"); + assertEquals(((Column)(columnIterator.next())).getName(), "CUSTOMER_ID_REF"); + assertEquals(((Column)(columnIterator.next())).getName(), "ORDER_NUMBER"); } @Test @@ -113,24 +132,24 @@ public void testPossibleKeyManyToOne() { null, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER")))); Property identifierProperty = product.getIdentifierProperty(); - Assert.assertTrue(identifierProperty.getValue() instanceof Component); + assertTrue(identifierProperty.getValue() instanceof Component); Component cmpid = (Component) identifierProperty.getValue(); - Assert.assertEquals(2, cmpid.getPropertySpan() ); + assertEquals(2, cmpid.getPropertySpan() ); Iterator iter = cmpid.getPropertyIterator(); Property id = (Property) iter.next(); Property extraId = (Property) iter.next(); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "CUSTOMER_ID"), id.getName() ); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "ORDER_NUMBER"), extraId.getName() ); - Assert.assertFalse(id.getValue() instanceof ManyToOne); - Assert.assertFalse(extraId.getValue() instanceof ManyToOne); + assertFalse(id.getValue() instanceof ManyToOne); + assertFalse(extraId.getValue() instanceof ManyToOne); } @Test @@ -142,49 +161,48 @@ public void testKeyProperty() { null, JdbcUtil.toIdentifier(this, "PRODUCT")))); Property identifierProperty = product.getIdentifierProperty(); - Assert.assertTrue(identifierProperty.getValue() instanceof Component); + assertTrue(identifierProperty.getValue() instanceof Component); Component cmpid = (Component) identifierProperty.getValue(); - Assert.assertEquals(2, cmpid.getPropertySpan() ); + assertEquals(2, cmpid.getPropertySpan() ); Iterator iter = cmpid.getPropertyIterator(); Property id = (Property) iter.next(); Property extraId = (Property) iter.next(); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "PRODUCT_ID"), id.getName() ); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "EXTRA_ID"), extraId.getName() ); - Assert.assertFalse(id.getValue() instanceof ManyToOne); - Assert.assertFalse(extraId.getValue() instanceof ManyToOne); + assertFalse(id.getValue() instanceof ManyToOne); + assertFalse(extraId.getValue() instanceof ManyToOne); } @Test public void testGeneration() throws Exception { - final File testFolder = temporaryFolder.getRoot(); Exporter exporter = new HibernateMappingExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(testFolder); + exporter.setOutputDirectory(temporaryFolder); Exporter javaExp = new POJOExporter(); javaExp.setMetadataDescriptor(metadataDescriptor); - javaExp.setOutputDirectory(testFolder); + javaExp.setOutputDirectory(temporaryFolder); exporter.start(); javaExp.start(); - JavaUtil.compile(testFolder); - URL[] urls = new URL[] { testFolder.toURI().toURL() }; + JavaUtil.compile(temporaryFolder); + URL[] urls = new URL[] { temporaryFolder.toURI().toURL() }; URLClassLoader ucl = new URLClassLoader( urls, Thread.currentThread().getContextClassLoader()); File[] files = new File[6]; - files[0] = new File(testFolder, "Simplecustomerorder.hbm.xml"); - files[1] = new File(testFolder, "Simplelineitem.hbm.xml"); - files[2] = new File(testFolder, "Product.hbm.xml"); - files[3] = new File(testFolder, "Customer.hbm.xml"); - files[4] = new File(testFolder, "Lineitem.hbm.xml"); - files[5] = new File(testFolder, "Customerorder.hbm.xml"); + files[0] = new File(temporaryFolder, "SimpleCustomerOrder.hbm.xml"); + files[1] = new File(temporaryFolder, "SimpleLineItem.hbm.xml"); + files[2] = new File(temporaryFolder, "Product.hbm.xml"); + files[3] = new File(temporaryFolder, "Customer.hbm.xml"); + files[4] = new File(temporaryFolder, "LineItem.hbm.xml"); + files[5] = new File(temporaryFolder, "CustomerOrder.hbm.xml"); Thread.currentThread().setContextClassLoader(ucl); SessionFactory factory = MetadataDescriptorFactory .createNativeDescriptor(null, files, null) @@ -194,22 +212,22 @@ public void testGeneration() throws Exception { JdbcUtil.populateDatabase(this); session.createQuery("from LineItem").getResultList(); List list = session.createQuery("from Product").getResultList(); - Assert.assertEquals(2,list.size() ); + assertEquals(2,list.size() ); list = session .createQuery("select li.customerOrder.id from LineItem as li") .getResultList(); - Assert.assertTrue(list.size()>0); + assertTrue(list.size()>0); Class productIdClass = ucl.loadClass("ProductId"); Object object = productIdClass.newInstance(); int hash = -1; try { hash = object.hashCode(); } catch(Throwable t) { - Assert.fail("Hashcode on new instance should not fail " + t); + fail("Hashcode on new instance should not fail " + t); } - Assert.assertFalse( - "hashcode should be different from system", - hash==System.identityHashCode(object)); + assertFalse( + hash==System.identityHashCode(object), + "hashcode should be different from system"); factory.close(); Thread.currentThread().setContextClassLoader(ucl.getParent() ); } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ForeignKeys/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ForeignKeys/TestCase.java index 44ca79208c..b5fce40ab1 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ForeignKeys/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ForeignKeys/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-11-24 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.ForeignKeys; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + import java.util.EnumSet; import java.util.Iterator; @@ -20,10 +41,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -34,7 +54,7 @@ public class TestCase { private Metadata metadata = null; private ReverseEngineeringStrategy reverseEngineeringStrategy = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); reverseEngineeringStrategy = new DefaultReverseEngineeringStrategy(); @@ -43,7 +63,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this);; } @@ -56,28 +76,28 @@ public void testMultiRefs() { ForeignKey foreignKey = HibernateUtil.getForeignKey( table, JdbcUtil.toIdentifier(this, "CON2MASTER") ); - Assert.assertNotNull(foreignKey); - Assert.assertEquals( + assertNotNull(foreignKey); + assertEquals( reverseEngineeringStrategy.tableToClassName( new TableIdentifier(null, null, "MASTER")), foreignKey.getReferencedEntityName() ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "CONNECTION"), foreignKey.getTable().getName() ); - Assert.assertEquals( + assertEquals( HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "MASTER") ), foreignKey.getReferencedTable() ); - Assert.assertNotNull( + assertNotNull( HibernateUtil.getForeignKey( table, JdbcUtil.toIdentifier(this, "CHILDREF1") ) ); - Assert.assertNotNull( + assertNotNull( HibernateUtil.getForeignKey( table, JdbcUtil.toIdentifier(this, "CHILDREF2") ) ); - Assert.assertNull( + assertNull( HibernateUtil.getForeignKey( table, JdbcUtil.toIdentifier(this, "DUMMY") ) ); @@ -86,7 +106,7 @@ public void testMultiRefs() { @Test public void testMasterChild() { - Assert.assertNotNull(HibernateUtil.getTable( + assertNotNull(HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "MASTER"))); Table child = HibernateUtil.getTable( @@ -94,9 +114,9 @@ public void testMasterChild() { JdbcUtil.toIdentifier(this, "CHILD") ); Iterator iterator = child.getForeignKeyIterator(); ForeignKey fk = (ForeignKey) iterator.next(); - Assert.assertFalse("should only be one fk", iterator.hasNext() ); - Assert.assertEquals(1, fk.getColumnSpan() ); - Assert.assertSame( + assertFalse(iterator.hasNext(), "should only be one fk" ); + assertEquals(1, fk.getColumnSpan() ); + assertSame( fk.getColumn(0), child.getColumn( new Column(JdbcUtil.toIdentifier(this, "MASTERREF")))); diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java index 864bff3e19..f628e9df3c 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Identity; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -11,10 +29,9 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -24,7 +41,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -32,7 +49,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -41,8 +58,8 @@ public void tearDown() { public void testIdentity() throws SQLException { PersistentClass classMapping = metadata.getEntityBinding("Autoinc"); - Assert.assertNotNull(classMapping); - Assert.assertEquals( + assertNotNull(classMapping); + assertEquals( "identity", ((SimpleValue)classMapping .getIdentifierProperty() @@ -50,7 +67,7 @@ public void testIdentity() throws SQLException { .getIdentifierGeneratorStrategy()); classMapping = metadata.getEntityBinding("Noautoinc"); - Assert.assertEquals( + assertEquals( "assigned", ((SimpleValue)classMapping .getIdentifierProperty() diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Index/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Index/TestCase.java index 93aa71f68e..0f1ac69acd 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Index/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Index/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-11-24 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Index; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import org.hibernate.boot.Metadata; @@ -14,10 +35,9 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -27,7 +47,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -35,7 +55,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -47,11 +67,11 @@ public void testUniqueKey() { JdbcUtil.toIdentifier(this, "WITH_INDEX") ); UniqueKey uniqueKey = table.getUniqueKey( JdbcUtil.toIdentifier(this, "OTHER_IDX") ); - Assert.assertNotNull(uniqueKey); - Assert.assertEquals(1, uniqueKey.getColumnSpan() ); + assertNotNull(uniqueKey); + assertEquals(1, uniqueKey.getColumnSpan() ); Column keyCol = uniqueKey.getColumn(0); - Assert.assertTrue(keyCol.isUnique() ); - Assert.assertSame(keyCol, table.getColumn(keyCol) ); + assertTrue(keyCol.isUnique() ); + assertSame(keyCol, table.getColumn(keyCol) ); } @Test @@ -59,38 +79,37 @@ public void testWithIndex() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "WITH_INDEX")); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "WITH_INDEX"), JdbcUtil.toIdentifier(this, table.getName())); - Assert.assertNull("there should be no pk", table.getPrimaryKey() ); + assertNull(table.getPrimaryKey(), "there should be no pk" ); Iterator iterator = table.getIndexIterator(); int cnt=0; while(iterator.hasNext() ) { iterator.next(); cnt++; } - Assert.assertEquals(1, cnt); + assertEquals(1, cnt); Index index = table.getIndex(JdbcUtil.toIdentifier(this, "MY_INDEX") ); - Assert.assertNotNull("No index ?", index); - Assert.assertEquals( + assertNotNull(index, "No index ?"); + assertEquals( JdbcUtil.toIdentifier(this, "MY_INDEX"), JdbcUtil.toIdentifier(this, index.getName())); - Assert.assertEquals(2, index.getColumnSpan() ); - Assert.assertSame(index.getTable(), table); + assertEquals(2, index.getColumnSpan() ); + assertSame(index.getTable(), table); Iterator cols = index.getColumnIterator(); Column col1 = cols.next(); Column col2 = cols.next(); - Assert.assertEquals( - JdbcUtil.toIdentifier(this, "FIRST"), + assertEquals( + JdbcUtil.toIdentifier(this, "ONE"), JdbcUtil.toIdentifier(this, col1.getName())); - Assert.assertEquals( - JdbcUtil.toIdentifier(this, "THIRD"), + assertEquals( + JdbcUtil.toIdentifier(this, "THREE"), JdbcUtil.toIdentifier(this, col2.getName())); Column example = new Column(); example.setName(col2.getName() ); - Assert.assertSame( - "column with same name should be same instance!", - table.getColumn(example), col2); + assertSame( + table.getColumn(example), col2, "column with same name should be same instance!"); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/TestCase.java index 05850c51e4..064deca7a4 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/TestCase.java @@ -1,5 +1,30 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.KeyPropertyCompositeId; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.net.URL; import java.net.URLClassLoader; @@ -27,12 +52,10 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -40,13 +63,13 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); private MetadataDescriptor metadataDescriptor = null; private ReverseEngineeringStrategy reverseEngineeringStrategy = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); reverseEngineeringStrategy = new DefaultReverseEngineeringStrategy(); @@ -54,7 +77,7 @@ public void setUp() { .createJdbcDescriptor(reverseEngineeringStrategy, null, false); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this);; } @@ -65,29 +88,29 @@ public void testMultiColumnForeignKeys() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "LINE_ITEM")); - Assert.assertNotNull(table); + assertNotNull(table); ForeignKey foreignKey = HibernateUtil.getForeignKey(table, JdbcUtil.toIdentifier(this, "TO_CUSTOMER_ORDER")); - Assert.assertNotNull(foreignKey); - Assert.assertEquals( + assertNotNull(foreignKey); + assertEquals( reverseEngineeringStrategy.tableToClassName( new TableIdentifier(null, null, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER"))), foreignKey.getReferencedEntityName()); - Assert.assertEquals(JdbcUtil.toIdentifier(this, "LINE_ITEM"), foreignKey.getTable().getName()); - Assert.assertEquals(2, foreignKey.getColumnSpan()); - Assert.assertEquals(foreignKey.getColumn(0).getName(), "CUSTOMER_ID_REF"); - Assert.assertEquals(foreignKey.getColumn(1).getName(), "ORDER_NUMBER"); + assertEquals(JdbcUtil.toIdentifier(this, "LINE_ITEM"), foreignKey.getTable().getName()); + assertEquals(2, foreignKey.getColumnSpan()); + assertEquals(foreignKey.getColumn(0).getName(), "CUSTOMER_ID_REF"); + assertEquals(foreignKey.getColumn(1).getName(), "ORDER_NUMBER"); Table tab = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER")); - Assert.assertEquals(tab.getPrimaryKey().getColumn(0).getName(), "CUSTOMER_ID"); - Assert.assertEquals(tab.getPrimaryKey().getColumn(1).getName(), "ORDER_NUMBER"); + assertEquals(tab.getPrimaryKey().getColumn(0).getName(), "CUSTOMER_ID"); + assertEquals(tab.getPrimaryKey().getColumn(1).getName(), "ORDER_NUMBER"); PersistentClass lineMapping = metadata.getEntityBinding( reverseEngineeringStrategy .tableToClassName(new TableIdentifier(null, null, JdbcUtil.toIdentifier(this, "LINE_ITEM")))); - Assert.assertEquals(4, lineMapping.getIdentifier().getColumnSpan()); + assertEquals(4, lineMapping.getIdentifier().getColumnSpan()); Iterator columnIterator = lineMapping.getIdentifier().getColumnIterator(); - Assert.assertEquals(((Column) (columnIterator.next())).getName(), "CUSTOMER_ID_REF"); - Assert.assertEquals(((Column) (columnIterator.next())).getName(), "ORDER_NUMBER"); + assertEquals(((Column) (columnIterator.next())).getName(), "CUSTOMER_ID_REF"); + assertEquals(((Column) (columnIterator.next())).getName(), "ORDER_NUMBER"); } @Test @@ -96,24 +119,24 @@ public void testPossibleKeyManyToOne() { reverseEngineeringStrategy .tableToClassName(new TableIdentifier(null, null, JdbcUtil.toIdentifier(this, "CUSTOMER_ORDER")))); Property identifierProperty = product.getIdentifierProperty(); - Assert.assertTrue(identifierProperty.getValue() instanceof Component); + assertTrue(identifierProperty.getValue() instanceof Component); Component cmpid = (Component) identifierProperty.getValue(); - Assert.assertEquals(2, cmpid.getPropertySpan()); + assertEquals(2, cmpid.getPropertySpan()); Iterator iter = cmpid.getPropertyIterator(); Property id = (Property) iter.next(); Property extraId = (Property) iter.next(); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "customer"), id.getName()); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "orderNumber"), extraId.getName()); - Assert.assertTrue(id.getValue() instanceof ManyToOne); - Assert.assertFalse(extraId.getValue() instanceof ManyToOne); + assertTrue(id.getValue() instanceof ManyToOne); + assertFalse(extraId.getValue() instanceof ManyToOne); } @Test @@ -122,47 +145,46 @@ public void testKeyProperty() { reverseEngineeringStrategy .tableToClassName(new TableIdentifier(null, null, JdbcUtil.toIdentifier(this, "PRODUCT")))); Property identifierProperty = product.getIdentifierProperty(); - Assert.assertTrue(identifierProperty.getValue() instanceof Component); + assertTrue(identifierProperty.getValue() instanceof Component); Component cmpid = (Component) identifierProperty.getValue(); - Assert.assertEquals(2, cmpid.getPropertySpan()); + assertEquals(2, cmpid.getPropertySpan()); Iterator iter = cmpid.getPropertyIterator(); Property id = (Property) iter.next(); Property extraId = (Property) iter.next(); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "productId"), id.getName()); - Assert.assertEquals( + assertEquals( reverseEngineeringStrategy.columnToPropertyName( null, "extraId"), extraId.getName()); - Assert.assertFalse(id.getValue() instanceof ManyToOne); - Assert.assertFalse(extraId.getValue() instanceof ManyToOne); + assertFalse(id.getValue() instanceof ManyToOne); + assertFalse(extraId.getValue() instanceof ManyToOne); } @Test public void testGeneration() throws Exception { - final File testFolder = temporaryFolder.getRoot(); Exporter exporter = new HibernateMappingExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(testFolder); + exporter.setOutputDirectory(temporaryFolder); Exporter javaExp = new POJOExporter(); javaExp.setMetadataDescriptor(metadataDescriptor); - javaExp.setOutputDirectory(testFolder); + javaExp.setOutputDirectory(temporaryFolder); exporter.start(); javaExp.start(); - JavaUtil.compile(testFolder); - URL[] urls = new URL[] { testFolder.toURI().toURL() }; + JavaUtil.compile(temporaryFolder); + URL[] urls = new URL[] { temporaryFolder.toURI().toURL() }; URLClassLoader ucl = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); File[] files = new File[6]; - files[0] = new File(testFolder, "Simplecustomerorder.hbm.xml"); - files[1] = new File(testFolder, "Simplelineitem.hbm.xml"); - files[2] = new File(testFolder, "Product.hbm.xml"); - files[3] = new File(testFolder, "Customer.hbm.xml"); - files[4] = new File(testFolder, "Lineitem.hbm.xml"); - files[5] = new File(testFolder, "Customerorder.hbm.xml"); + files[0] = new File(temporaryFolder, "SimpleCustomerOrder.hbm.xml"); + files[1] = new File(temporaryFolder, "SimpleLineItem.hbm.xml"); + files[2] = new File(temporaryFolder, "Product.hbm.xml"); + files[3] = new File(temporaryFolder, "Customer.hbm.xml"); + files[4] = new File(temporaryFolder, "LineItem.hbm.xml"); + files[5] = new File(temporaryFolder, "CustomerOrder.hbm.xml"); Thread.currentThread().setContextClassLoader(ucl); SessionFactory factory = MetadataDescriptorFactory .createNativeDescriptor(null, files, null) @@ -172,20 +194,20 @@ public void testGeneration() throws Exception { JdbcUtil.populateDatabase(this);; session.createQuery("from LineItem").getResultList(); List list = session.createQuery("from Product").getResultList(); - Assert.assertEquals(2, list.size()); + assertEquals(2, list.size()); list = session .createQuery("select li.id.customerOrder.id from LineItem as li") .getResultList(); - Assert.assertTrue(list.size() > 0); + assertTrue(list.size() > 0); Class productIdClass = ucl.loadClass("ProductId"); Object object = productIdClass.newInstance(); int hash = -1; try { hash = object.hashCode(); } catch (Throwable t) { - Assert.fail("Hashcode on new instance should not fail " + t); + fail("Hashcode on new instance should not fail " + t); } - Assert.assertFalse("hashcode should be different from system", hash == System.identityHashCode(object)); + assertFalse(hash == System.identityHashCode(object), "hashcode should be different from system"); factory.close(); Thread.currentThread().setContextClassLoader(ucl.getParent()); } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ManyToMany/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ManyToMany/TestCase.java index 5273c3e657..c423f3a02b 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ManyToMany/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/ManyToMany/TestCase.java @@ -1,9 +1,31 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.ManyToMany; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.hibernate.MappingException; @@ -16,12 +38,10 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -29,15 +49,15 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File temporaryFolder = new File("temp"); - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -53,26 +73,26 @@ public void testNoManyToManyBiDirectional() { PersistentClass project = metadata.getEntityBinding("Project"); - Assert.assertNotNull(project.getProperty("worksOns")); + assertNotNull(project.getProperty("worksOns")); //assertNotNull(project.getProperty("employee")); - Assert.assertEquals(3, project.getPropertyClosureSpan()); - Assert.assertEquals("projectId", project.getIdentifierProperty().getName()); + assertEquals(3, project.getPropertyClosureSpan()); + assertEquals("projectId", project.getIdentifierProperty().getName()); PersistentClass employee = metadata.getEntityBinding("Employee"); - Assert.assertNotNull(employee.getProperty("worksOns")); - Assert.assertNotNull(employee.getProperty("employees")); - Assert.assertNotNull(employee.getProperty("employee")); + assertNotNull(employee.getProperty("worksOns")); + assertNotNull(employee.getProperty("employees")); + assertNotNull(employee.getProperty("employee")); //assertNotNull(employee.getProperty("projects")); - Assert.assertEquals(6, employee.getPropertyClosureSpan()); - Assert.assertEquals("id", employee.getIdentifierProperty().getName()); + assertEquals(6, employee.getPropertyClosureSpan()); + assertEquals("id", employee.getIdentifierProperty().getName()); PersistentClass worksOn = metadata.getEntityBinding("WorksOn"); - Assert.assertNotNull(worksOn.getProperty("project")); - Assert.assertNotNull(worksOn.getProperty("employee")); - Assert.assertEquals(2, worksOn.getPropertyClosureSpan()); - Assert.assertEquals("id", worksOn.getIdentifierProperty().getName()); + assertNotNull(worksOn.getProperty("project")); + assertNotNull(worksOn.getProperty("employee")); + assertEquals(2, worksOn.getPropertyClosureSpan()); + assertEquals("id", worksOn.getIdentifierProperty().getName()); } @Test @@ -81,22 +101,22 @@ public void testAutoCreation() { .createJdbcDescriptor(null, null, true) .createMetadata(); - Assert.assertNull("No middle class should be generated.", metadata.getEntityBinding( "WorksOn" )); + assertNull(metadata.getEntityBinding( "WorksOn" ), "No middle class should be generated."); - Assert.assertNotNull("Should create worksontext since one of the foreign keys is not part of pk", metadata.getEntityBinding( "WorksOnContext" )); + assertNotNull(metadata.getEntityBinding( "WorksOnContext" ), "Should create worksontext since one of the foreign keys is not part of pk"); PersistentClass projectClass = metadata.getEntityBinding("Project"); - Assert.assertNotNull( projectClass ); + assertNotNull( projectClass ); PersistentClass employeeClass = metadata.getEntityBinding("Employee"); - Assert.assertNotNull( employeeClass ); + assertNotNull( employeeClass ); assertPropertyNotExist( projectClass, "worksOns" ); assertPropertyNotExist( employeeClass, "worksOns" ); Property property = employeeClass.getProperty( "projects" ); - Assert.assertNotNull( property); - Assert.assertNotNull( projectClass.getProperty( "employees" )); + assertNotNull( property); + assertNotNull( projectClass.getProperty( "employees" )); } @@ -105,7 +125,7 @@ public void testFalsePositive() { Metadata metadata = MetadataDescriptorFactory .createJdbcDescriptor(null, null, true) .createMetadata(); - Assert.assertNotNull("Middle class should be generated.", metadata.getEntityBinding( "NonMiddle" )); + assertNotNull(metadata.getEntityBinding( "NonMiddle" ), "Middle class should be generated."); } @Test @@ -113,7 +133,7 @@ public void testBuildMappings() { Metadata metadata = MetadataDescriptorFactory .createJdbcDescriptor(null, null, true) .createMetadata(); - Assert.assertNotNull(metadata); + assertNotNull(metadata); } @Test @@ -121,33 +141,31 @@ public void testGenerateAndReadable() { MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createJdbcDescriptor(null, null, true); - File outputDir = temporaryFolder.getRoot(); - - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); HibernateMappingExporter hme = new HibernateMappingExporter(); hme.setMetadataDescriptor(metadataDescriptor); - hme.setOutputDirectory(outputDir); + hme.setOutputDirectory(temporaryFolder); hme.start(); - assertFileAndExists( new File(outputDir, "Employee.hbm.xml") ); - assertFileAndExists( new File(outputDir, "Project.hbm.xml") ); - assertFileAndExists( new File(outputDir, "WorksOnContext.hbm.xml") ); + assertFileAndExists( new File(temporaryFolder, "Employee.hbm.xml") ); + assertFileAndExists( new File(temporaryFolder, "Project.hbm.xml") ); + assertFileAndExists( new File(temporaryFolder, "WorksOnContext.hbm.xml") ); - assertFileAndExists( new File(outputDir, "RightTable.hbm.xml") ); - assertFileAndExists( new File(outputDir, "LeftTable.hbm.xml") ); - assertFileAndExists( new File(outputDir, "NonMiddle.hbm.xml") ); //Must be there since it has a fkey that is not part of the pk + assertFileAndExists( new File(temporaryFolder, "RightTable.hbm.xml") ); + assertFileAndExists( new File(temporaryFolder, "LeftTable.hbm.xml") ); + assertFileAndExists( new File(temporaryFolder, "NonMiddle.hbm.xml") ); //Must be there since it has a fkey that is not part of the pk - Assert.assertFalse(new File(outputDir, "WorksOn.hbm.xml").exists() ); + assertFalse(new File(temporaryFolder, "WorksOn.hbm.xml").exists() ); - Assert.assertEquals(6, outputDir.listFiles().length); + assertEquals(6, temporaryFolder.listFiles().length); File[] files = new File[3]; - files[0] = new File(outputDir, "Employee.hbm.xml"); - files[1] = new File(outputDir, "Project.hbm.xml"); - files[2] = new File(outputDir, "WorksOnContext.hbm.xml"); + files[0] = new File(temporaryFolder, "Employee.hbm.xml"); + files[1] = new File(temporaryFolder, "Project.hbm.xml"); + files[2] = new File(temporaryFolder, "WorksOnContext.hbm.xml"); - Assert.assertNotNull(MetadataDescriptorFactory + assertNotNull(MetadataDescriptorFactory .createNativeDescriptor(null, files, null) .createMetadata()); @@ -157,16 +175,16 @@ public void testGenerateAndReadable() { private void assertPropertyNotExist(PersistentClass projectClass, String prop) { try { projectClass.getProperty(prop); - Assert.fail("property " + prop + " should not exist on " + projectClass); + fail("property " + prop + " should not exist on " + projectClass); } catch(MappingException e) { // expected } } private void assertFileAndExists(File file) { - Assert.assertTrue(file + " does not exist", file.exists() ); - Assert.assertTrue(file + " not a file", file.isFile() ); - Assert.assertTrue(file + " does not have any contents", file.length()>0); + assertTrue(file.exists(), file + " does not exist" ); + assertTrue(file.isFile(), file + " not a file" ); + assertTrue(file.length()>0, file + " does not have any contents"); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/MetaData/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/MetaData/TestCase.java index 877b83a96f..55f568e6db 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/MetaData/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/MetaData/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.MetaData; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.hibernate.boot.Metadata; import org.hibernate.mapping.Column; import org.hibernate.mapping.PrimaryKey; @@ -12,10 +32,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -25,7 +44,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -33,7 +52,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -47,24 +66,20 @@ public void testBasic() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "BASIC" ) ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "BASIC"), JdbcUtil.toIdentifier(this, table.getName())); - Assert.assertEquals( 2, table.getColumnSpan() ); + assertEquals( 2, table.getColumnSpan() ); Column basicColumn = table.getColumn( 0 ); - Assert.assertEquals( + assertEquals( JdbcUtil.toIdentifier(this, "A"), JdbcUtil.toIdentifier(this, basicColumn.getName())); - // TODO: we cannot call getSqlType(dialect,cfg) without a - // MappingassertEquals("INTEGER", basicColumn.getSqlType() ); // at - // least on hsqldb - // assertEquals(22, basicColumn.getLength() ); // at least on oracle PrimaryKey key = table.getPrimaryKey(); - Assert.assertNotNull( "There should be a primary key!", key ); - Assert.assertEquals( key.getColumnSpan(), 1 ); + assertNotNull(key, "There should be a primary key!" ); + assertEquals( key.getColumnSpan(), 1 ); Column column = key.getColumn( 0 ); - Assert.assertTrue( column.isUnique() ); - Assert.assertSame( basicColumn, column ); + assertTrue( column.isUnique() ); + assertSame( basicColumn, column ); } @Test @@ -73,32 +88,18 @@ public void testScalePrecisionLength() { metadata, JdbcUtil.toIdentifier(this, "BASIC")); Column nameCol = table.getColumn(new Column( JdbcUtil.toIdentifier(this, "NAME" ) ) ); - Assert.assertEquals( nameCol.getLength(), 20 ); - Assert.assertEquals( nameCol.getPrecision(), Column.DEFAULT_PRECISION ); - Assert.assertEquals( nameCol.getScale(), Column.DEFAULT_SCALE ); + assertEquals( nameCol.getLength(), 20 ); + assertEquals( nameCol.getPrecision(), Column.DEFAULT_PRECISION ); + assertEquals( nameCol.getScale(), Column.DEFAULT_SCALE ); } - /* - * public void testGetTables() { - * - * Table table = new Table(); table.setName("dummy"); cfg.addTable(table); - * - * Table foundTable = cfg.getTable(null,null,"dummy"); - * - * assertSame(table,foundTable); - * - * foundTable = cfg.getTable(null,"dschema", "dummy"); - * - * assertNotSame(table, foundTable); } - */ - @Test public void testCompositeKeys() { Table table = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "MULTIKEYED")); PrimaryKey primaryKey = table.getPrimaryKey(); - Assert.assertEquals( 2, primaryKey.getColumnSpan() ); + assertEquals( 2, primaryKey.getColumnSpan() ); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/TestCase.java index ae5eb821a7..f56f4a8453 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/TestCase.java @@ -1,17 +1,31 @@ /* - * Created on 2004-11-24 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.NoPrimaryKey; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -19,19 +33,19 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @Test public void testMe() { - Assert.assertNotNull( + assertNotNull( MetadataDescriptorFactory .createJdbcDescriptor(null, null, true) .createMetadata()); diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OneToOne/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OneToOne/TestCase.java index 403153642f..4d5e621b16 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OneToOne/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OneToOne/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.OneToOne; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.net.MalformedURLException; import java.net.URL; @@ -31,12 +51,10 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -44,20 +62,20 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputDir = new File("output"); private MetadataDescriptor metadataDescriptor = null; private Metadata metadata = null; - @Before + @BeforeEach public void setUp() throws Exception { JdbcUtil.createDatabase(this); metadataDescriptor = MetadataDescriptorFactory.createJdbcDescriptor(null, null, true); metadata = metadataDescriptor.createMetadata(); } - @After + @AfterEach public void tearDown() throws Exception { JdbcUtil.dropDatabase(this); } @@ -66,68 +84,67 @@ public void tearDown() throws Exception { public void testOneToOneSingleColumnBiDirectional() { PersistentClass person = metadata.getEntityBinding("Person"); Property addressProperty = person.getProperty("addressPerson"); - Assert.assertNotNull(addressProperty); - Assert.assertTrue(addressProperty.getValue() instanceof OneToOne); + assertNotNull(addressProperty); + assertTrue(addressProperty.getValue() instanceof OneToOne); OneToOne oto = (OneToOne) addressProperty.getValue(); - Assert.assertEquals(oto.getColumnSpan(),1); - Assert.assertEquals("Person", oto.getEntityName()); - Assert.assertEquals("AddressPerson", oto.getReferencedEntityName()); - Assert.assertEquals(2, person.getPropertyClosureSpan()); - Assert.assertEquals("personId", person.getIdentifierProperty().getName()); - Assert.assertFalse(oto.isConstrained()); + assertEquals(oto.getColumnSpan(),1); + assertEquals("Person", oto.getEntityName()); + assertEquals("AddressPerson", oto.getReferencedEntityName()); + assertEquals(2, person.getPropertyClosureSpan()); + assertEquals("personId", person.getIdentifierProperty().getName()); + assertFalse(oto.isConstrained()); PersistentClass addressPerson = metadata.getEntityBinding("AddressPerson"); Property personProperty = addressPerson.getProperty("person"); - Assert.assertNotNull(personProperty); - Assert.assertTrue(personProperty.getValue() instanceof OneToOne); + assertNotNull(personProperty); + assertTrue(personProperty.getValue() instanceof OneToOne); oto = (OneToOne) personProperty.getValue(); - Assert.assertTrue(oto.isConstrained()); - Assert.assertEquals(oto.getColumnSpan(),1); - Assert.assertEquals("AddressPerson", oto.getEntityName()); - Assert.assertEquals("Person", oto.getReferencedEntityName()); - Assert.assertEquals(2, addressPerson.getPropertyClosureSpan()); - Assert.assertEquals("addressId", addressPerson.getIdentifierProperty().getName()); + assertTrue(oto.isConstrained()); + assertEquals(oto.getColumnSpan(),1); + assertEquals("AddressPerson", oto.getEntityName()); + assertEquals("Person", oto.getReferencedEntityName()); + assertEquals(2, addressPerson.getPropertyClosureSpan()); + assertEquals("addressId", addressPerson.getIdentifierProperty().getName()); } @Test public void testAddressWithForeignKeyGeneration() { PersistentClass address = metadata.getEntityBinding("AddressPerson"); - Assert.assertEquals("foreign", ((SimpleValue)address.getIdentifier()).getIdentifierGeneratorStrategy()); + assertEquals("foreign", ((SimpleValue)address.getIdentifier()).getIdentifierGeneratorStrategy()); } @Test public void testOneToOneMultiColumnBiDirectional() { PersistentClass person = metadata.getEntityBinding("MultiPerson"); Property addressProperty = person.getProperty("addressMultiPerson"); - Assert.assertNotNull(addressProperty); - Assert.assertTrue(addressProperty.getValue() instanceof OneToOne); + assertNotNull(addressProperty); + assertTrue(addressProperty.getValue() instanceof OneToOne); OneToOne oto = (OneToOne) addressProperty.getValue(); - Assert.assertEquals(oto.getColumnSpan(),2); - Assert.assertEquals("MultiPerson", oto.getEntityName()); - Assert.assertEquals("AddressMultiPerson", oto.getReferencedEntityName()); - Assert.assertFalse(oto.isConstrained()); - Assert.assertEquals(2, person.getPropertyClosureSpan()); - Assert.assertEquals("compositeid gives generic id name", "id", person.getIdentifierProperty().getName()); + assertEquals(oto.getColumnSpan(),2); + assertEquals("MultiPerson", oto.getEntityName()); + assertEquals("AddressMultiPerson", oto.getReferencedEntityName()); + assertFalse(oto.isConstrained()); + assertEquals(2, person.getPropertyClosureSpan()); + assertEquals("id", person.getIdentifierProperty().getName(), "compositeid gives generic id name"); PersistentClass addressPerson = metadata.getEntityBinding("AddressMultiPerson"); Property personProperty = addressPerson.getProperty("multiPerson"); - Assert.assertNotNull(personProperty); - Assert.assertTrue(personProperty.getValue() instanceof OneToOne); + assertNotNull(personProperty); + assertTrue(personProperty.getValue() instanceof OneToOne); oto = (OneToOne) personProperty.getValue(); - Assert.assertEquals(oto.getColumnSpan(),2); - Assert.assertEquals("AddressMultiPerson", oto.getEntityName()); - Assert.assertEquals("MultiPerson", oto.getReferencedEntityName()); - Assert.assertEquals(2, addressPerson.getPropertyClosureSpan()); - Assert.assertEquals("compositeid gives generic id name","id", addressPerson.getIdentifierProperty().getName()); - Assert.assertTrue(oto.isConstrained()); + assertEquals(oto.getColumnSpan(),2); + assertEquals("AddressMultiPerson", oto.getEntityName()); + assertEquals("MultiPerson", oto.getReferencedEntityName()); + assertEquals(2, addressPerson.getPropertyClosureSpan()); + assertEquals("id", addressPerson.getIdentifierProperty().getName(), "compositeid gives generic id name"); + assertTrue(oto.isConstrained()); } @Test public void testBuildMappings() { - Assert.assertNotNull(metadata); + assertNotNull(metadata); } @Test public void testGenerateMappingAndReadable() throws MalformedURLException { - File outputDir = temporaryFolder.getRoot(); HibernateMappingExporter hme = new HibernateMappingExporter(); hme.setMetadataDescriptor(metadataDescriptor); hme.setOutputDirectory(outputDir); @@ -139,7 +156,7 @@ public void testGenerateMappingAndReadable() throws MalformedURLException { assertFileAndExists( new File(outputDir, "MiddleTable.hbm.xml") ); assertFileAndExists( new File(outputDir, "LeftTable.hbm.xml") ); assertFileAndExists( new File(outputDir, "RightTable.hbm.xml") ); - Assert.assertEquals(7, outputDir.listFiles().length); + assertEquals(7, outputDir.listFiles().length); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(outputDir); @@ -175,7 +192,6 @@ public void testGenerateMappingAndReadable() throws MalformedURLException { @Test public void testGenerateAnnotatedClassesAndReadable() throws MappingException, ClassNotFoundException, MalformedURLException { - File outputDir = temporaryFolder.getRoot(); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(outputDir); @@ -189,7 +205,7 @@ public void testGenerateAnnotatedClassesAndReadable() throws MappingException, C assertFileAndExists( new File(outputDir, "AddressMultiPerson.java") ); assertFileAndExists( new File(outputDir, "AddressMultiPersonId.java") ); assertFileAndExists( new File(outputDir, "MultiPerson.java") ); - Assert.assertEquals(9, outputDir.listFiles().length); + assertEquals(9, outputDir.listFiles().length); List paths = new ArrayList(); paths.add(JavaUtil.resolvePathToJarFileFor(Persistence.class)); // for jpa api paths.add(JavaUtil.resolvePathToJarFileFor(Version.class)); // for hibernate core @@ -228,9 +244,9 @@ public void testGenerateAnnotatedClassesAndReadable() throws MappingException, C } private void assertFileAndExists(File file) { - Assert.assertTrue(file + " does not exist", file.exists() ); - Assert.assertTrue(file + " not a file", file.isFile() ); - Assert.assertTrue(file + " does not have any contents", file.length()>0); + assertTrue(file.exists(), file + " does not exist"); + assertTrue(file.isFile(), file + " not a file"); + assertTrue(file.length()>0, file + " does not have any contents"); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OverrideBinder/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OverrideBinder/TestCase.java index 3781b9c7ce..d7ce01f773 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OverrideBinder/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/OverrideBinder/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.OverrideBinder; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.Types; import java.util.Iterator; import java.util.List; @@ -30,10 +51,9 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -48,7 +68,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); OverrideRepository or = new OverrideRepository(); @@ -60,7 +80,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -72,23 +92,23 @@ public void testReadTypeMappings() { or.addResource(TEST_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(null); - Assert.assertEquals("int", repository.columnToHibernateTypeName(null, null, Types.INTEGER, 5, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("long", repository.columnToHibernateTypeName(null, null, Types.INTEGER, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("byte[]", repository.columnToHibernateTypeName(null, null, Types.BIGINT, SQLTypeMapping.UNKNOWN_LENGTH, 5, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("java.math.BigInteger", repository.columnToHibernateTypeName(null, null, Types.BIGINT, SQLTypeMapping.UNKNOWN_LENGTH, 2, 3, false, false) ); - Assert.assertEquals("string", repository.columnToHibernateTypeName(null, null, Types.CHAR, 1, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("int", repository.columnToHibernateTypeName(null, null, Types.INTEGER, 5, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("long", repository.columnToHibernateTypeName(null, null, Types.INTEGER, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("byte[]", repository.columnToHibernateTypeName(null, null, Types.BIGINT, SQLTypeMapping.UNKNOWN_LENGTH, 5, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("java.math.BigInteger", repository.columnToHibernateTypeName(null, null, Types.BIGINT, SQLTypeMapping.UNKNOWN_LENGTH, 2, 3, false, false) ); + assertEquals("string", repository.columnToHibernateTypeName(null, null, Types.CHAR, 1, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); //Assert.assertEquals("string", repository.jdbcToHibernateType(Types.CHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE) ); - Assert.assertEquals("Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, 0, false, false) ); - Assert.assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, 43, false, false) ); + assertEquals("Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, 0, false, false) ); + assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, null, Types.NUMERIC, 1, 10, 43, false, false) ); // nullability - Assert.assertEquals("nonnull-float", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,17,false, false) ); - Assert.assertEquals("null-float", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,17,true, false) ); + assertEquals("nonnull-float", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,17,false, false) ); + assertEquals("null-float", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,17,true, false) ); - Assert.assertEquals("onlynotnull", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,SQLTypeMapping.UNKNOWN_SCALE,false, false) ); - Assert.assertEquals("donotcare", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,SQLTypeMapping.UNKNOWN_SCALE,true, false) ); + assertEquals("onlynotnull", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,SQLTypeMapping.UNKNOWN_SCALE,false, false) ); + assertEquals("donotcare", repository.columnToHibernateTypeName(null, null, Types.FLOAT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION,SQLTypeMapping.UNKNOWN_SCALE,true, false) ); } @@ -100,12 +120,12 @@ public void testDocExample() { or.addResource(DOC_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(new DefaultReverseEngineeringStrategy()); - Assert.assertEquals("int", repository.columnToHibernateTypeName(null, "ID", Types.INTEGER, SQLTypeMapping.UNKNOWN_LENGTH, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("your.package.TrimStringUserType", repository.columnToHibernateTypeName(null, "NAME", Types.VARCHAR, 30, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); - Assert.assertEquals("char", repository.columnToHibernateTypeName(null, "INITIAL", Types.VARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); - Assert.assertEquals("java.lang.Character", repository.columnToHibernateTypeName(null, "CODE", Types.VARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("big_decimal", repository.columnToHibernateTypeName(null, "SALARY", Types.NUMERIC, SQLTypeMapping.UNKNOWN_LENGTH, 15, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); - Assert.assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, "AGE", Types.NUMERIC, SQLTypeMapping.UNKNOWN_LENGTH, 3, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); + assertEquals("int", repository.columnToHibernateTypeName(null, "ID", Types.INTEGER, SQLTypeMapping.UNKNOWN_LENGTH, 10, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("your.package.TrimStringUserType", repository.columnToHibernateTypeName(null, "NAME", Types.VARCHAR, 30, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); + assertEquals("char", repository.columnToHibernateTypeName(null, "INITIAL", Types.VARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); + assertEquals("java.lang.Character", repository.columnToHibernateTypeName(null, "CODE", Types.VARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("big_decimal", repository.columnToHibernateTypeName(null, "SALARY", Types.NUMERIC, SQLTypeMapping.UNKNOWN_LENGTH, 15, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); + assertEquals("java.lang.Long", repository.columnToHibernateTypeName(null, "AGE", Types.NUMERIC, SQLTypeMapping.UNKNOWN_LENGTH, 3, SQLTypeMapping.UNKNOWN_SCALE, true, false) ); } @@ -118,29 +138,29 @@ public void testSchemaSelection() { List schemaSelectors = repository.getSchemaSelections(); - Assert.assertNotNull(schemaSelectors); - Assert.assertEquals(4,schemaSelectors.size()); + assertNotNull(schemaSelectors); + assertEquals(4,schemaSelectors.size()); SchemaSelection ss; ss = (SchemaSelection) schemaSelectors.get(0); - Assert.assertEquals(null,ss.getMatchCatalog()); - Assert.assertEquals(null,ss.getMatchSchema()); - Assert.assertEquals(null,ss.getMatchTable()); + assertEquals(null,ss.getMatchCatalog()); + assertEquals(null,ss.getMatchSchema()); + assertEquals(null,ss.getMatchTable()); ss = (SchemaSelection) schemaSelectors.get(1); - Assert.assertEquals(null,ss.getMatchCatalog()); - Assert.assertEquals("OVRTEST",ss.getMatchSchema()); - Assert.assertEquals(null,ss.getMatchTable()); + assertEquals(null,ss.getMatchCatalog()); + assertEquals("OVRTEST",ss.getMatchSchema()); + assertEquals(null,ss.getMatchTable()); ss = (SchemaSelection) schemaSelectors.get(2); - Assert.assertEquals("UBERCATALOG",ss.getMatchCatalog()); - Assert.assertEquals("OVRTEST",ss.getMatchSchema()); - Assert.assertEquals(null,ss.getMatchTable()); + assertEquals("UBERCATALOG",ss.getMatchCatalog()); + assertEquals("OVRTEST",ss.getMatchSchema()); + assertEquals(null,ss.getMatchTable()); ss = (SchemaSelection) schemaSelectors.get(3); - Assert.assertEquals("PUBLIC.*",ss.getMatchCatalog()); - Assert.assertEquals("OVRTEST",ss.getMatchSchema()); - Assert.assertEquals(".*",ss.getMatchTable()); + assertEquals("PUBLIC.*",ss.getMatchCatalog()); + assertEquals("OVRTEST",ss.getMatchSchema()); + assertEquals(".*",ss.getMatchTable()); OverrideRepository ox = new OverrideRepository(); ox.addSchemaSelection(new SchemaSelection(null, null, "DUMMY.*")); @@ -151,8 +171,8 @@ public void testSchemaSelection() { Iterator
tableMappings = md.collectTableMappings().iterator(); Table t = (Table) tableMappings.next(); - Assert.assertEquals(t.getName(), "DUMMY"); - Assert.assertFalse(tableMappings.hasNext()); + assertEquals(t.getName(), "DUMMY"); + assertFalse(tableMappings.hasNext()); } @Test @@ -162,24 +182,24 @@ public void testColumnTypeMappings() { or.addResource(OVERRIDETEST_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(null); - Assert.assertNull(repository.columnToHibernateTypeName(new TableIdentifier("blah"), "bogus",0,0,0,0, false, false)); - Assert.assertNull(repository.columnToHibernateTypeName(new TableIdentifier("ORDERS"), "CUSTID",0,0,0,0, false, false)); - Assert.assertEquals("string", repository.columnToHibernateTypeName(new TableIdentifier(null, null, "ORDERS"), "NAME",0,0,0,0, false, false)); + assertNull(repository.columnToHibernateTypeName(new TableIdentifier("blah"), "bogus",0,0,0,0, false, false)); + assertNull(repository.columnToHibernateTypeName(new TableIdentifier("ORDERS"), "CUSTID",0,0,0,0, false, false)); + assertEquals("string", repository.columnToHibernateTypeName(new TableIdentifier(null, null, "ORDERS"), "NAME",0,0,0,0, false, false)); PersistentClass classMapping = metadata.getEntityBinding("Orders"); Property property = classMapping.getProperty("completed"); - Assert.assertEquals("boolean because of not null", "boolean", ((SimpleValue)property.getValue()).getTypeName()); + assertEquals("boolean", ((SimpleValue)property.getValue()).getTypeName(), "boolean because of not null"); property = classMapping.getProperty("verified"); - Assert.assertEquals("java.lang.Boolean because of null","java.lang.Boolean", ((SimpleValue)property.getValue()).getTypeName()); + assertEquals("java.lang.Boolean", ((SimpleValue)property.getValue()).getTypeName(), "java.lang.Boolean because of null"); classMapping = metadata.getEntityBinding("MiscTypes"); property = classMapping.getIdentifierProperty(); - Assert.assertFalse(((SimpleValue)property.getValue()).isNullable()); - Assert.assertEquals("java.lang.Long because of primary key", "java.lang.Long", ((SimpleValue)property.getValue()).getTypeName()); + assertFalse(((SimpleValue)property.getValue()).isNullable()); + assertEquals("java.lang.Long", ((SimpleValue)property.getValue()).getTypeName(), "java.lang.Long because of primary key"); } @Test @@ -189,18 +209,18 @@ public void testColumnPropertyNameMappings() { or.addResource(OVERRIDETEST_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(null); - Assert.assertNull(repository.columnToPropertyName(new TableIdentifier("blah"), "bogus")); - Assert.assertNull(repository.columnToPropertyName(new TableIdentifier("ORDERS"), "cust_id")); - Assert.assertEquals("orderName", repository.columnToPropertyName(new TableIdentifier(null, null, "ORDERS"), "NAME")); + assertNull(repository.columnToPropertyName(new TableIdentifier("blah"), "bogus")); + assertNull(repository.columnToPropertyName(new TableIdentifier("ORDERS"), "cust_id")); + assertEquals("orderName", repository.columnToPropertyName(new TableIdentifier(null, null, "ORDERS"), "NAME")); } @Test public void testMetaAttributeMappings() { PersistentClass classMapping = metadata.getEntityBinding( "Orders" ); - Assert.assertEquals("order table value", classMapping.getMetaAttribute( "order-meta" ).getValue()); + assertEquals("order table value", classMapping.getMetaAttribute( "order-meta" ).getValue()); Property property = classMapping.getProperty("orderName"); - Assert.assertEquals("order column value", property.getMetaAttribute( "order-meta" ).getValue()); + assertEquals("order column value", property.getMetaAttribute( "order-meta" ).getValue()); //TODO: test sequence of meta } @@ -212,46 +232,46 @@ public void testIdGenerator() { ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(null); TableIdentifier miscTable = new TableIdentifier(null,null, "MISC_TYPES"); - Assert.assertEquals("sequence",repository.getTableIdentifierStrategyName(miscTable)); + assertEquals("sequence",repository.getTableIdentifierStrategyName(miscTable)); Map props = repository.getTableIdentifierProperties(miscTable); - Assert.assertEquals("seq_table", props.get("table")); + assertEquals("seq_table", props.get("table")); - Assert.assertNull(repository.getTableIdentifierStrategyName(new TableIdentifier("blah"))); - Assert.assertNull(repository.getTableIdentifierProperties(new TableIdentifier("blah"))); + assertNull(repository.getTableIdentifierStrategyName(new TableIdentifier("blah"))); + assertNull(repository.getTableIdentifierProperties(new TableIdentifier("blah"))); TableIdentifier ordersTable = new TableIdentifier(null,null, "ORDERS"); - Assert.assertEquals("customOrderId", repository.tableToIdentifierPropertyName(ordersTable)); - Assert.assertEquals(null, repository.tableToIdentifierPropertyName(new TableIdentifier("blah"))); + assertEquals("customOrderId", repository.tableToIdentifierPropertyName(ordersTable)); + assertEquals(null, repository.tableToIdentifierPropertyName(new TableIdentifier("blah"))); - Assert.assertEquals("CustomOID", repository.tableToCompositeIdName(ordersTable)); - Assert.assertEquals(null, repository.tableToCompositeIdName(new TableIdentifier("blah"))); + assertEquals("CustomOID", repository.tableToCompositeIdName(ordersTable)); + assertEquals(null, repository.tableToCompositeIdName(new TableIdentifier("blah"))); List primaryKeyColumnNames = repository.getPrimaryKeyColumnNames(new TableIdentifier("blah")); - Assert.assertNull(primaryKeyColumnNames); + assertNull(primaryKeyColumnNames); primaryKeyColumnNames = repository.getPrimaryKeyColumnNames(ordersTable); - Assert.assertNotNull(primaryKeyColumnNames); - Assert.assertEquals(2, primaryKeyColumnNames.size()); - Assert.assertEquals("ORDERID", primaryKeyColumnNames.get(0)); - Assert.assertEquals("CUSTID", primaryKeyColumnNames.get(1)); - Assert.assertFalse(repository.excludeColumn(ordersTable, "CUSTID")); + assertNotNull(primaryKeyColumnNames); + assertEquals(2, primaryKeyColumnNames.size()); + assertEquals("ORDERID", primaryKeyColumnNames.get(0)); + assertEquals("CUSTID", primaryKeyColumnNames.get(1)); + assertFalse(repository.excludeColumn(ordersTable, "CUSTID")); // applied PersistentClass classMapping = metadata.getEntityBinding("Orders"); SimpleValue sv = (SimpleValue) classMapping.getIdentifier(); - Assert.assertEquals("CustomOID", ((Component)sv).getComponentClassName()); + assertEquals("CustomOID", ((Component)sv).getComponentClassName()); - Assert.assertEquals(2,classMapping.getIdentifierProperty().getColumnSpan()); + assertEquals(2,classMapping.getIdentifierProperty().getColumnSpan()); Property identifierProperty = classMapping.getIdentifierProperty(); - Assert.assertEquals("customOrderId", identifierProperty.getName()); + assertEquals("customOrderId", identifierProperty.getName()); classMapping = metadata.getEntityBinding("MiscTypes"); sv = (SimpleValue) classMapping.getIdentifier(); - Assert.assertEquals("sequence", sv.getIdentifierGeneratorStrategy()); // will fail if default schema is not set since then there is no match in the override binder + assertEquals("sequence", sv.getIdentifierGeneratorStrategy()); // will fail if default schema is not set since then there is no match in the override binder - Assert.assertNotNull(sv.getIdentifierGeneratorProperties()); - Assert.assertEquals("seq_table", sv.getIdentifierGeneratorProperties().getProperty("table")); + assertNotNull(sv.getIdentifierGeneratorProperties()); + assertEquals("seq_table", sv.getIdentifierGeneratorProperties().getProperty("table")); } @@ -262,11 +282,11 @@ public void testReadExcludeTables() { or.addResource(OVERRIDETEST_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(null); - Assert.assertTrue(repository.excludeTable(new TableIdentifier(null,null, "DoNotWantIt") ) ); - Assert.assertFalse(repository.excludeTable(new TableIdentifier(null,null, "NotListedThere") ) ); - Assert.assertFalse(repository.excludeTable(new TableIdentifier("cat","sch", "WantedTable") ) ); - Assert.assertFalse(repository.excludeTable(new TableIdentifier("BAD","SCHEMA", "WantedTable") ) ); - Assert.assertTrue(repository.excludeTable(new TableIdentifier("BAD","SCHEMA", "SomethingElse") ) ); + assertTrue(repository.excludeTable(new TableIdentifier(null,null, "DoNotWantIt") ) ); + assertFalse(repository.excludeTable(new TableIdentifier(null,null, "NotListedThere") ) ); + assertFalse(repository.excludeTable(new TableIdentifier("cat","sch", "WantedTable") ) ); + assertFalse(repository.excludeTable(new TableIdentifier("BAD","SCHEMA", "WantedTable") ) ); + assertTrue(repository.excludeTable(new TableIdentifier("BAD","SCHEMA", "SomethingElse") ) ); } @@ -277,28 +297,28 @@ public void testReadPackageName() { or.addResource(OVERRIDETEST_REVENG_XML); ReverseEngineeringStrategy repository = or.getReverseEngineeringStrategy(new DefaultReverseEngineeringStrategy()); - Assert.assertEquals("org.werd.Q", repository.tableToClassName(new TableIdentifier("q","Werd", "Q") ) ); - Assert.assertEquals("Notknown", repository.tableToClassName(new TableIdentifier(null,null, "notknown") ) ); + assertEquals("org.werd.Q", repository.tableToClassName(new TableIdentifier("q","Werd", "Q") ) ); + assertEquals("Notknown", repository.tableToClassName(new TableIdentifier(null,null, "notknown") ) ); - Assert.assertEquals("org.werd.MyWorld", repository.tableToClassName(new TableIdentifier(null,"Werd", "TBL_PKG") ) ); - Assert.assertEquals("other.MyWorld", repository.tableToClassName(new TableIdentifier(null,"Werd", "TBL_OTHER") ) ); + assertEquals("org.werd.MyWorld", repository.tableToClassName(new TableIdentifier(null,"Werd", "TBL_PKG") ) ); + assertEquals("other.MyWorld", repository.tableToClassName(new TableIdentifier(null,"Werd", "TBL_OTHER") ) ); } @Test public void testRevEngExclude() { - Assert.assertNull(HibernateUtil.getTable( + assertNull(HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "DEFUNCT_TABLE") ) ); Table foundTable = HibernateUtil.getTable( metadata, JdbcUtil.toIdentifier(this, "INTHEMIDDLE") ); - Assert.assertNotNull(foundTable); + assertNotNull(foundTable); Iterator fkiter = foundTable.getForeignKeyIterator(); ForeignKey fk1 = (ForeignKey) fkiter.next(); - Assert.assertNotNull(fk1); - Assert.assertFalse(fkiter.hasNext() ); + assertNotNull(fk1); + assertFalse(fkiter.hasNext() ); } @@ -312,25 +332,25 @@ public void testSQLTypeMappingComparisons() { SQLTypeMapping morespecific = new SQLTypeMapping(Types.BIGINT, 2, 3, 4, Boolean.TRUE); SQLTypeMapping equalmorespecific = new SQLTypeMapping(Types.BIGINT, 2, 3, 4, Boolean.TRUE); - Assert.assertFalse(one.equals(two) ); - Assert.assertFalse(two.equals(one) ); - Assert.assertTrue(two.equals(two) ); - Assert.assertTrue(one.equals(one) ); - Assert.assertTrue(morespecific.equals(equalmorespecific)); + assertFalse(one.equals(two) ); + assertFalse(two.equals(one) ); + assertTrue(two.equals(two) ); + assertTrue(one.equals(one) ); + assertTrue(morespecific.equals(equalmorespecific)); - Assert.assertEquals(-1, one.compareTo(two) ); - Assert.assertEquals(1, two.compareTo(one) ); + assertEquals(-1, one.compareTo(two) ); + assertEquals(1, two.compareTo(one) ); - Assert.assertEquals(1, generic.compareTo(one) ); - Assert.assertEquals(1, generic.compareTo(two) ); - Assert.assertEquals(1, generic.compareTo(specific) ); + assertEquals(1, generic.compareTo(one) ); + assertEquals(1, generic.compareTo(two) ); + assertEquals(1, generic.compareTo(specific) ); - Assert.assertEquals(-1, specific.compareTo(one) ); - Assert.assertEquals(-1, specific.compareTo(two) ); - Assert.assertEquals(-1, specific.compareTo(generic) ); - Assert.assertEquals(1, specific.compareTo(morespecific) ); - Assert.assertEquals(-1, morespecific.compareTo(specific) ); + assertEquals(-1, specific.compareTo(one) ); + assertEquals(-1, specific.compareTo(two) ); + assertEquals(-1, specific.compareTo(generic) ); + assertEquals(1, specific.compareTo(morespecific) ); + assertEquals(-1, morespecific.compareTo(specific) ); } @@ -351,9 +371,9 @@ public void testSqlTypeOverride() { or.addTypeMapping(sqltype); ReverseEngineeringStrategy res = or.getReverseEngineeringStrategy(null); - Assert.assertEquals("boolean",res.columnToHibernateTypeName(null,null, Types.BINARY, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals(null,res.columnToHibernateTypeName(null,null, Types.LONGVARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); - Assert.assertEquals("yes_no",res.columnToHibernateTypeName(null,null, Types.BIT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("boolean",res.columnToHibernateTypeName(null,null, Types.BINARY, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals(null,res.columnToHibernateTypeName(null,null, Types.LONGVARCHAR, 1, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); + assertEquals("yes_no",res.columnToHibernateTypeName(null,null, Types.BIT, SQLTypeMapping.UNKNOWN_LENGTH, SQLTypeMapping.UNKNOWN_PRECISION, SQLTypeMapping.UNKNOWN_SCALE, false, false) ); } @Test @@ -361,18 +381,18 @@ public void testTableExclude() { TableFilter tf = new TableFilter(); tf.setMatchName("max"); tf.setExclude(Boolean.TRUE); - Assert.assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); - Assert.assertNull(tf.exclude(new TableIdentifier("maxnotexact") ) ); + assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); + assertNull(tf.exclude(new TableIdentifier("maxnotexact") ) ); tf.setMatchName(".*max"); - Assert.assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); - Assert.assertNull(tf.exclude(new TableIdentifier("maxnotending") ) ); - Assert.assertTrue(tf.exclude(new TableIdentifier("endingWithmax") ).booleanValue() ); + assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); + assertNull(tf.exclude(new TableIdentifier("maxnotending") ) ); + assertTrue(tf.exclude(new TableIdentifier("endingWithmax") ).booleanValue() ); tf.setMatchName("max.*"); - Assert.assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); + assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); tf.setMatchName(".*max.*"); - Assert.assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); - Assert.assertNull(tf.exclude(new TableIdentifier("notxam") ) ); - Assert.assertTrue(tf.exclude(new TableIdentifier("heremaxsub") ).booleanValue() ); + assertTrue(tf.exclude(new TableIdentifier("max") ).booleanValue() ); + assertNull(tf.exclude(new TableIdentifier("notxam") ) ); + assertTrue(tf.exclude(new TableIdentifier("heremaxsub") ).booleanValue() ); } @Test @@ -383,15 +403,15 @@ public void testColumnExclude() { ReverseEngineeringStrategy reverseEngineeringStrategy = or.getReverseEngineeringStrategy(); - Assert.assertFalse(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "blah")); - Assert.assertFalse(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "NAME")); - Assert.assertTrue(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "EXCOLUMN")); + assertFalse(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "blah")); + assertFalse(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "NAME")); + assertTrue(reverseEngineeringStrategy.excludeColumn(new TableIdentifier("EXCOLUMNS"), "EXCOLUMN")); Table table = HibernateUtil.getTable(metadata, JdbcUtil.toIdentifier(this, "EXCOLUMNS")); - Assert.assertNotNull(table); + assertNotNull(table); - Assert.assertNotNull(table.getColumn(new Column("name"))); - Assert.assertNull(table.getColumn(new Column("excolumn"))); + assertNotNull(table.getColumn(new Column("name"))); + assertNull(table.getColumn(new Column("excolumn"))); } @@ -402,7 +422,7 @@ public void testSimpleUserDefinedForeignKeys() { Iterator foreignKeyIterator = table.getForeignKeyIterator(); ForeignKey fk = (ForeignKey) foreignKeyIterator.next(); - Assert.assertEquals(fk.getReferencedTable().getName(), JdbcUtil.toIdentifier(this, "CUSTOMER") ); + assertEquals(fk.getReferencedTable().getName(), JdbcUtil.toIdentifier(this, "CUSTOMER") ); PersistentClass classMapping = metadata.getEntityBinding("Orders"); classMapping.getProperty("customer"); @@ -419,13 +439,13 @@ public void testCompositeUserDefinedForeignKeys() { Iterator foreignKeyIterator = table.getForeignKeyIterator(); ForeignKey fk = (ForeignKey) foreignKeyIterator.next(); - Assert.assertEquals(fk.getReferencedTable().getName(), JdbcUtil.toIdentifier(this, "PARENT") ); - Assert.assertEquals(2, fk.getReferencedColumns().size()); - Assert.assertEquals("child_to_parent", fk.getName()); + assertEquals(fk.getReferencedTable().getName(), JdbcUtil.toIdentifier(this, "PARENT") ); + assertEquals(2, fk.getReferencedColumns().size()); + assertEquals("child_to_parent", fk.getName()); PersistentClass classMapping = metadata.getEntityBinding("Children"); Property property = classMapping.getProperty("propertyParent"); - Assert.assertEquals(2,property.getColumnSpan()); + assertEquals(2,property.getColumnSpan()); classMapping = metadata.getEntityBinding("Parent"); property = classMapping.getProperty("propertyChildren"); @@ -435,13 +455,13 @@ public void testCompositeUserDefinedForeignKeys() { @Test public void testTypes() { PersistentClass classMapping = metadata.getEntityBinding("MiscTypes"); - Assert.assertEquals( + assertEquals( "SomeUserType", ((SimpleValue)classMapping.getProperty("name").getValue()).getTypeName()); - Assert.assertEquals( + assertEquals( "string", ((SimpleValue)classMapping.getProperty("shortname").getValue()).getTypeName()); - Assert.assertEquals( + assertEquals( "yes_no", ((SimpleValue)classMapping.getProperty("flag").getValue()).getTypeName()); } @@ -452,7 +472,7 @@ public void testTableToClass() { ReverseEngineeringStrategy res = new OverrideRepository().addResource(OVERRIDETEST_REVENG_XML).getReverseEngineeringStrategy(new DefaultReverseEngineeringStrategy()); TableIdentifier tableIdentifier = new TableIdentifier(null, null, "TblTest"); - Assert.assertEquals("org.test.Test", res.tableToClassName(tableIdentifier)); + assertEquals("org.test.Test", res.tableToClassName(tableIdentifier)); tableIdentifier = new TableIdentifier( Environment @@ -460,10 +480,10 @@ public void testTableToClass() { .getProperty(AvailableSettings.DEFAULT_CATALOG), "Werd", "Testy"); - Assert.assertEquals("org.werd.Testy", res.tableToClassName(tableIdentifier)); + assertEquals("org.werd.Testy", res.tableToClassName(tableIdentifier)); tableIdentifier = new TableIdentifier(null, null, "Nothing"); - Assert.assertEquals("Nothing", res.tableToClassName(tableIdentifier)); + assertEquals("Nothing", res.tableToClassName(tableIdentifier)); } @@ -474,11 +494,11 @@ public void testMetaAttributes() { TableIdentifier tableIdentifier = new TableIdentifier(null, null, "TblTest"); Map attributes = res.tableToMetaAttributes(tableIdentifier); - Assert.assertNotNull(attributes); - Assert.assertEquals(attributes.size(),1); + assertNotNull(attributes); + assertEquals(attributes.size(),1); MetaAttribute ma = (MetaAttribute) attributes.get("use-in-test"); - Assert.assertEquals(ma.getName(), "use-in-test"); - Assert.assertEquals(ma.getValue(), "true"); + assertEquals(ma.getName(), "use-in-test"); + assertEquals(ma.getValue(), "true"); tableIdentifier = new TableIdentifier( Environment @@ -487,34 +507,34 @@ public void testMetaAttributes() { "Werd", "Testy"); attributes = res.tableToMetaAttributes( tableIdentifier ); - Assert.assertNotNull(attributes); + assertNotNull(attributes); ma = attributes.get( "werd-meta" ); - Assert.assertEquals(ma.getName(), "werd-meta"); - Assert.assertEquals(ma.getValues().size(), 2); + assertEquals(ma.getName(), "werd-meta"); + assertEquals(ma.getValues().size(), 2); tableIdentifier = new TableIdentifier(null, "Werd", "MetaTable"); attributes = res.tableToMetaAttributes( tableIdentifier ); - Assert.assertNotNull(attributes); - Assert.assertEquals(2, attributes.size()); + assertNotNull(attributes); + assertEquals(2, attributes.size()); ma = attributes.get("specific-werd"); - Assert.assertEquals(ma.getName(), "specific-werd"); - Assert.assertEquals(ma.getValue(), "a one"); + assertEquals(ma.getName(), "specific-werd"); + assertEquals(ma.getValue(), "a one"); ma = attributes.get( "werd-meta" ); - Assert.assertEquals(ma.getName(), "werd-meta"); - Assert.assertEquals(1, ma.getValues().size()); // as long as no inherit this should be one - Assert.assertEquals("value three", ma.getValue()); + assertEquals(ma.getName(), "werd-meta"); + assertEquals(1, ma.getValues().size()); // as long as no inherit this should be one + assertEquals("value three", ma.getValue()); tableIdentifier = new TableIdentifier(null, null, "Nothing"); - Assert.assertEquals(null, res.tableToMetaAttributes(tableIdentifier)); + assertEquals(null, res.tableToMetaAttributes(tableIdentifier)); - Assert.assertNull(res.columnToMetaAttributes(new TableIdentifier("Nothing"), "bogus")); - Assert.assertNull(res.columnToMetaAttributes( new TableIdentifier(null, "Werd", "MetaTable"), "bogusColumn" )); + assertNull(res.columnToMetaAttributes(new TableIdentifier("Nothing"), "bogus")); + assertNull(res.columnToMetaAttributes( new TableIdentifier(null, "Werd", "MetaTable"), "bogusColumn" )); attributes = res.columnToMetaAttributes( new TableIdentifier(null, "Werd", "MetaTable"), "MetaColumn" ); - Assert.assertEquals(1, attributes.size()); + assertEquals(1, attributes.size()); ma = attributes.get("specific-column"); - Assert.assertEquals("specific-column",ma.getName()); - Assert.assertEquals("yes a column with meta",ma.getValue()); + assertEquals("specific-column",ma.getName()); + assertEquals("yes a column with meta",ma.getValue()); } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Performance/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Performance/TestCase.java index f367a520a6..89f7ecbd44 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Performance/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Performance/TestCase.java @@ -1,9 +1,26 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Performance; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -11,10 +28,9 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -25,12 +41,12 @@ public class TestCase { private static final int TABLECOUNT = 200; private static final int COLCOUNT = 10; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -45,7 +61,7 @@ public void testBasic() throws SQLException { metadata.collectTableMappings().iterator(), TABLECOUNT); Table tab = (Table) metadata.collectTableMappings().iterator().next(); - Assert.assertEquals(tab.getColumnSpan(), COLCOUNT+1); + assertEquals(tab.getColumnSpan(), COLCOUNT+1); } } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Item.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Item.java index dfecf2e303..340b041de8 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Item.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Item.java @@ -1,4 +1,22 @@ - +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.PersistentClasses; public class Item { diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Orders.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Orders.java index 27734faf38..7f9d0c10f9 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Orders.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/Orders.java @@ -1,4 +1,22 @@ - +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.PersistentClasses; import java.util.HashSet; import java.util.Set; diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/TestCase.java index 5ec29d6867..dd1151efb5 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/PersistentClasses/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.PersistentClasses; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.SQLException; import org.hibernate.Hibernate; @@ -24,10 +44,9 @@ import org.hibernate.mapping.Set; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -39,7 +58,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); DefaultReverseEngineeringStrategy c = new DefaultReverseEngineeringStrategy(); @@ -49,7 +68,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -57,22 +76,22 @@ public void tearDown() { @Test public void testCreatePersistentClasses() { PersistentClass classMapping = metadata.getEntityBinding(PACKAGE_NAME + ".Orders"); - Assert.assertNotNull("class not found", classMapping); + assertNotNull(classMapping, "class not found"); KeyValue identifier = classMapping.getIdentifier(); - Assert.assertNotNull(identifier); + assertNotNull(identifier); } @Test public void testCreateManyToOne() { PersistentClass classMapping = metadata.getEntityBinding(PACKAGE_NAME + ".Item"); - Assert.assertNotNull(classMapping); + assertNotNull(classMapping); KeyValue identifier = classMapping.getIdentifier(); - Assert.assertNotNull(identifier); - Assert.assertEquals(3,classMapping.getPropertyClosureSpan() ); + assertNotNull(identifier); + assertEquals(3,classMapping.getPropertyClosureSpan() ); Property property = classMapping.getProperty("ordersByRelatedOrderId"); - Assert.assertNotNull(property); + assertNotNull(property); property = classMapping.getProperty("ordersByOrderId"); - Assert.assertNotNull(property); + assertNotNull(property); } @Test @@ -81,11 +100,11 @@ public void testCreateOneToMany() { Property itemset = orders.getProperty("itemsForRelatedOrderId"); Collection col = (Collection) itemset.getValue(); OneToMany otm = (OneToMany) col.getElement(); - Assert.assertEquals(otm.getReferencedEntityName(), PACKAGE_NAME + ".Item"); - Assert.assertEquals(otm.getAssociatedClass().getClassName(), PACKAGE_NAME + ".Item"); - Assert.assertEquals(otm.getTable().getName(), "ORDERS"); - Assert.assertNotNull(itemset); - Assert.assertTrue(itemset.getValue() instanceof Set); + assertEquals(otm.getReferencedEntityName(), PACKAGE_NAME + ".Item"); + assertEquals(otm.getAssociatedClass().getClassName(), PACKAGE_NAME + ".Item"); + assertEquals(otm.getTable().getName(), "ORDERS"); + assertNotNull(itemset); + assertTrue(itemset.getValue() instanceof Set); } @Test @@ -124,15 +143,15 @@ public void testBinding() throws HibernateException, SQLException { Item loadeditem = (Item) session.get(PACKAGE_NAME + ".Item", new Integer(42) ); - Assert.assertEquals(item.getName(),loadeditem.getName() ); - Assert.assertEquals(item.getChildId(),loadeditem.getChildId() ); - Assert.assertEquals(item.getOrderId().getId(),loadeditem.getOrderId().getId() ); + assertEquals(item.getName(),loadeditem.getName() ); + assertEquals(item.getChildId(),loadeditem.getChildId() ); + assertEquals(item.getOrderId().getId(),loadeditem.getOrderId().getId() ); - Assert.assertTrue(loadeditem.getOrderId().getItemsForOrderId().contains(loadeditem) ); - Assert.assertTrue(item.getOrderId().getItemsForOrderId().contains(item) ); + assertTrue(loadeditem.getOrderId().getItemsForOrderId().contains(loadeditem) ); + assertTrue(item.getOrderId().getItemsForOrderId().contains(item) ); - Assert.assertEquals(5,item.getOrderId().getItemsForOrderId().size() ); - Assert.assertEquals(5,loadeditem.getOrderId().getItemsForOrderId().size() ); + assertEquals(5,item.getOrderId().getItemsForOrderId().size() ); + assertEquals(5,loadeditem.getOrderId().getItemsForOrderId().size() ); t.commit(); session.close(); @@ -141,12 +160,12 @@ public void testBinding() throws HibernateException, SQLException { t = session.beginTransaction(); order = (Orders) session.load(Orders.class, new Integer(1) ); - Assert.assertFalse(Hibernate.isInitialized(order) ); - Assert.assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) ); + assertFalse(Hibernate.isInitialized(order) ); + assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) ); order = (Orders) session.createQuery("from " + PACKAGE_NAME + ".Orders").getSingleResult(); - Assert.assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) ); + assertFalse(Hibernate.isInitialized(order.getItemsForOrderId() ) ); t.commit(); session.close(); sf.close(); diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/TestCase.java index 8447b0c1bf..96dab2f797 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.RevEngForeignKey; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.net.MalformedURLException; import org.hibernate.MappingException; @@ -16,10 +36,9 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -30,12 +49,12 @@ public class TestCase { private static final String FOREIGN_KEY_TEST_XML = "org/hibernate/tool/jdbc2cfg/RevEngForeignKey/foreignkeytest.reveng.xml"; private static final String BAD_FOREIGNKEY_XML = "org/hibernate/tool/jdbc2cfg/RevEngForeignKey/badforeignkeytest.reveng.xml"; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -46,22 +65,22 @@ public void testDefaultBiDirectional() { .createJdbcDescriptor(null, null, true) .createMetadata(); PersistentClass project = metadata.getEntityBinding("Project"); - Assert.assertNotNull(project.getProperty("worksOns")); - Assert.assertNotNull(project.getProperty("employee")); - Assert.assertEquals(3, project.getPropertyClosureSpan()); - Assert.assertEquals("projectId", project.getIdentifierProperty().getName()); + assertNotNull(project.getProperty("worksOns")); + assertNotNull(project.getProperty("employee")); + assertEquals(3, project.getPropertyClosureSpan()); + assertEquals("projectId", project.getIdentifierProperty().getName()); PersistentClass employee = metadata.getEntityBinding("Employee"); - Assert.assertNotNull(employee.getProperty("worksOns")); - Assert.assertNotNull(employee.getProperty("employees")); - Assert.assertNotNull(employee.getProperty("employee")); - Assert.assertNotNull(employee.getProperty("projects")); - Assert.assertEquals(5, employee.getPropertyClosureSpan()); - Assert.assertEquals("id", employee.getIdentifierProperty().getName()); + assertNotNull(employee.getProperty("worksOns")); + assertNotNull(employee.getProperty("employees")); + assertNotNull(employee.getProperty("employee")); + assertNotNull(employee.getProperty("projects")); + assertEquals(5, employee.getPropertyClosureSpan()); + assertEquals("id", employee.getIdentifierProperty().getName()); PersistentClass worksOn = metadata.getEntityBinding("WorksOn"); - Assert.assertNotNull(worksOn.getProperty("project")); - Assert.assertNotNull(worksOn.getProperty("employee")); - Assert.assertEquals(4, worksOn.getPropertyClosureSpan()); - Assert.assertEquals("id", worksOn.getIdentifierProperty().getName()); + assertNotNull(worksOn.getProperty("project")); + assertNotNull(worksOn.getProperty("employee")); + assertEquals(4, worksOn.getPropertyClosureSpan()); + assertEquals("id", worksOn.getIdentifierProperty().getName()); } @Test @@ -73,27 +92,27 @@ public void testSetAndManyToOne() { .createJdbcDescriptor(repository, null, true) .createMetadata(); PersistentClass project = metadata.getEntityBinding("Project"); - Assert.assertNotNull(project.getProperty("worksOns")); + assertNotNull(project.getProperty("worksOns")); assertPropertyNotExists(project, "employee", "should be removed by reveng.xml"); Property property = project.getProperty("teamLead"); - Assert.assertNotNull(property); - Assert.assertTrue(property.getValue() instanceof SimpleValue); - Assert.assertEquals(3, project.getPropertyClosureSpan()); - Assert.assertEquals("projectId", project.getIdentifierProperty().getName()); + assertNotNull(property); + assertTrue(property.getValue() instanceof SimpleValue); + assertEquals(3, project.getPropertyClosureSpan()); + assertEquals("projectId", project.getIdentifierProperty().getName()); PersistentClass employee = metadata.getEntityBinding("Employee"); - Assert.assertNotNull(employee.getProperty("worksOns")); - Assert.assertNotNull("property should be renamed by reveng.xml", employee.getProperty("manager")); + assertNotNull(employee.getProperty("worksOns")); + assertNotNull(employee.getProperty("manager"), "property should be renamed by reveng.xml"); assertPropertyNotExists( employee, "employees", "set should be excluded by reveng.xml" ); Property setProperty = employee.getProperty("managedProjects"); - Assert.assertNotNull("should be renamed by reveng.xml", setProperty); - Assert.assertEquals("delete, update", setProperty.getCascade()); - Assert.assertEquals(4, employee.getPropertyClosureSpan()); - Assert.assertEquals("id", employee.getIdentifierProperty().getName()); + assertNotNull(setProperty); + assertEquals("delete, update", setProperty.getCascade()); + assertEquals(4, employee.getPropertyClosureSpan()); + assertEquals("id", employee.getIdentifierProperty().getName()); PersistentClass worksOn = metadata.getEntityBinding("WorksOn"); - Assert.assertNotNull(worksOn.getProperty("project")); - Assert.assertNotNull(worksOn.getProperty("employee")); - Assert.assertEquals(4, worksOn.getPropertyClosureSpan()); - Assert.assertEquals("id", worksOn.getIdentifierProperty().getName()); + assertNotNull(worksOn.getProperty("project")); + assertNotNull(worksOn.getProperty("employee")); + assertEquals(4, worksOn.getPropertyClosureSpan()); + assertEquals("id", worksOn.getIdentifierProperty().getName()); } @Test @@ -111,13 +130,13 @@ public void testOneToOne() throws MalformedURLException, ClassNotFoundException assertPropertyNotExists(addressPerson, "person", "should be removed by reveng.xml"); assertPropertyNotExists(person, "addressPerson", "should be removed by reveng.xml"); Property property = addressMultiPerson.getProperty("renamedOne"); - Assert.assertNotNull(property); - Assert.assertEquals("Casade should be set to delete by reveng.xml", "delete", property.getCascade()); + assertNotNull(property); + assertEquals("delete", property.getCascade(), "Casade should be set to delete by reveng.xml"); assertPropertyNotExists(multiPerson, "addressMultiPerson", "should not be there"); Property o2o = multiPerson.getProperty("renamedInversedOne"); - Assert.assertNotNull(o2o); - Assert.assertEquals("update", o2o.getCascade()); - Assert.assertEquals("JOIN", o2o.getValue().getFetchMode().toString()); + assertNotNull(o2o); + assertEquals("update", o2o.getCascade()); + assertEquals("JOIN", o2o.getValue().getFetchMode().toString()); } @Test @@ -129,9 +148,9 @@ public void testDuplicateForeignKeyDefinition() { MetadataDescriptorFactory .createJdbcDescriptor(repository, null, true) .createMetadata(); - Assert.fail("Should fail because foreign key is already defined in the database"); // maybe we should ignore the definition and only listen to what is overwritten ? For now we error. + fail("Should fail because foreign key is already defined in the database"); // maybe we should ignore the definition and only listen to what is overwritten ? For now we error. } catch(MappingException me) { - Assert.assertTrue(me.getMessage().indexOf("already defined")>=0); + assertTrue(me.getMessage().indexOf("already defined")>=0); } } @@ -142,10 +161,10 @@ public void testManyToOneAttributeDefaults() { .createMetadata(); PersistentClass classMapping = metadata.getEntityBinding("Employee"); Property property = classMapping.getProperty("employee"); - Assert.assertEquals("none", property.getCascade()); - Assert.assertEquals(true, property.isUpdateable()); - Assert.assertEquals(true, property.isInsertable()); - Assert.assertEquals("SELECT", property.getValue().getFetchMode().toString()); + assertEquals("none", property.getCascade()); + assertEquals(true, property.isUpdateable()); + assertEquals(true, property.isInsertable()); + assertEquals("SELECT", property.getValue().getFetchMode().toString()); } @Test @@ -158,16 +177,16 @@ public void testManyToOneAttributeOverrides() { .createMetadata(); PersistentClass classMapping = metadata.getEntityBinding("Employee"); Property property = classMapping.getProperty("manager"); - Assert.assertEquals("all", property.getCascade()); - Assert.assertEquals(false, property.isUpdateable()); - Assert.assertEquals(false, property.isInsertable()); - Assert.assertEquals("JOIN", property.getValue().getFetchMode().toString()); + assertEquals("all", property.getCascade()); + assertEquals(false, property.isUpdateable()); + assertEquals(false, property.isInsertable()); + assertEquals("JOIN", property.getValue().getFetchMode().toString()); } private void assertPropertyNotExists(PersistentClass employee, String name, String msg) { try { employee.getProperty(name); - Assert.fail(msg); + fail(msg); } catch(MappingException me) { // excpected } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/SearchEscapeString/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/SearchEscapeString/TestCase.java index 38ea061ceb..6ace5a31de 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/SearchEscapeString/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/SearchEscapeString/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.SearchEscapeString; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -12,10 +30,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -25,7 +42,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -33,7 +50,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -49,11 +66,11 @@ public void testBasic() throws SQLException { Table table = HibernateUtil.getTable(metadata, JdbcUtil.toIdentifier(this, "B_TAB" ) ); Table table2 = HibernateUtil.getTable(metadata, JdbcUtil.toIdentifier(this, "B2TAB" ) ); - Assert.assertNotNull(table); - Assert.assertNotNull(table2); + assertNotNull(table); + assertNotNull(table2); - Assert.assertEquals(table.getColumnSpan(), 2); - Assert.assertEquals(table2.getColumnSpan(), 2); + assertEquals(table.getColumnSpan(), 2); + assertEquals(table2.getColumnSpan(), 2); } diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/TernarySchema/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/TernarySchema/TestCase.java index e4c60b0330..a1742bff20 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/TernarySchema/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/TernarySchema/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.TernarySchema; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.sql.SQLException; import java.util.ArrayList; @@ -21,13 +39,11 @@ import org.hibernate.tool.hbm2x.visitor.DefaultValueVisitor; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -35,12 +51,12 @@ */ public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("temp"); private MetadataDescriptor metadataDescriptor = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); DefaultReverseEngineeringStrategy c = new DefaultReverseEngineeringStrategy() { @@ -56,23 +72,22 @@ public List getSchemaSelections() { .createJdbcDescriptor(c, null, true); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } // TODO Investigate the ignored test: HBX-1410 - @Ignore + @Disabled @Test public void testTernaryModel() throws SQLException { assertMultiSchema(metadataDescriptor.createMetadata()); } // TODO Investigate the ignored test: HBX-1410 - @Ignore + @Disabled @Test public void testGeneration() { - File outputFolder = temporaryFolder.getRoot(); HibernateMappingExporter hme = new HibernateMappingExporter(); hme.setMetadataDescriptor(metadataDescriptor); hme.setOutputDirectory(outputFolder); @@ -80,7 +95,7 @@ public void testGeneration() { JUnitUtil.assertIsNonEmptyFile( new File(outputFolder, "Role.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile( new File(outputFolder, "User.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile( new File(outputFolder, "Plainrole.hbm.xml") ); - Assert.assertEquals(3, outputFolder.listFiles().length); + assertEquals(3, outputFolder.listFiles().length); File[] files = new File[3]; files[0] = new File(outputFolder, "Role.hbm.xml"); files[0] = new File(outputFolder, "User.hbm.xml"); @@ -96,28 +111,28 @@ private void assertMultiSchema(Metadata metadata) { metadata.getEntityBindings().iterator(), 5); final PersistentClass role = metadata.getEntityBinding("Role"); - Assert.assertNotNull(role); + assertNotNull(role); PersistentClass userroles = metadata.getEntityBinding("Userroles"); - Assert.assertNotNull(userroles); + assertNotNull(userroles); PersistentClass user = metadata.getEntityBinding("User"); - Assert.assertNotNull(user); + assertNotNull(user); PersistentClass plainRole = metadata.getEntityBinding("Plainrole"); - Assert.assertNotNull(plainRole); + assertNotNull(plainRole); Property property = role.getProperty("users"); - Assert.assertEquals(role.getTable().getSchema(), "OTHERSCHEMA"); - Assert.assertNotNull(property); + assertEquals(role.getTable().getSchema(), "OTHERSCHEMA"); + assertNotNull(property); property.getValue().accept(new DefaultValueVisitor(true) { public Object accept(Set o) { - Assert.assertEquals(o.getCollectionTable().getSchema(), "THIRDSCHEMA"); + assertEquals(o.getCollectionTable().getSchema(), "THIRDSCHEMA"); return null; } }); property = plainRole.getProperty("users"); - Assert.assertEquals(role.getTable().getSchema(), "OTHERSCHEMA"); - Assert.assertNotNull(property); + assertEquals(role.getTable().getSchema(), "OTHERSCHEMA"); + assertNotNull(property); property.getValue().accept(new DefaultValueVisitor(true) { public Object accept(Set o) { - Assert.assertEquals(o.getCollectionTable().getSchema(), null); + assertEquals(o.getCollectionTable().getSchema(), null); return null; } }); diff --git a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Versioning/TestCase.java b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Versioning/TestCase.java index 36d36210c9..bfecce9759 100644 --- a/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Versioning/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/jdbc2cfg/Versioning/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-11-24 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Versioning; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.boot.Metadata; @@ -14,16 +34,14 @@ import org.hibernate.tool.hbm2x.Exporter; import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.JdbcUtil; -import org.hibernate.type.BigDecimalType; +import org.hibernate.type.BigIntegerType; import org.hibernate.type.IntegerType; import org.hibernate.type.RowVersionType; import org.hibernate.type.TimestampType; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * To be extended by VersioningForJDK50Test for the JPA generation part @@ -35,10 +53,10 @@ public class TestCase { private Metadata metadata = null; private MetadataDescriptor metadataDescriptor = null; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File testFolder = new File("test"); - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadataDescriptor = MetadataDescriptorFactory @@ -47,7 +65,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this);; } @@ -56,51 +74,50 @@ public void tearDown() { public void testVersion() { PersistentClass cl = metadata.getEntityBinding("WithVersion"); Property version = cl.getVersion(); - Assert.assertNotNull(version); - Assert.assertEquals("version", version.getName()); + assertNotNull(version); + assertEquals("version", version.getName()); cl = metadata.getEntityBinding("NoVersion"); - Assert.assertNotNull(cl); + assertNotNull(cl); version = cl.getVersion(); - Assert.assertNull(version); + assertNull(version); } @Test public void testGenerateMappings() { - File testFolder = temporaryFolder.getRoot(); Exporter exporter = new HibernateMappingExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(testFolder); exporter.start(); File[] files = new File[4]; - files[0] = new File(testFolder, "Withversion.hbm.xml"); - files[1] = new File(testFolder, "Noversion.hbm.xml"); - files[2] = new File(testFolder, "Withrealtimestamp.hbm.xml"); - files[3] = new File(testFolder, "Withfaketimestamp.hbm.xml"); + files[0] = new File(testFolder, "WithVersion.hbm.xml"); + files[1] = new File(testFolder, "NoVersion.hbm.xml"); + files[2] = new File(testFolder, "WithRealTimestamp.hbm.xml"); + files[3] = new File(testFolder, "WithFakeTimestamp.hbm.xml"); Metadata metadata = MetadataDescriptorFactory .createNativeDescriptor(null, files, null) .createMetadata(); PersistentClass cl = metadata.getEntityBinding( "WithVersion" ); Property version = cl.getVersion(); - Assert.assertNotNull(version); - Assert.assertEquals("version", version.getName()); + assertNotNull(version); + assertEquals("version", version.getName()); cl = metadata.getEntityBinding( "NoVersion" ); - Assert.assertNotNull(cl); + assertNotNull(cl); version = cl.getVersion(); - Assert.assertNull(version); + assertNull(version); cl = metadata.getEntityBinding( "WithRealTimestamp" ); - Assert.assertNotNull(cl); + assertNotNull(cl); version = cl.getVersion(); - Assert.assertNotNull(version); - Assert.assertTrue( + assertNotNull(version); + assertTrue( version.getType() instanceof TimestampType || version.getType() instanceof RowVersionType); // on MS SQL Server cl = metadata.getEntityBinding( "WithFakeTimestamp" ); - Assert.assertNotNull(cl); + assertNotNull(cl); version = cl.getVersion(); - Assert.assertNotNull(version); - Assert.assertTrue( + assertNotNull(version); + assertTrue( version.getType() instanceof IntegerType || - version.getType() instanceof BigDecimalType); // on Oracle + version.getType() instanceof BigIntegerType); // on Oracle } } diff --git a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/Group.java b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/Group.java index 3e0f748c97..864ad6025d 100644 --- a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/Group.java +++ b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/Group.java @@ -1,4 +1,22 @@ -//$Id: Group.java 5686 2005-02-12 07:27:32Z steveebersole $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.stat.Statistics; import java.util.HashSet; diff --git a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/SessionAttribute.java b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/SessionAttribute.java index 20e7ffa6cd..b6de132772 100644 --- a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/SessionAttribute.java +++ b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/SessionAttribute.java @@ -1,4 +1,22 @@ -//$Id: SessionAttribute.java 5686 2005-02-12 07:27:32Z steveebersole $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.stat.Statistics; diff --git a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/TestCase.java b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/TestCase.java index 87734da755..d94e938345 100644 --- a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/TestCase.java +++ b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/TestCase.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.stat.Statistics; import org.hibernate.Session; @@ -7,31 +26,30 @@ import org.hibernate.boot.MetadataSources; import org.hibernate.tool.stat.StatisticsBrowser; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } + // HBX-1554: Ignore the test for now + // TODO: re-enable the test + @Disabled @Test public void testBrowser() throws Exception { MetadataSources mds = new MetadataSources(); mds.addResource("/org/hibernate/tool/stat/Statistics/UserGroup.hbm.xml"); -// StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); -// ssrb.applySetting("hibernate.hbm2ddl.auto", "create"); -// ssrb.applySetting("hibernate.hbm2dll.create_namespaces", true); -// ssrb.applySetting("hibernate.show_sql", true); -// Metadata md = mds.buildMetadata(ssrb.build()); Metadata md = mds.buildMetadata(); SessionFactory sf = md.buildSessionFactory(); sf.getStatistics().setStatisticsEnabled(true); @@ -57,6 +75,7 @@ public void testBrowser() throws Exception { s.createQuery( "from java.lang.Object" ).getResultList(); tx.commit(); s.close(); + sf.close(); } } diff --git a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/User.java b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/User.java index 65bc88a005..3fb975a14d 100644 --- a/test/common/src/main/java/org/hibernate/tool/stat/Statistics/User.java +++ b/test/common/src/main/java/org/hibernate/tool/stat/Statistics/User.java @@ -1,4 +1,22 @@ -//$Id: User.java 5686 2005-02-12 07:27:32Z steveebersole $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.stat.Statistics; import java.util.HashSet; diff --git a/test/common/src/main/java/org/hibernate/tool/test/db/CommonTestSuite.java b/test/common/src/main/java/org/hibernate/tool/test/db/CommonTestSuite.java deleted file mode 100644 index 828096dd0f..0000000000 --- a/test/common/src/main/java/org/hibernate/tool/test/db/CommonTestSuite.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.hibernate.tool.test.db; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ - org.hibernate.tool.ant.AntHibernateTool.TestCase.class, - org.hibernate.tool.ant.Cfg2HbmNoError.TestCase.class, - org.hibernate.tool.ant.Cfg2HbmWithCustomReverseNamingStrategy.TestCase.class, - org.hibernate.tool.ant.Cfg2HbmWithInvalidReverseNamingStrategy.TestCase.class, - org.hibernate.tool.ant.Cfg2HbmWithPackageName.TestCase.class, - org.hibernate.tool.ant.Cfg2HbmWithPackageNameAndReverseNamingStrategy.TestCase.class, - org.hibernate.tool.ant.EJB3Configuration.TestCase.class, - org.hibernate.tool.ant.GenericExport.TestCase.class, - org.hibernate.tool.ant.Hbm2JavaConfiguration.TestCase.class, - org.hibernate.tool.ant.HbmLint.TestCase.class, - org.hibernate.tool.ant.JDBCConfiguration.TestCase.class, - org.hibernate.tool.ant.JDBCConfigWithRevEngXml.TestCase.class, - org.hibernate.tool.ant.JPABogusPUnit.TestCase.class, - org.hibernate.tool.ant.JPAPropertyOverridesPUnit.TestCase.class, - org.hibernate.tool.ant.JPAPUnit.TestCase.class, - org.hibernate.tool.ant.Properties.TestCase.class, - org.hibernate.tool.ant.Query.TestCase.class, - org.hibernate.tool.ant.SchemaExportWarning.TestCase.class, - org.hibernate.tool.cfg.DriverMetaData.TestCase.class, - org.hibernate.tool.cfg.JDBCMetaDataConfiguration.TestCase.class, - org.hibernate.tool.hbm2x.CachedMetaData.TestCase.class, - org.hibernate.tool.hbm2x.DefaultDatabaseCollector.TestCase.class, - org.hibernate.tool.hbm2x.DefaultSchemaCatalog.TestCase.class, - org.hibernate.tool.hbm2x.GenerateFromJDBC.TestCase.class, - org.hibernate.tool.hbm2x.GenerateFromJDBCWithJavaKeyword.TestCase.class, - org.hibernate.tool.hbm2x.JdbcHbm2JavaEjb3.TestCase.class, - org.hibernate.tool.hbm2x.IncrementalSchemaReading.TestCase.class, - org.hibernate.tool.hbm2x.query.QueryExporterTest.TestCase.class, - org.hibernate.tool.hbmlint.HbmLintTest.TestCase.class, - org.hibernate.tool.hbmlint.SchemaAnalyzer.TestCase.class, - org.hibernate.tool.jdbc2cfg.AutoQuote.TestCase.class, - org.hibernate.tool.jdbc2cfg.Basic.TestCase.class, - org.hibernate.tool.jdbc2cfg.BasicMultiSchema.TestCase.class, - org.hibernate.tool.jdbc2cfg.CompositeId.TestCase.class, - org.hibernate.tool.jdbc2cfg.ForeignKeys.TestCase.class, - org.hibernate.tool.jdbc2cfg.Identity.TestCase.class, - org.hibernate.tool.jdbc2cfg.Index.TestCase.class, - org.hibernate.tool.jdbc2cfg.KeyPropertyCompositeId.TestCase.class, - org.hibernate.tool.jdbc2cfg.ManyToMany.TestCase.class, - org.hibernate.tool.jdbc2cfg.MetaData.TestCase.class, - org.hibernate.tool.jdbc2cfg.NoPrimaryKey.TestCase.class, - org.hibernate.tool.jdbc2cfg.OneToOne.TestCase.class, - org.hibernate.tool.jdbc2cfg.OverrideBinder.TestCase.class, - org.hibernate.tool.jdbc2cfg.Performance.TestCase.class, - org.hibernate.tool.jdbc2cfg.PersistentClasses.TestCase.class, - org.hibernate.tool.jdbc2cfg.RevEngForeignKey.TestCase.class, - org.hibernate.tool.jdbc2cfg.SearchEscapeString.TestCase.class, - org.hibernate.tool.jdbc2cfg.TernarySchema.TestCase.class, - org.hibernate.tool.jdbc2cfg.Versioning.TestCase.class, - org.hibernate.tool.stat.Statistics.TestCase.class -}) -public class CommonTestSuite {} diff --git a/test/common/src/main/java/org/hibernate/tool/test/db/DbTestSuite.java b/test/common/src/main/java/org/hibernate/tool/test/db/DbTestSuite.java new file mode 100644 index 0000000000..cd3dd17c13 --- /dev/null +++ b/test/common/src/main/java/org/hibernate/tool/test/db/DbTestSuite.java @@ -0,0 +1,79 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.test.db; + +import org.junit.jupiter.api.Nested; + +public class DbTestSuite { + + @Nested public class AntHibernateToolTests extends org.hibernate.tool.ant.AntHibernateTool.TestCase {} + @Nested public class Cfg2HbmNoError extends org.hibernate.tool.ant.Cfg2HbmNoError.TestCase {} + @Nested public class Cfg2HbmWithCustomReverseNamingStrategy extends org.hibernate.tool.ant.Cfg2HbmWithCustomReverseNamingStrategy.TestCase {} + @Nested public class Cfg2HbmWithInvalidReverseNamingStrategy extends org.hibernate.tool.ant.Cfg2HbmWithInvalidReverseNamingStrategy.TestCase {} + @Nested public class Cfg2HbmWithPackageName extends org.hibernate.tool.ant.Cfg2HbmWithPackageName.TestCase {} + @Nested public class Cfg2HbmWithPackageNameAndReverseNamingStrategy extends org.hibernate.tool.ant.Cfg2HbmWithPackageNameAndReverseNamingStrategy.TestCase {} + @Nested public class EJB3Configuration extends org.hibernate.tool.ant.EJB3Configuration.TestCase {} + @Nested public class GenericExport extends org.hibernate.tool.ant.GenericExport.TestCase {} + @Nested public class Hbm2JavaConfiguration extends org.hibernate.tool.ant.Hbm2JavaConfiguration.TestCase {} + @Nested public class Hbm2JavaEJB3Configuration extends org.hibernate.tool.ant.Hbm2JavaEJB3Configuration.TestCase {} + @Nested public class HbmLint extends org.hibernate.tool.ant.HbmLint.TestCase {} + @Nested public class JDBCConfiguration extends org.hibernate.tool.ant.JDBCConfiguration.TestCase {} + @Nested public class JDBCConfigWithRevEngXml extends org.hibernate.tool.ant.JDBCConfigWithRevEngXml.TestCase {} + @Nested public class JPABogusPUnit extends org.hibernate.tool.ant.JPABogusPUnit.TestCase {} + @Nested public class JPAPropertyOverridesPUnit extends org.hibernate.tool.ant.JPAPropertyOverridesPUnit.TestCase {} + @Nested public class JPAPUnit extends org.hibernate.tool.ant.JPAPUnit.TestCase {} + @Nested public class Properties extends org.hibernate.tool.ant.Properties.TestCase {} + @Nested public class Query extends org.hibernate.tool.ant.Query.TestCase {} + @Nested public class SchemaExportWarning extends org.hibernate.tool.ant.SchemaExportWarning.TestCase {} + @Nested public class SchemaUpdateWarning extends org.hibernate.tool.ant.SchemaUpdateWarning.TestCase {} + @Nested public class DriverMetaData extends org.hibernate.tool.cfg.DriverMetaData.TestCase {} + @Nested public class JDBCMetaDataConfiguration extends org.hibernate.tool.cfg.JDBCMetaDataConfiguration.TestCase {} + @Nested public class CachedMetaData extends org.hibernate.tool.hbm2x.CachedMetaData.TestCase {} + @Nested public class DefaultDatabaseCollector extends org.hibernate.tool.hbm2x.DefaultDatabaseCollector.TestCase {} + @Nested public class DefaultSchemaCatalog extends org.hibernate.tool.hbm2x.DefaultSchemaCatalog.TestCase {} + @Nested public class GenerateFromJDBC extends org.hibernate.tool.hbm2x.GenerateFromJDBC.TestCase {} + @Nested public class GenerateFromJDBCWithJavaKeyword extends org.hibernate.tool.hbm2x.GenerateFromJDBCWithJavaKeyword.TestCase {} + @Nested public class IncrementalSchemaReading extends org.hibernate.tool.hbm2x.IncrementalSchemaReading.TestCase {} + @Nested public class JdbcHbm2JavaEjb3 extends org.hibernate.tool.hbm2x.JdbcHbm2JavaEjb3.TestCase {} + @Nested public class QueryExporterTest extends org.hibernate.tool.hbm2x.query.QueryExporterTest.TestCase {} + @Nested public class HbmLintTest extends org.hibernate.tool.hbmlint.HbmLintTest.TestCase {} + @Nested public class SchemaAnalyzer extends org.hibernate.tool.hbmlint.SchemaAnalyzer.TestCase {} + @Nested public class AutoQuote extends org.hibernate.tool.jdbc2cfg.AutoQuote.TestCase {} + @Nested public class Basic extends org.hibernate.tool.jdbc2cfg.Basic.TestCase {} + @Nested public class BasicMultiSchema extends org.hibernate.tool.jdbc2cfg.BasicMultiSchema.TestCase {} + @Nested public class CompositeId extends org.hibernate.tool.jdbc2cfg.CompositeId.TestCase {} + @Nested public class ForeignKeys extends org.hibernate.tool.jdbc2cfg.ForeignKeys.TestCase {} + @Nested public class Identity extends org.hibernate.tool.jdbc2cfg.Identity.TestCase {} + @Nested public class Index extends org.hibernate.tool.jdbc2cfg.Index.TestCase {} + @Nested public class KeyPropertyCompositeId extends org.hibernate.tool.jdbc2cfg.KeyPropertyCompositeId.TestCase {} + @Nested public class ManyToMany extends org.hibernate.tool.jdbc2cfg.ManyToMany.TestCase {} + @Nested public class MetaData extends org.hibernate.tool.jdbc2cfg.MetaData.TestCase {} + @Nested public class NoPrimaryKey extends org.hibernate.tool.jdbc2cfg.NoPrimaryKey.TestCase {} + @Nested public class OneToOne extends org.hibernate.tool.jdbc2cfg.OneToOne.TestCase {} + @Nested public class OverrideBinder extends org.hibernate.tool.jdbc2cfg.OverrideBinder.TestCase {} + @Nested public class Performance extends org.hibernate.tool.jdbc2cfg.Performance.TestCase {} + @Nested public class PersistentClasses extends org.hibernate.tool.jdbc2cfg.PersistentClasses.TestCase {} + @Nested public class RevEngForeignKey extends org.hibernate.tool.jdbc2cfg.RevEngForeignKey.TestCase {} + @Nested public class SearchEscapeString extends org.hibernate.tool.jdbc2cfg.SearchEscapeString.TestCase {} + @Nested public class TernarySchema extends org.hibernate.tool.jdbc2cfg.TernarySchema.TestCase {} + @Nested public class Versioning extends org.hibernate.tool.jdbc2cfg.Versioning.TestCase {} + @Nested public class Statistics extends org.hibernate.tool.stat.Statistics.TestCase {} + +} diff --git a/test/common/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/TopDown.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/TopDown.hbm.xml index 7423324ed5..767bd5de29 100644 --- a/test/common/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/TopDown.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/TopDown.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/common/src/main/resources/org/hibernate/tool/ant/GenericExport/TopDown.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/ant/GenericExport/TopDown.hbm.xml index 7423324ed5..767bd5de29 100644 --- a/test/common/src/main/resources/org/hibernate/tool/ant/GenericExport/TopDown.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/ant/GenericExport/TopDown.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaConfiguration/SomeClass.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaConfiguration/SomeClass.hbm.xml index 6f660da374..a18a73271f 100644 --- a/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaConfiguration/SomeClass.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaConfiguration/SomeClass.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/SomeClass.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/SomeClass.hbm.xml index 6f660da374..a18a73271f 100644 --- a/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/SomeClass.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/ant/Hbm2JavaEJB3Configuration/SomeClass.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/common/src/main/resources/org/hibernate/tool/ant/HbmLint/Column.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/ant/HbmLint/Column.hbm.xml index 658bef462f..54b5df61c2 100644 --- a/test/common/src/main/resources/org/hibernate/tool/ant/HbmLint/Column.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/ant/HbmLint/Column.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/common/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql b/test/common/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql index d8a2f6776c..03b653a3ab 100644 --- a/test/common/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql +++ b/test/common/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql @@ -1,4 +1,4 @@ -CREATE TABLE WITH_VERSION (FIRST INT, SECOND INT, VERSION INT, NAME VARCHAR(256), PRIMARY KEY (FIRST)) -CREATE TABLE NO_VERSION (FIRST INT, SECOND INT, NAME VARCHAR(256), PRIMARY KEY (SECOND)) -CREATE TABLE WITH_REAL_TIMESTAMP (FIRST INT, SECOND INT, TIMESTAMP TIMESTAMP, NAME VARCHAR(256), PRIMARY KEY (FIRST)) -CREATE TABLE WITH_FAKE_TIMESTAMP (FIRST INT, SECOND INT, TIMESTAMP INT, NAME VARCHAR(256), PRIMARY KEY (FIRST)) +CREATE TABLE WITH_VERSION (ONE INT, TWO INT, VERSION INT, NAME VARCHAR(256), PRIMARY KEY (ONE)) +CREATE TABLE NO_VERSION (ONE INT, TWO INT, NAME VARCHAR(256), PRIMARY KEY (TWO)) +CREATE TABLE WITH_REAL_TIMESTAMP (ONE INT, TWO INT, DBTIMESTAMP TIMESTAMP, NAME VARCHAR(256), PRIMARY KEY (ONE)) +CREATE TABLE WITH_FAKE_TIMESTAMP (ONE INT, TWO INT, DBTIMESTAMP INT, NAME VARCHAR(256), PRIMARY KEY (ONE)) diff --git a/test/common/src/main/resources/org/hibernate/tool/stat/Statistics/UserGroup.hbm.xml b/test/common/src/main/resources/org/hibernate/tool/stat/Statistics/UserGroup.hbm.xml index 235fce7bb8..721aa41ed7 100644 --- a/test/common/src/main/resources/org/hibernate/tool/stat/Statistics/UserGroup.hbm.xml +++ b/test/common/src/main/resources/org/hibernate/tool/stat/Statistics/UserGroup.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> + com.h2database + h2 + ${h2.version} + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.properties b/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.properties new file mode 100644 index 0000000000..71496b3adc --- /dev/null +++ b/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.properties @@ -0,0 +1,7 @@ +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:./test;DB_CLOSE_ON_EXIT=FALSE +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.pool_size=1 +hibernate.show_sql=true \ No newline at end of file diff --git a/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.reveng.xml b/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.reveng.xml new file mode 100644 index 0000000000..7ac52fd2cf --- /dev/null +++ b/test/maven-plugin/src/it/generateHbm/src/main/resources/hibernate.reveng.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/Pojo.ftl b/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/Pojo.ftl new file mode 100644 index 0000000000..84ff76a5b2 --- /dev/null +++ b/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/Pojo.ftl @@ -0,0 +1,29 @@ +${pojo.getPackageDeclaration()} +// Generated ${date} by Hibernate Tools ${version} + +<#assign classbody> +<#include "PojoTypeDeclaration.ftl"/> { + +<#if !pojo.isInterface()> +<#include "PojoFields.ftl"/> + +<#include "PojoConstructors.ftl"/> + +<#include "PojoPropertyAccessors.ftl"/> + +<#include "PojoToString.ftl"/> + +<#include "PojoEqualsHashcode.ftl"/> + +<#else> +<#include "PojoInterfacePropertyAccessors.ftl"/> + + +<#include "PojoExtraClassCode.ftl"/> + +} + + +${pojo.generateImports()} +${classbody} + diff --git a/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/PojoFields.ftl b/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/PojoFields.ftl new file mode 100644 index 0000000000..18cf396cc6 --- /dev/null +++ b/test/maven-plugin/src/it/generateHbm/src/main/resources/templates/pojo/PojoFields.ftl @@ -0,0 +1,7 @@ +<#-- // Fields --> +<#list pojo.getAllPropertiesIterator() as field><#if pojo.getMetaAttribAsBool(field, "gen-property", true)><#if pojo.hasMetaAttribute(field, "field-description")> /** + ${pojo.getFieldJavaDoc(field, 0)} + */ + ${pojo.getFieldModifiers(field)} ${pojo.getJavaTypeName(field, jdk5)} ${c2j.keyWordCheck(field.name)}<#if pojo.hasFieldInitializor(field, jdk5)> = ${pojo.getFieldInitialization(field, jdk5)}; + + diff --git a/test/maven-plugin/src/it/generateHbm/test.mv.db b/test/maven-plugin/src/it/generateHbm/test.mv.db new file mode 100644 index 0000000000..72d79270f8 Binary files /dev/null and b/test/maven-plugin/src/it/generateHbm/test.mv.db differ diff --git a/test/maven-plugin/src/it/generateHbm/verify.groovy b/test/maven-plugin/src/it/generateHbm/verify.groovy new file mode 100644 index 0000000000..586fe51dc5 --- /dev/null +++ b/test/maven-plugin/src/it/generateHbm/verify.groovy @@ -0,0 +1,6 @@ +import java.io.*; + +File file = new File(basedir, "target/generated-sources/Person.hbm.xml"); +if (!file.isFile()) { + throw new FileNotFoundException("Could not find generated HBM file: " + file); +} diff --git a/test/maven-plugin/src/it/hbm2dao/invoker.properties b/test/maven-plugin/src/it/hbm2dao/invoker.properties new file mode 100644 index 0000000000..4537ab14c4 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/invoker.properties @@ -0,0 +1,2 @@ +invoker.java.version = 1.8+ +invoker.goals = generate-sources \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2dao/pom.xml b/test/maven-plugin/src/it/hbm2dao/pom.xml new file mode 100644 index 0000000000..66e7b39e9f --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.hibernate.tool.test + hbm2dao + 0.0.1-SNAPSHOT + + + UTF-8 + UTF-8 + + 1.8 + 1.4.195 + + + + + + org.hibernate + hibernate-tools-maven-plugin + @project.version@ + + + DAO generation + generate-sources + + hbm2dao + + + ${project.basedir}/src/main/resources/templates/ + + + + + ${project.basedir}/src/main/resources/hibernate.reveng.xml + + + + + com.h2database + h2 + ${h2.version} + + + + + + + diff --git a/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.properties b/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.properties new file mode 100644 index 0000000000..71496b3adc --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.properties @@ -0,0 +1,7 @@ +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:./test;DB_CLOSE_ON_EXIT=FALSE +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.pool_size=1 +hibernate.show_sql=true \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.reveng.xml b/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.reveng.xml new file mode 100644 index 0000000000..7ac52fd2cf --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/src/main/resources/hibernate.reveng.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2dao/src/main/resources/templates/dao/daohome.ftl b/test/maven-plugin/src/it/hbm2dao/src/main/resources/templates/dao/daohome.ftl new file mode 100644 index 0000000000..7232452587 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/src/main/resources/templates/dao/daohome.ftl @@ -0,0 +1,253 @@ +${pojo.getPackageDeclaration()} +// Generated ${date} by Hibernate Tools ${version} + +<#assign classbody> +<#assign declarationName = pojo.importType(pojo.getDeclarationName())>/** + * Home object for domain model class ${declarationName}. + * @see ${pojo.getQualifiedDeclarationName()} + * @author Hibernate Tools + */ +<#if ejb3> +@${pojo.importType("javax.ejb.Stateless")} + +public class ${declarationName}Home { + + private static final ${pojo.importType("java.util.logging.Logger")} logger = ${pojo.importType("Logger")}.getLogger(${pojo.getDeclarationName()}Home.class.getName()); + +<#if ejb3> + @${pojo.importType("javax.persistence.PersistenceContext")} private ${pojo.importType("javax.persistence.EntityManager")} entityManager; + + public void persist(${declarationName} transientInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persisting ${declarationName} instance"); + try { + entityManager.persist(transientInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persist successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "persist failed", re); + throw re; + } + } + + public void remove(${declarationName} persistentInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "removing ${declarationName} instance"); + try { + entityManager.remove(persistentInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "remove successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "remove failed", re); + throw re; + } + } + + public ${declarationName} merge(${declarationName} detachedInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merging ${declarationName} instance"); + try { + ${declarationName} result = entityManager.merge(detachedInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merge successful"); + return result; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "merge failed", re); + throw re; + } + } + +<#if clazz.identifierProperty?has_content> + public ${declarationName} findById( ${pojo.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance with id: " + id); + try { + ${declarationName} instance = entityManager.find(${pojo.getDeclarationName()}.class, id); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful"); + return instance; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "get failed", re); + throw re; + } + } + +<#else> + private final ${pojo.importType("org.hibernate.SessionFactory")} sessionFactory = getSessionFactory(); + + protected ${pojo.importType("org.hibernate.SessionFactory")} getSessionFactory() { + try { + return (${pojo.importType("org.hibernate.SessionFactory")}) new ${pojo.importType("javax.naming.InitialContext")}().lookup("${sessionFactoryName}"); + } + catch (Exception e) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "Could not locate SessionFactory in JNDI", e); + throw new IllegalStateException("Could not locate SessionFactory in JNDI"); + } + } + + public void persist(${declarationName} transientInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persisting ${declarationName} instance"); + try { + sessionFactory.getCurrentSession().persist(transientInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "persist successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "persist failed", re); + throw re; + } + } + + public void attachDirty(${declarationName} instance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attaching dirty ${declarationName} instance"); + try { + sessionFactory.getCurrentSession().saveOrUpdate(instance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attach successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "attach failed", re); + throw re; + } + } + + public void attachClean(${declarationName} instance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attaching clean ${declarationName} instance"); + try { + sessionFactory.getCurrentSession().lock(instance, ${pojo.importType("org.hibernate.LockMode")}.NONE); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "attach successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "attach failed", re); + throw re; + } + } + + public void delete(${declarationName} persistentInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "deleting ${declarationName} instance"); + try { + sessionFactory.getCurrentSession().delete(persistentInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "delete successful"); + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "delete failed", re); + throw re; + } + } + + public ${declarationName} merge(${declarationName} detachedInstance) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merging ${declarationName} instance"); + try { + ${declarationName} result = (${declarationName}) sessionFactory.getCurrentSession() + .merge(detachedInstance); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "merge successful"); + return result; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "merge failed", re); + throw re; + } + } + +<#if clazz.identifierProperty?has_content> + public ${declarationName} findById( ${c2j.getJavaTypeName(clazz.identifierProperty, jdk5)} id) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance with id: " + id); + try { + ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession() + .get("${clazz.entityName}", id); + if (instance==null) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, no instance found"); + } + else { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, instance found"); + } + return instance; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "get failed", re); + throw re; + } + } + + +<#if clazz.hasNaturalId()> + public ${declarationName} findByNaturalId(${c2j.asNaturalIdParameterList(clazz)}) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "getting ${declarationName} instance by natural id"); + try { + ${declarationName} instance = (${declarationName}) sessionFactory.getCurrentSession() + .createCriteria("${clazz.entityName}") +<#if jdk5> + .add( ${pojo.staticImport("org.hibernate.criterion.Restrictions", "naturalId")}() +<#else> + .add( ${pojo.importType("org.hibernate.criterion.Restrictions")}.naturalId() + +<#foreach property in pojo.getAllPropertiesIterator()> +<#if property.isNaturalIdentifier()> + .set("${property.name}", ${property.name}) + + + ) + .uniqueResult(); + if (instance==null) { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, no instance found"); + } + else { + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "get successful, instance found"); + } + return instance; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "query failed", re); + throw re; + } + } + +<#if jdk5> + public ${pojo.importType("java.util.List")}<${declarationName}> findByExample(${declarationName} instance) { +<#else> + public ${pojo.importType("java.util.List")} findByExample(${declarationName} instance) { + + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "finding ${declarationName} instance by example"); + try { +<#if jdk5> + ${pojo.importType("java.util.List")}<${declarationName}> results = (List<${declarationName}>) sessionFactory.getCurrentSession() +<#else> + ${pojo.importType("java.util.List")} results = sessionFactory.getCurrentSession() + + .createCriteria("${clazz.entityName}") +<#if jdk5> + .add( ${pojo.staticImport("org.hibernate.criterion.Example", "create")}(instance) ) +<#else> + .add(${pojo.importType("org.hibernate.criterion.Example")}.create(instance)) + + .list(); + logger.log(${pojo.importType("java.util.logging.Level")}.INFO, "find by example successful, result size: " + results.size()); + return results; + } + catch (RuntimeException re) { + logger.log(${pojo.importType("java.util.logging.Level")}.SEVERE, "find by example failed", re); + throw re; + } + } +<#foreach query in md.namedQueryDefinitions> +<#assign queryName = query.name> +<#if queryName.startsWith(clazz.entityName + ".")> +<#assign methname = c2j.unqualify(queryName)> +<#if jdk5 && methname.startsWith("find")> + public ${pojo.importType("java.util.List")}<${declarationName}> ${methname}(${argList}) { +<#elseif methname.startsWith("count")> + public int ${methname}(${argList}) { +<#else> + public ${pojo.importType("java.util.List")} ${methname}(${argList}) { + + ${pojo.importType("org.hibernate.Query")} query = sessionFactory.getCurrentSession() + .getNamedQuery("${queryName}"); +<#if jdk5 && methname.startsWith("find")> + return (List<${declarationName}>) query.list(); +<#elseif methname.startsWith("count")> + return ( (Integer) query.uniqueResult() ).intValue(); +<#else> + return query.list(); + + } + + +} + + +${pojo.generateImports()} +${classbody} diff --git a/test/maven-plugin/src/it/hbm2dao/test.mv.db b/test/maven-plugin/src/it/hbm2dao/test.mv.db new file mode 100644 index 0000000000..aba76d3403 Binary files /dev/null and b/test/maven-plugin/src/it/hbm2dao/test.mv.db differ diff --git a/test/maven-plugin/src/it/hbm2dao/verify.groovy b/test/maven-plugin/src/it/hbm2dao/verify.groovy new file mode 100644 index 0000000000..c1c99b0976 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2dao/verify.groovy @@ -0,0 +1,6 @@ +import java.io.*; + +File dao = new File(basedir, "target/generated-sources/PersonHome.java"); +if (!dao.isFile()) { + throw new FileNotFoundException("Could not find generated JPA DAO: " + dao); +} diff --git a/test/maven-plugin/src/it/hbm2ddl/invoker.properties b/test/maven-plugin/src/it/hbm2ddl/invoker.properties new file mode 100644 index 0000000000..13598db400 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2ddl/invoker.properties @@ -0,0 +1,2 @@ +invoker.java.version = 1.8+ +invoker.goals = generate-resources \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2ddl/pom.xml b/test/maven-plugin/src/it/hbm2ddl/pom.xml new file mode 100644 index 0000000000..00a4847b00 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2ddl/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.hibernate + hbm2ddl + 0.0.1-SNAPSHOT + + + UTF-8 + UTF-8 + + 1.8 + 1.4.195 + + + + + + org.hibernate + hibernate-tools-maven-plugin + @project.version@ + + + Schema generation + generate-resources + + hbm2ddl + + + BOTH + + + + + ${project.basedir}/src/main/resources/hibernate.reveng.xml + + + + + com.h2database + h2 + ${h2.version} + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.properties b/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.properties new file mode 100644 index 0000000000..71496b3adc --- /dev/null +++ b/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.properties @@ -0,0 +1,7 @@ +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:./test;DB_CLOSE_ON_EXIT=FALSE +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.pool_size=1 +hibernate.show_sql=true \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.reveng.xml b/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.reveng.xml new file mode 100644 index 0000000000..7ac52fd2cf --- /dev/null +++ b/test/maven-plugin/src/it/hbm2ddl/src/main/resources/hibernate.reveng.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2ddl/test.mv.db b/test/maven-plugin/src/it/hbm2ddl/test.mv.db new file mode 100644 index 0000000000..72d79270f8 Binary files /dev/null and b/test/maven-plugin/src/it/hbm2ddl/test.mv.db differ diff --git a/test/maven-plugin/src/it/hbm2ddl/verify.groovy b/test/maven-plugin/src/it/hbm2ddl/verify.groovy new file mode 100644 index 0000000000..14485800e0 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2ddl/verify.groovy @@ -0,0 +1,6 @@ +import java.io.*; + +File schema = new File(basedir, "target/generated-resources/schema.ddl"); +if (!schema.isFile()) { + throw new FileNotFoundException("Could not find generated schema file: " + schema); +} diff --git a/test/maven-plugin/src/it/hbm2java/invoker.properties b/test/maven-plugin/src/it/hbm2java/invoker.properties new file mode 100644 index 0000000000..4537ab14c4 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/invoker.properties @@ -0,0 +1,2 @@ +invoker.java.version = 1.8+ +invoker.goals = generate-sources \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2java/pom.xml b/test/maven-plugin/src/it/hbm2java/pom.xml new file mode 100644 index 0000000000..90666ccc09 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/pom.xml @@ -0,0 +1,52 @@ + + + 4.0.0 + + org.hibernate + hbm2java + 0.0.1-SNAPSHOT + + + UTF-8 + UTF-8 + + 1.8 + 1.4.195 + + + + + + org.hibernate + hibernate-tools-maven-plugin + @project.version@ + + + Entity generation + generate-sources + + hbm2java + + + ${project.basedir}/src/main/resources/templates/ + + + + + ${project.basedir}/src/main/resources/hibernate.reveng.xml + + + + + com.h2database + h2 + ${h2.version} + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.properties b/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.properties new file mode 100644 index 0000000000..71496b3adc --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.properties @@ -0,0 +1,7 @@ +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.url=jdbc:h2:./test;DB_CLOSE_ON_EXIT=FALSE +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.pool_size=1 +hibernate.show_sql=true \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.reveng.xml b/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.reveng.xml new file mode 100644 index 0000000000..7ac52fd2cf --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/src/main/resources/hibernate.reveng.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/Pojo.ftl b/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/Pojo.ftl new file mode 100644 index 0000000000..84ff76a5b2 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/Pojo.ftl @@ -0,0 +1,29 @@ +${pojo.getPackageDeclaration()} +// Generated ${date} by Hibernate Tools ${version} + +<#assign classbody> +<#include "PojoTypeDeclaration.ftl"/> { + +<#if !pojo.isInterface()> +<#include "PojoFields.ftl"/> + +<#include "PojoConstructors.ftl"/> + +<#include "PojoPropertyAccessors.ftl"/> + +<#include "PojoToString.ftl"/> + +<#include "PojoEqualsHashcode.ftl"/> + +<#else> +<#include "PojoInterfacePropertyAccessors.ftl"/> + + +<#include "PojoExtraClassCode.ftl"/> + +} + + +${pojo.generateImports()} +${classbody} + diff --git a/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/PojoFields.ftl b/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/PojoFields.ftl new file mode 100644 index 0000000000..098e5ef030 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/src/main/resources/templates/pojo/PojoFields.ftl @@ -0,0 +1,7 @@ +<#-- // Fields --> +<#foreach field in pojo.getAllPropertiesIterator()><#if pojo.getMetaAttribAsBool(field, "gen-property", true)><#if pojo.hasMetaAttribute(field, "field-description")> /** + ${pojo.getFieldJavaDoc(field, 0)} + */ + ${pojo.getFieldModifiers(field)} ${pojo.getJavaTypeName(field, jdk5)} ${c2j.keyWordCheck(field.name)}<#if pojo.hasFieldInitializor(field, jdk5)> = ${pojo.getFieldInitialization(field, jdk5)}; + + diff --git a/test/maven-plugin/src/it/hbm2java/test.mv.db b/test/maven-plugin/src/it/hbm2java/test.mv.db new file mode 100644 index 0000000000..aba76d3403 Binary files /dev/null and b/test/maven-plugin/src/it/hbm2java/test.mv.db differ diff --git a/test/maven-plugin/src/it/hbm2java/verify.groovy b/test/maven-plugin/src/it/hbm2java/verify.groovy new file mode 100644 index 0000000000..b42495d3d5 --- /dev/null +++ b/test/maven-plugin/src/it/hbm2java/verify.groovy @@ -0,0 +1,6 @@ +import java.io.*; + +File entity = new File(basedir, "target/generated-sources/Person.java"); +if (!entity.isFile()) { + throw new FileNotFoundException("Could not find generated JPA Entity: " + entity); +} diff --git a/test/maven-plugin/src/it/noPropertiesFile/invoker.properties b/test/maven-plugin/src/it/noPropertiesFile/invoker.properties new file mode 100644 index 0000000000..4537ab14c4 --- /dev/null +++ b/test/maven-plugin/src/it/noPropertiesFile/invoker.properties @@ -0,0 +1,2 @@ +invoker.java.version = 1.8+ +invoker.goals = generate-sources \ No newline at end of file diff --git a/test/maven-plugin/src/it/noPropertiesFile/pom.xml b/test/maven-plugin/src/it/noPropertiesFile/pom.xml new file mode 100644 index 0000000000..2431341e2c --- /dev/null +++ b/test/maven-plugin/src/it/noPropertiesFile/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + + org.hibernate.tool.test + no-properties-file + 0.0.1-SNAPSHOT + + + UTF-8 + UTF-8 + + 1.8 + 1.4.195 + + + + + + org.hibernate + hibernate-tools-maven-plugin + @project.version@ + + + Entity generation + generate-sources + + hbm2java + + + + + + + + \ No newline at end of file diff --git a/test/maven-plugin/src/it/noPropertiesFile/verify.groovy b/test/maven-plugin/src/it/noPropertiesFile/verify.groovy new file mode 100644 index 0000000000..040800a6dd --- /dev/null +++ b/test/maven-plugin/src/it/noPropertiesFile/verify.groovy @@ -0,0 +1,28 @@ +import java.io.*; + +println "start verify.groovy" + +File buildLog = new File(basedir, "build.log") + +if (!buildLog.isFile()) { + + println "'" + buildLog.absolutePath + "' is not a file." + + throw new FileNotFoundException("Could not find build log file: '" + buildLog + "'") + +} else { + + println "inspecting build log lines" + + boolean found = false + String startString = "[INFO] Property file '" + String endString = "src/main/resources/hibernate.properties' cannot be found, aborting..." + buildLog.eachLine { + line -> if (line.startsWith(startString) && line.endsWith(endString)) found = true + } + return found + +} + + +println "end verify.groovy" \ No newline at end of file diff --git a/test/maven-plugin/src/it/settings.xml b/test/maven-plugin/src/it/settings.xml new file mode 100644 index 0000000000..15b3aee62b --- /dev/null +++ b/test/maven-plugin/src/it/settings.xml @@ -0,0 +1,46 @@ + + + + + it-repo + + true + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + false + + + true + + plexus-snapshots + Plexus Snapshot Repository + https://oss.sonatype.org/content/repositories/plexus-snapshots + + + + + local.central + @localRepositoryUrl@ + + true + + + true + + + + + + \ No newline at end of file diff --git a/test/mssql/pom.xml b/test/mssql/pom.xml index 0944f7c29b..3de6ddfceb 100644 --- a/test/mssql/pom.xml +++ b/test/mssql/pom.xml @@ -8,7 +8,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-mssql @@ -16,10 +16,6 @@ Hibernate Tools MS SQL Server Tests Project - - junit - junit - com.microsoft.sqlserver mssql-jdbc @@ -28,6 +24,10 @@ org.hibernate hibernate-tools-tests-common + + org.junit.jupiter + junit-jupiter-engine + diff --git a/test/mssql/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java b/test/mssql/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java similarity index 75% rename from test/mssql/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java rename to test/mssql/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java index 3d9f6dae29..7ba7df2b0d 100644 --- a/test/mssql/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java +++ b/test/mssql/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java @@ -4,6 +4,9 @@ */ package org.hibernate.tool.jdbc2cfg.Identity; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -11,11 +14,10 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @author max @@ -25,7 +27,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); MetadataDescriptorFactory @@ -33,18 +35,18 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } // TODO HBX-1413: Enable the test below - @Ignore + @Disabled @Test public void testIdentity() throws SQLException { PersistentClass classMapping = metadata.getEntityBinding("WithIdentity"); - Assert.assertNotNull(classMapping); - Assert.assertEquals( + assertNotNull(classMapping); + assertEquals( "identity", ((SimpleValue)classMapping .getIdentifierProperty() @@ -53,12 +55,12 @@ public void testIdentity() throws SQLException { } // TODO HBX-1413: Enable the test below - @Ignore + @Disabled @Test public void testGuid() throws SQLException { PersistentClass classMapping = metadata.getEntityBinding("WithGuid"); - Assert.assertNotNull(classMapping); - Assert.assertEquals( + assertNotNull(classMapping); + assertEquals( "guid", ((SimpleValue)classMapping .getIdentifierProperty() diff --git a/test/mssql/src/test/java/org/hibernate/tool/test/db/sqlserver/TestSuite.java b/test/mssql/src/test/java/org/hibernate/tool/test/db/sqlserver/TestSuite.java index 39cfef5d7f..c3e74df41a 100644 --- a/test/mssql/src/test/java/org/hibernate/tool/test/db/sqlserver/TestSuite.java +++ b/test/mssql/src/test/java/org/hibernate/tool/test/db/sqlserver/TestSuite.java @@ -1,11 +1,30 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.test.db.sqlserver; -import org.hibernate.tools.test.util.DbSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite.SuiteClasses; +import org.hibernate.tool.test.db.DbTestSuite; +import org.junit.jupiter.api.Nested; -@RunWith(DbSuite.class) -@SuiteClasses({ - org.hibernate.tool.test.db.CommonTestSuite.class -}) -public class TestSuite {} +public class TestSuite { + + @Nested + public class SqlServerTestSuite extends DbTestSuite {} + +} diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/AntHibernateTool/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/AntHibernateTool/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/AntHibernateTool/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/AntHibernateTool/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/AntHibernateTool/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmNoError/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmNoError/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmNoError/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmNoError/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmNoError/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmNoError/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmNoError/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmNoError/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithCustomReverseNamingStrategy/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageName/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Cfg2HbmWithPackageNameAndReverseNamingStrategy/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/EJB3Configuration/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/EJB3Configuration/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/EJB3Configuration/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/EJB3Configuration/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/EJB3Configuration/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/EJB3Configuration/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/EJB3Configuration/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/EJB3Configuration/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfigWithRevEngXml/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfiguration/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfiguration/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfiguration/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfiguration/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfiguration/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfiguration/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JDBCConfiguration/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JDBCConfiguration/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPABogusPUnit/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPABogusPUnit/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPABogusPUnit/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPABogusPUnit/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPABogusPUnit/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPABogusPUnit/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPABogusPUnit/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPABogusPUnit/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPUnit/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPUnit/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPUnit/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPUnit/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPUnit/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPUnit/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPUnit/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPUnit/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/JPAPropertyOverridesPUnit/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Query/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Query/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Query/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Query/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/ant/Query/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/ant/Query/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/ant/Query/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/ant/Query/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/cfg/DriverMetaData/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/cfg/DriverMetaData/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/cfg/DriverMetaData/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/cfg/DriverMetaData/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/cfg/DriverMetaData/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/cfg/DriverMetaData/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/cfg/DriverMetaData/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/cfg/DriverMetaData/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/cfg/JDBCMetaDataConfiguration/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/CachedMetaData/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/CachedMetaData/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/CachedMetaData/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/CachedMetaData/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/CachedMetaData/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/CachedMetaData/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/CachedMetaData/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/CachedMetaData/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBC/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/GenerateFromJDBCWithJavaKeyword/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/IncrementalSchemaReading/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/JdbcHbm2JavaEjb3/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbm2x/query/QueryExporterTest/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Basic/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Basic/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Basic/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Basic/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Basic/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Basic/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Basic/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Basic/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/data.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/data.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/data.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/data.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeId/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeId/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ForeignKeys/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Index/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Index/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Index/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Index/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Index/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Index/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Index/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Index/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/data.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/data.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/data.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/data.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/KeyPropertyCompositeId/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/ManyToMany/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/MetaData/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/MetaData/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/MetaData/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/MetaData/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/MetaData/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/MetaData/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/MetaData/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/MetaData/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/NoPrimaryKey/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OneToOne/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OneToOne/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OneToOne/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OneToOne/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OneToOne/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OneToOne/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OneToOne/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OneToOne/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/OverrideBinder/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Performance/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Performance/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Performance/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Performance/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Performance/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Performance/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Performance/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Performance/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/SearchEscapeString/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Versioning/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Versioning/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/jdbc2cfg/Versioning/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/jdbc2cfg/Versioning/drop.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/stat/Statistics/create.sql b/test/mssql/src/test/resources/org/hibernate/tool/stat/Statistics/create.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/stat/Statistics/create.sql rename to test/mssql/src/test/resources/org/hibernate/tool/stat/Statistics/create.sql diff --git a/test/mssql/src/main/resources/org/hibernate/tool/stat/Statistics/drop.sql b/test/mssql/src/test/resources/org/hibernate/tool/stat/Statistics/drop.sql similarity index 100% rename from test/mssql/src/main/resources/org/hibernate/tool/stat/Statistics/drop.sql rename to test/mssql/src/test/resources/org/hibernate/tool/stat/Statistics/drop.sql diff --git a/test/mysql/pom.xml b/test/mysql/pom.xml index 706d9da93e..678b2dce1b 100644 --- a/test/mysql/pom.xml +++ b/test/mysql/pom.xml @@ -8,7 +8,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-mysql @@ -16,11 +16,7 @@ Hibernate Tools MySQL Tests Project - - junit - junit - - + mysql mysql-connector-java @@ -28,6 +24,10 @@ org.hibernate hibernate-tools-tests-common + + org.junit.jupiter + junit-jupiter-engine + diff --git a/test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java b/test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java similarity index 77% rename from test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java rename to test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java index c3b9eca2e8..87e2fe2153 100644 --- a/test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java +++ b/test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/TestCase.java @@ -10,6 +10,11 @@ ******************************************************************************/ package org.hibernate.tool.hbm2x.DefaultDatabaseCollector; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -35,11 +40,10 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** * @author Dmitry Geraskov @@ -47,18 +51,18 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } // TODO Reenable this test (HBX-1401) - @Ignore + @Disabled @Test public void testReadOnlySpecificSchema() { OverrideRepository or = new OverrideRepository(); @@ -68,7 +72,7 @@ public void testReadOnlySpecificSchema() { .createJdbcDescriptor(res, null, true) .createMetadata(); List
tables = getTables(metadata); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("cat.master")) { @@ -77,8 +81,8 @@ public void testReadOnlySpecificSchema() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals(new TableIdentifier(null, "cat.cat", "cat.child"), childid); - Assert.assertEquals(new TableIdentifier(null, "cat.cat", "cat.master"), masterid); + assertEquals(new TableIdentifier(null, "cat.cat", "cat.child"), childid); + assertEquals(new TableIdentifier(null, "cat.cat", "cat.master"), masterid); } @Test @@ -88,9 +92,9 @@ public void testNeedQuote() { ssrb.applySettings(properties); ServiceRegistry serviceRegistry = ssrb.build(); MetaDataDialect realMetaData = MetaDataDialectFactory.createMetaDataDialect( serviceRegistry.getService(JdbcServices.class).getDialect(), properties); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.cat")); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.child")); - Assert.assertTrue("The name must be quoted!", realMetaData.needQuote("cat.master")); + assertTrue(realMetaData.needQuote("cat.cat"), "The name must be quoted!"); + assertTrue(realMetaData.needQuote("cat.child"), "The name must be quoted!"); + assertTrue(realMetaData.needQuote("cat.master"), "The name must be quoted!"); } /** @@ -102,7 +106,7 @@ public void testNeedQuote() { * but getTable uses non-quoted names ) */ // TODO Reenable this test (HBX-1401) - @Ignore + @Disabled @Test public void testQuotedNamesAndDefaultDatabaseCollector() { Properties properties = Environment.getProperties(); @@ -117,11 +121,11 @@ properties, new DefaultReverseEngineeringStrategy(), DatabaseCollector dc = new DefaultDatabaseCollector(reader.getMetaDataDialect()); reader.readDatabaseSchema( dc, null, "cat.cat" ); String defaultCatalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG); - Assert.assertNotNull("The table should be found", dc.getTable("cat.cat", defaultCatalog, "cat.child")); - Assert.assertNotNull("The table should be found", dc.getTable("cat.cat", defaultCatalog, "cat.master")); - Assert.assertNull("Quoted names should not return the table", dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.child"))); - Assert.assertNull("Quoted names should not return the table", dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.master"))); - Assert.assertEquals("Foreign key 'masterref' was filtered!", 1, dc.getOneToManyCandidates().size()); + assertNotNull(dc.getTable("cat.cat", defaultCatalog, "cat.child"), "The table should be found"); + assertNotNull(dc.getTable("cat.cat", defaultCatalog, "cat.master"), "The table should be found"); + assertNull(dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.child")), "Quoted names should not return the table"); + assertNull(dc.getTable(quote("cat.cat"), defaultCatalog, quote("cat.master")), "Quoted names should not return the table"); + assertEquals(1, dc.getOneToManyCandidates().size(), "Foreign key 'masterref' was filtered!"); } private static String quote(String name) { diff --git a/test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java b/test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java similarity index 80% rename from test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java rename to test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java index 054736c384..87359d00d7 100644 --- a/test/mysql/src/main/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java +++ b/test/mysql/src/test/java/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/TestCase.java @@ -4,6 +4,9 @@ */ package org.hibernate.tool.hbm2x.DefaultSchemaCatalog; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -21,12 +24,10 @@ import org.hibernate.mapping.Table; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; /** @@ -36,17 +37,17 @@ */ public class TestCase { - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } - @Ignore + @Disabled @Test public void testReadOnlySpecificSchema() { OverrideRepository or = new OverrideRepository(); @@ -56,7 +57,7 @@ public void testReadOnlySpecificSchema() { .createJdbcDescriptor(res, null, true) .createMetadata(); List
tables = getTables(metadata); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("CATMASTER")) { @@ -65,11 +66,11 @@ public void testReadOnlySpecificSchema() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals(new TableIdentifier(null, "OVRTEST", "CATMASTER"), masterid); - Assert.assertEquals(new TableIdentifier(null, "OVRTEST", "CATCHILD"), childid); + assertEquals(new TableIdentifier(null, "OVRTEST", "CATMASTER"), masterid); + assertEquals(new TableIdentifier(null, "OVRTEST", "CATCHILD"), childid); } - @Ignore + @Disabled @Test public void testOverlapping() { OverrideRepository or = new OverrideRepository(); @@ -86,12 +87,12 @@ public void testOverlapping() { Table element = iter.next(); boolean added = tables.add(TableIdentifier.create(element)); if(!added) - Assert.fail("duplicate table found for " + element); + fail("duplicate table found for " + element); } - Assert.assertEquals(4,tables.size()); + assertEquals(4,tables.size()); } - @Ignore + @Disabled @Test public void testUseDefault() { Properties properties = new Properties(); @@ -101,7 +102,7 @@ public void testUseDefault() { .createJdbcDescriptor(null, properties, true) .createMetadata(); List
tables = getTables(metadata); - Assert.assertEquals(2,tables.size()); + assertEquals(2,tables.size()); Table catchild = (Table) tables.get(0); Table catmaster = (Table) tables.get(1); if(catchild.getName().equals("CATMASTER")) { @@ -110,8 +111,8 @@ public void testUseDefault() { } TableIdentifier masterid = TableIdentifier.create(catmaster); TableIdentifier childid = TableIdentifier.create(catchild); - Assert.assertEquals("jdbcreader has not nulled out according to default schema", new TableIdentifier(null, null, "CATMASTER"), masterid); - Assert.assertEquals("jdbcreader has not nulled out according to default schema", new TableIdentifier(null, null, "CATCHILD"), childid); + assertEquals(new TableIdentifier(null, null, "CATMASTER"), masterid, "jdbcreader has not nulled out according to default schema"); + assertEquals(new TableIdentifier(null, null, "CATCHILD"), childid, "jdbcreader has not nulled out according to default schema"); } private List
getTables(Metadata metadata) { diff --git a/test/mysql/src/test/java/org/hibernate/tool/test/db/mysql/TestSuite.java b/test/mysql/src/test/java/org/hibernate/tool/test/db/mysql/TestSuite.java index 93d88907ff..79cc65bedd 100644 --- a/test/mysql/src/test/java/org/hibernate/tool/test/db/mysql/TestSuite.java +++ b/test/mysql/src/test/java/org/hibernate/tool/test/db/mysql/TestSuite.java @@ -1,11 +1,30 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.test.db.mysql; -import org.hibernate.tools.test.util.DbSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite.SuiteClasses; +import org.hibernate.tool.test.db.DbTestSuite; +import org.junit.jupiter.api.Nested; -@RunWith(DbSuite.class) -@SuiteClasses({ - org.hibernate.tool.test.db.CommonTestSuite.class -}) -public class TestSuite {} +public class TestSuite { + + @Nested + public class SqlServerTestSuite extends DbTestSuite {} + +} diff --git a/test/mysql/src/test/resources/hibernate.properties b/test/mysql/src/test/resources/hibernate.properties index 0cebc65bb3..c10d836970 100644 --- a/test/mysql/src/test/resources/hibernate.properties +++ b/test/mysql/src/test/resources/hibernate.properties @@ -1,7 +1,7 @@ -hibernate.dialect org.hibernate.dialect.MySQL5InnoDBDialect +hibernate.dialect org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class com.mysql.cj.jdbc.Driver hibernate.connection.username root hibernate.connection.password P@55w0rd -hibernate.connection.url jdbc:mysql://localhost:3306/htt?useSSL=false +hibernate.connection.url jdbc:mysql://localhost:3306/htt?useSSL=false&allowPublicKeyRetrieval=true hibernate.default_catalog htt diff --git a/test/mysql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql b/test/mysql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql rename to test/mysql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql b/test/mysql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql rename to test/mysql/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml b/test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml similarity index 94% rename from test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml rename to test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml index 67c8779e6e..66c5b1f035 100644 --- a/test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml +++ b/test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql b/test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql rename to test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/create.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql b/test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql rename to test/mysql/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/drop.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql b/test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql rename to test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/create.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql b/test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql rename to test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/AutoQuote/drop.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql b/test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql rename to test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql b/test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql rename to test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql diff --git a/test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql b/test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql similarity index 100% rename from test/mysql/src/main/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql rename to test/mysql/src/test/resources/org/hibernate/tool/jdbc2cfg/RevEngForeignKey/drop.sql diff --git a/test/nodb/pom.xml b/test/nodb/pom.xml index a5394bec28..0fb6dbd5cd 100644 --- a/test/nodb/pom.xml +++ b/test/nodb/pom.xml @@ -7,7 +7,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-nodb @@ -17,26 +17,22 @@ Hibernate Tools No Database Tests Project - - org.hibernate - hibernate-tools - - - org.hibernate - hibernate-tools-tests-utils - - - junit - junit - - - jaxen - jaxen - + + org.hibernate + hibernate-tools + + + org.hibernate + hibernate-tools-tests-utils + javax javaee-api + + org.junit.jupiter + junit-jupiter-engine + diff --git a/test/nodb/src/test/java/org/hibernate/tool/VersionTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/VersionTest/TestCase.java index 07632660a1..dfd3676725 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/VersionTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/VersionTest/TestCase.java @@ -1,5 +1,7 @@ package org.hibernate.tool.VersionTest; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.io.File; import java.io.FileInputStream; import java.io.InputStream; @@ -11,8 +13,7 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -23,7 +24,7 @@ public class TestCase { @Test public void testVersion() throws Exception { - Assert.assertEquals( + assertEquals( org.hibernate.tool.Version.VERSION, extractVersion(getPomXml())); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ant/Exception/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ant/Exception/TestCase.java index 41ea5fee9b..a2c119a436 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ant/Exception/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ant/Exception/TestCase.java @@ -1,30 +1,49 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.Exception; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); } @@ -42,10 +61,10 @@ public void testException() throws Exception { try { project.executeTarget("testException"); - Assert.fail("An exception should occur"); + fail("An exception should occur"); } catch (BuildException e) { - Assert.assertTrue(e.getMessage(), e.getMessage().contains("Error while processing Entity")); + assertTrue(e.getMessage().contains("Error while processing Entity"), e.getMessage()); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ant/JavaFormatter/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ant/JavaFormatter/TestCase.java index 614d3ce375..4b3d5d7a3a 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ant/JavaFormatter/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ant/JavaFormatter/TestCase.java @@ -1,31 +1,51 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.JavaFormatter; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; -import org.hibernate.tool.ide.formatting.JavaFormatter; +import org.hibernate.tool.ide.formatting.DefaultJavaPrettyPrinterStrategy; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); } @@ -41,22 +61,22 @@ public void testJavaFormatFile() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File simpleOne = new File(destinationDir, "formatting/SimpleOne.java"); - Assert.assertFalse(simpleOne.exists()); + assertFalse(simpleOne.exists()); project.executeTarget("copyfiles"); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(simpleOne.exists()); - Assert.assertFalse(FileUtil + assertTrue(simpleOne.exists()); + assertFalse(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); - JavaFormatter formatter = new JavaFormatter(null); + DefaultJavaPrettyPrinterStrategy formatter = new DefaultJavaPrettyPrinterStrategy(null); formatter.formatFile( simpleOne ); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); @@ -74,28 +94,28 @@ public void testJavaJdk5FormatFile() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File simple5One = new File(destinationDir, "formatting/Simple5One.java"); - Assert.assertFalse(simple5One.exists()); + assertFalse(simple5One.exists()); project.executeTarget("copyfiles"); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(simple5One.exists()); - Assert.assertFalse(FileUtil + assertTrue(simple5One.exists()); + assertFalse(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); project.executeTarget("copyfiles"); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - JavaFormatter formatter = new JavaFormatter(null); - Assert.assertTrue( - "formatting should pass when using default settings", - formatter.formatFile(simple5One)); + DefaultJavaPrettyPrinterStrategy formatter = new DefaultJavaPrettyPrinterStrategy(null); + assertTrue( + formatter.formatFile(simple5One), + "formatting should pass when using default settings"); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); } @@ -112,21 +132,21 @@ public void testAntFormatTask() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File simpleOne = new File(destinationDir, "formatting/SimpleOne.java"); - Assert.assertFalse(simpleOne.exists()); + assertFalse(simpleOne.exists()); project.executeTarget("copyfiles"); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(simpleOne.exists()); - Assert.assertFalse(FileUtil + assertTrue(simpleOne.exists()); + assertFalse(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); project.executeTarget("formatfiles"); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); @@ -144,58 +164,58 @@ public void testConfig() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File simpleOne = new File(destinationDir, "formatting/SimpleOne.java"); - Assert.assertFalse(simpleOne.exists()); + assertFalse(simpleOne.exists()); File simple5One = new File(destinationDir, "formatting/Simple5One.java"); - Assert.assertFalse(simple5One.exists()); + assertFalse(simple5One.exists()); project.executeTarget("copyfiles"); String log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(simpleOne.exists()); - Assert.assertTrue(simple5One.exists()); + assertTrue(simpleOne.exists()); + assertTrue(simple5One.exists()); - Assert.assertFalse(FileUtil + assertFalse(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); - Assert.assertFalse(FileUtil + assertFalse(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); project.executeTarget("configtest"); log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); - Assert.assertTrue(simpleOne.delete()); - Assert.assertTrue(simple5One.delete()); + assertTrue(simpleOne.delete()); + assertTrue(simple5One.delete()); project.executeTarget("copyfiles"); log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertFalse(FileUtil + assertFalse(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); - Assert.assertFalse(FileUtil + assertFalse(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); project.executeTarget("noconfigtest"); log = AntUtil.getLog(project); - Assert.assertFalse(log.contains("Exception")); + assertFalse(log.contains("Exception")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simpleOne) .contains("SimpleOne")); - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString("public", simple5One) .contains("Simple5One")); diff --git a/test/nodb/src/test/java/org/hibernate/tool/ant/NoConfig/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ant/NoConfig/TestCase.java index 3eaaedbbab..23b1446ec1 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ant/NoConfig/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ant/NoConfig/TestCase.java @@ -1,30 +1,51 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.NoConfig; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); } @@ -40,20 +61,20 @@ public void testNoConfig() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File generatedSchema = new File(destinationDir, "generated-schema.sql"); - Assert.assertFalse(generatedSchema.exists()); + assertFalse(generatedSchema.exists()); try { project.executeTarget("testNoConfig"); - Assert.fail("Exception should happen"); + fail("Exception should happen"); } catch (BuildException e) { - Assert.assertTrue(e.getMessage().contains("No configuration specified")); + assertTrue(e.getMessage().contains("No configuration specified")); } - Assert.assertFalse(generatedSchema.exists()); + assertFalse(generatedSchema.exists()); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ant/NoConnInfoExport/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ant/NoConnInfoExport/TestCase.java index cd288eeb0f..9c41134b2c 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ant/NoConnInfoExport/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ant/NoConnInfoExport/TestCase.java @@ -1,30 +1,50 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.NoConnInfoExport; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File destinationDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - destinationDir = new File(temporaryFolder.getRoot(), "destination"); + destinationDir = new File(outputFolder, "destination"); destinationDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); } @@ -40,12 +60,12 @@ public void testNoConnInfoExport() { project.setProperty("resourcesDir", resourcesDir.getAbsolutePath()); File noConnInfo = new File(destinationDir, "noConnInfo.sql"); - Assert.assertFalse(noConnInfo.exists()); + assertFalse(noConnInfo.exists()); project.executeTarget("testNoConnInfoExport"); - Assert.assertTrue(noConnInfo.exists()); - Assert.assertTrue(FileUtil + assertTrue(noConnInfo.exists()); + assertTrue(FileUtil .findFirstString("create", noConnInfo) .contains("create table TopDown (id bigint not null, name varchar(255), primary key (id));")); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ant/NoExporters/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ant/NoExporters/TestCase.java index c749b633a6..7eed121b83 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ant/NoExporters/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ant/NoExporters/TestCase.java @@ -1,26 +1,47 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ant.NoExporters; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import org.apache.tools.ant.BuildException; import org.hibernate.tools.test.util.AntUtil; import org.hibernate.tools.test.util.ResourceUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private File resourcesDir = null; - @Before + @BeforeEach public void setUp() { - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); } @@ -37,12 +58,12 @@ public void testNoConnInfoExport() { try { project.executeTarget("testNoExporters"); - Assert.fail("should have failed with no exporters!"); + fail("should have failed with no exporters!"); } catch (BuildException e) { // should happen! - Assert.assertTrue(e.getMessage().indexOf("No exporters specified")>=0); + assertTrue(e.getMessage().indexOf("No exporters specified")>=0); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/cfg/MetaDataDialectFactoryTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/cfg/MetaDataDialectFactoryTest/TestCase.java index f3e2d51a51..5d45b529dd 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/cfg/MetaDataDialectFactoryTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/cfg/MetaDataDialectFactoryTest/TestCase.java @@ -1,5 +1,28 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.cfg.MetaDataDialectFactoryTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.Properties; import org.hibernate.cfg.JDBCBinderException; @@ -17,8 +40,7 @@ import org.hibernate.dialect.Oracle10gDialect; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.dialect.Oracle9iDialect; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCase { @@ -63,11 +85,11 @@ public void testCreateMetaDataDialectNonExistingOverride() { p.setProperty("hibernatetool.metadatadialect", "DoesNotExists"); try { MetaDataDialectFactory.createMetaDataDialect(new MySQL5Dialect(), p); - Assert.fail(); + fail(); } catch (JDBCBinderException jbe) { // expected } catch(Exception e) { - Assert.fail(); + fail(); } } @@ -126,33 +148,33 @@ public void testFromDialectName() { private void assertSameClass(Class clazz, Object instance) { if(clazz==null && instance==null) { - Assert.assertEquals((Object)null, (Object)null); + assertEquals((Object)null, (Object)null); return; } if(clazz==null) { - Assert.assertEquals(null, instance); + assertEquals(null, instance); return; } if(instance==null) { - Assert.assertEquals(clazz.getCanonicalName(), null); + assertEquals(clazz.getCanonicalName(), null); return; } - Assert.assertEquals(clazz.getCanonicalName(), instance.getClass().getName()); + assertEquals(clazz.getCanonicalName(), instance.getClass().getName()); } private void assertSameClass(String msg, Class clazz, Object instance) { if(clazz==null && instance==null) { - Assert.assertEquals((Object)null, (Object)null); + assertEquals((Object)null, (Object)null); return; } if(clazz==null) { - Assert.assertEquals(msg, null, instance); + assertEquals(null, instance, msg); return; } if(instance==null) { - Assert.assertEquals(msg, clazz.getCanonicalName(), null); + assertEquals(clazz.getCanonicalName(), null, msg); return; } - Assert.assertEquals(msg, clazz.getCanonicalName(), instance.getClass().getName()); + assertEquals(clazz.getCanonicalName(), instance.getClass().getName(), msg); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/cfg/reveng/ReverseEngineeringStrategyUtilTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/cfg/reveng/ReverseEngineeringStrategyUtilTest/TestCase.java index 361174739d..331b94eb3d 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/cfg/reveng/ReverseEngineeringStrategyUtilTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/cfg/reveng/ReverseEngineeringStrategyUtilTest/TestCase.java @@ -1,27 +1,47 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.cfg.reveng.ReverseEngineeringStrategyUtilTest; -import org.hibernate.cfg.reveng.ReverseEngineeringStrategyUtil; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.hibernate.cfg.reveng.ReverseEngineeringStrategyUtil; +import org.junit.jupiter.api.Test; public class TestCase { @Test public void testSimplePluralizeWithSingleH() throws Exception { String plural = ReverseEngineeringStrategyUtil.simplePluralize("h"); - Assert.assertEquals("hs", plural); + assertEquals("hs", plural); } @Test public void testPluralize(){ - Assert.assertEquals("boxes", ReverseEngineeringStrategyUtil.simplePluralize("box")); - Assert.assertEquals("buses", ReverseEngineeringStrategyUtil.simplePluralize("bus")); - Assert.assertEquals("keys", ReverseEngineeringStrategyUtil.simplePluralize("key")); - Assert.assertEquals("countries", ReverseEngineeringStrategyUtil.simplePluralize("country")); - Assert.assertEquals("churches", ReverseEngineeringStrategyUtil.simplePluralize("church")); - Assert.assertEquals("bushes", ReverseEngineeringStrategyUtil.simplePluralize("bush")); - Assert.assertEquals("roofs", ReverseEngineeringStrategyUtil.simplePluralize("roof")); + assertEquals("boxes", ReverseEngineeringStrategyUtil.simplePluralize("box")); + assertEquals("buses", ReverseEngineeringStrategyUtil.simplePluralize("bus")); + assertEquals("keys", ReverseEngineeringStrategyUtil.simplePluralize("key")); + assertEquals("countries", ReverseEngineeringStrategyUtil.simplePluralize("country")); + assertEquals("churches", ReverseEngineeringStrategyUtil.simplePluralize("church")); + assertEquals("bushes", ReverseEngineeringStrategyUtil.simplePluralize("bush")); + assertEquals("roofs", ReverseEngineeringStrategyUtil.simplePluralize("roof")); } } \ No newline at end of file diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/DocExporterTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/DocExporterTest/TestCase.java index d30297ea15..1d919af351 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/DocExporterTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/DocExporterTest/TestCase.java @@ -1,5 +1,32 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.DocExporterTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -14,11 +41,9 @@ import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; @@ -41,19 +66,19 @@ public class TestCase { "DependentValue.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private boolean ignoreDot; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "src"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); @@ -61,6 +86,7 @@ public void setUp() throws Exception { Properties properties = new Properties(); properties.put( "jdk5", "true"); // test generics properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); if(File.pathSeparator.equals(";")) { // to work around windows/jvm not seeming to respect executing just "dot" properties.put("dot.executable", System.getProperties().getProperty("dot.executable","dot.exe")); } else { @@ -73,59 +99,59 @@ public void setUp() throws Exception { properties.setProperty("dot.ignoreerror", Boolean.toString(ignoreDot)); exporter.getProperties().putAll(properties); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); } @Test public void testExporter() { - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "index.html") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "assets/doc-style.css") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "assets/hibernate_logo.gif") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "tables/default/summary.html") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "tables/default/Customer.html") ); - Assert.assertFalse(new File(outputDir, "tables/default/UPerson.html").exists() ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "tables/CROWN/CROWN_USERS.html") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "entities/org/hibernate/tool/hbm2x/Customer.html") ); - Assert.assertTrue(new File(outputDir, "entities/org/hibernate/tool/hbm2x/UPerson.html").exists() ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "entities/org/hibernate/tool/hbm2x/UUser.html") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "index.html") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "assets/doc-style.css") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "assets/hibernate_logo.gif") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "tables/default/summary.html") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "tables/default/Customer.html") ); + assertFalse(new File(srcDir, "tables/default/UPerson.html").exists() ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "tables/CROWN/CROWN_USERS.html") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "entities/org/hibernate/tool/hbm2x/Customer.html") ); + assertTrue(new File(srcDir, "entities/org/hibernate/tool/hbm2x/UPerson.html").exists() ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "entities/org/hibernate/tool/hbm2x/UUser.html") ); if (!ignoreDot) { - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "entities/entitygraph.dot")); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "entities/entitygraph.png")); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "tables/tablegraph.dot")); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "tables/tablegraph.png")); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "entities/entitygraph.dot")); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "entities/entitygraph.png")); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "tables/tablegraph.dot")); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "tables/tablegraph.png")); } - checkHtml(outputDir); + checkHtml(srcDir); } @Test public void testCommentIncluded() { - // A unique customer comment! - File tableFile = new File(outputDir, "tables/default/Customer.html"); - JUnitUtil.assertIsNonEmptyFile(tableFile ); - Assert.assertNotNull(FileUtil.findFirstString("A unique customer comment!", tableFile)); + // A unique customer comment! + File tableFile = new File(srcDir, "tables/default/Customer.html"); + JUnitUtil.assertIsNonEmptyFile(tableFile ); + assertNotNull(FileUtil.findFirstString("A unique customer comment!", tableFile)); } @Test public void testGenericsRenderedCorrectly() { - // A unique customer comment! - File tableFile = new File(outputDir, "entities/org/hibernate/tool/hbm2x/Customer.html"); - JUnitUtil.assertIsNonEmptyFile(tableFile); - Assert.assertNull( - "Generics syntax should not occur verbatim in html", - FileUtil.findFirstString("List<", tableFile)); - Assert.assertNotNull( - "Generics syntax occur verbatim in html", - FileUtil.findFirstString("List<", tableFile)); + // A unique customer comment! + File tableFile = new File(srcDir, "entities/org/hibernate/tool/hbm2x/Customer.html"); + JUnitUtil.assertIsNonEmptyFile(tableFile); + assertNull( + FileUtil.findFirstString("List<", tableFile), + "Generics syntax should not occur verbatim in html"); + assertNotNull( + FileUtil.findFirstString("List<", tableFile), + "Generics syntax occur verbatim in html"); } @Test public void testInheritedProperties() { - File entityFile = new File(outputDir, "entities/org/hibernate/tool/hbm2x/UUser.html"); + File entityFile = new File(srcDir, "entities/org/hibernate/tool/hbm2x/UUser.html"); JUnitUtil.assertIsNonEmptyFile(entityFile); - Assert.assertNotNull( - "Missing inherited property", - FileUtil.findFirstString("firstName", entityFile)); + assertNotNull( + FileUtil.findFirstString("firstName", entityFile), + "Missing inherited property"); } private void checkHtml(File file) { @@ -141,10 +167,10 @@ private void checkHtml(File file) { parser.setErrorHandler(handler); parser.setEntityResolver(new TestResolver()); parser.parse(new InputSource(new FileInputStream(file))); - Assert.assertEquals(file + "has errors ", 0, handler.errors); - Assert.assertEquals(file + "has warnings ", 0, handler.warnings); + assertEquals(0, handler.errors, file + "has errors "); + assertEquals(0, handler.warnings, file + "has warnings "); } catch (Exception e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/GenericExporterTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/GenericExporterTest/TestCase.java index 05afe4c136..a99a929429 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/GenericExporterTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/GenericExporterTest/TestCase.java @@ -1,9 +1,31 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.GenericExporterTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -17,11 +39,9 @@ import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -35,19 +55,19 @@ public class TestCase { "HelloWorld.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + private MetadataDescriptor metadataDescriptor = null; private File outputDir = null; private File resourcesDir = null; private String resourcesLocation = null; - @Before + @BeforeEach public void setUp() { - outputDir = new File(temporaryFolder.getRoot(), "output"); + outputDir = new File(outputFolder, "src"); outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); @@ -64,10 +84,10 @@ public void testSingleFileGeneration() { ge.start(); JUnitUtil.assertIsNonEmptyFile(new File( outputDir,"artifacts.txt")); JUnitUtil.assertIsNonEmptyFile(new File( outputDir, "templates.txt")); - Assert.assertEquals( + assertEquals( null, FileUtil.findFirstString("$", new File(outputDir, "artifacts.txt"))); - Assert.assertEquals( + assertEquals( "File for artifacts in " + Version.getDefault().getVersion(), FileUtil.findFirstString("artifacts", new File( outputDir, "artifacts.txt"))); } @@ -82,10 +102,10 @@ public void testFreeMarkerSyntaxFailureExpected() { ge.setFilePattern("{class-name}.ftltest"); ge.start(); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "Author.ftltest" ) ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "Article.ftlTest" ) ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "BaseHelloWorld.ftlTest" ) ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "HelloUniverse.ftlTest" ) ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "UniversalAddress.ftlTest" ) ); + JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "Article.ftltest" ) ); + JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "BaseHelloWorld.ftltest" ) ); + JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "HelloUniverse.ftltest" ) ); + JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "UniversalAddress.ftltest" ) ); } @Test @@ -127,14 +147,14 @@ public void testForEachGeneration() { JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/genericAuthor.txt")); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/genericArticle.txt")); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/genericArticle.txt")); - Assert.assertFalse( - "component file should not exist", - new File(outputDir, "genericUniversalAddress.txt" ).exists()); + assertFalse( + new File(outputDir, "genericUniversalAddress.txt" ).exists(), + "component file should not exist"); JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "genericHelloUniverse.txt" ) ); try { ge.setForEach( "does, not, exist" ); ge.start(); - Assert.fail(); + fail(); } catch(Exception e) { //e.printStackTrace(); //expected @@ -151,23 +171,23 @@ public void testForEachWithExceptionGeneration() { try { ge.setForEach("entity"); ge.start(); - Assert.fail(); + fail(); } catch(ExporterException e) { - Assert.assertTrue(e.getMessage().startsWith("Error while processing Entity:")); + assertTrue(e.getMessage().startsWith("Error while processing Entity:")); } try { ge.setForEach("component"); ge.start(); - Assert.fail(); + fail(); } catch(ExporterException e) { - Assert.assertTrue(e.getMessage().startsWith("Error while processing Component: UniversalAddress")); + assertTrue(e.getMessage().startsWith("Error while processing Component: UniversalAddress")); } try { ge.setForEach("configuration"); ge.start(); - Assert.fail(); + fail(); } catch(ExporterException e) { - Assert.assertTrue(e.getMessage().startsWith("Error while processing Configuration")); + assertTrue(e.getMessage().startsWith("Error while processing Configuration")); } } @@ -195,11 +215,11 @@ public void testPropertySet() throws FileNotFoundException, IOException { is.close(); } } - Assert.assertEquals(generated.getProperty("booleanProperty"), "true"); - Assert.assertEquals(generated.getProperty("hibernatetool.booleanProperty"), "true"); - Assert.assertNull(generated.getProperty("booleanWasTrue")); - Assert.assertEquals(generated.getProperty("myTool.value"), "value"); - Assert.assertEquals(generated.getProperty("refproperty"), "proptest=A value"); + assertEquals(generated.getProperty("booleanProperty"), "true"); + assertEquals(generated.getProperty("hibernatetool.booleanProperty"), "true"); + assertNull(generated.getProperty("booleanWasTrue")); + assertEquals(generated.getProperty("myTool.value"), "value"); + assertEquals(generated.getProperty("refproperty"), "proptest=A value"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HashcodeEqualsTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HashcodeEqualsTest/TestCase.java index b1c9481458..d6743dabf8 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HashcodeEqualsTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HashcodeEqualsTest/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.HashcodeEqualsTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.io.File; import org.hibernate.tool.api.metadata.MetadataDescriptor; @@ -14,11 +33,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -30,25 +47,25 @@ public class TestCase { "HashEquals.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private ArtifactCollector artifactCollector = null; private MetadataDescriptor metadataDescriptor = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); artifactCollector = new ArtifactCollector(); exporter.setArtifactCollector(artifactCollector); exporter.start(); @@ -58,7 +75,7 @@ public void setUp() throws Exception { public void testJDK5FailureExpectedOnJDK4() { POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.getProperties().setProperty("jdk5", "true"); artifactCollector = new ArtifactCollector(); exporter.setArtifactCollector(artifactCollector); @@ -71,17 +88,17 @@ public void testJDK5FailureExpectedOnJDK4() { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/HashEquals.java")); + srcDir, "org/hibernate/tool/hbm2x/HashEquals.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/Address.java")); - Assert.assertEquals(2, artifactCollector.getFileCount("java")); + srcDir, "org/hibernate/tool/hbm2x/Address.java")); + assertEquals(2, artifactCollector.getFileCount("java")); } @Test public void testCompilable() { - File compiled = new File(temporaryFolder.getRoot(), "compiled"); + File compiled = new File(outputFolder, "compiled"); compiled.mkdir(); - JavaUtil.compile(outputDir, compiled); + JavaUtil.compile(srcDir, compiled); JUnitUtil.assertIsNonEmptyFile(new File( compiled, "org/hibernate/tool/hbm2x/HashEquals.class")); JUnitUtil.assertIsNonEmptyFile(new File( @@ -90,17 +107,17 @@ public void testCompilable() { @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/HashEquals.java"))); - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Address.java"))); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2CfgTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2CfgTest/TestCase.java index 4a1969b1bf..927f38dfc0 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2CfgTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2CfgTest/TestCase.java @@ -1,9 +1,29 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2CfgTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.io.File; import java.util.Properties; @@ -15,11 +35,9 @@ import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -31,25 +49,25 @@ public class TestCase { "HelloWorld.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private File outputDir = null; + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; private File resourcesDir = null; private HibernateConfigurationExporter cfgexporter; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "src"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); cfgexporter = new HibernateConfigurationExporter(); cfgexporter.setMetadataDescriptor(metadataDescriptor); - cfgexporter.setOutputDirectory(outputDir); + cfgexporter.setOutputDirectory(srcDir); cfgexporter.start(); } @@ -57,61 +75,63 @@ public void setUp() throws Exception { public void testMagicPropertyHandling() { HibernateConfigurationExporter exporter = new HibernateConfigurationExporter(); Properties properties = exporter.getProperties(); - properties.setProperty( "hibernate.basic", "aValue" ); - properties.setProperty( Environment.SESSION_FACTORY_NAME, "shouldNotShowUp"); - properties.setProperty( Environment.HBM2DDL_AUTO, "false"); - properties.setProperty( "hibernate.temp.use_jdbc_metadata_defaults", "false"); - properties.setProperty("hibernate.dialect", HibernateUtil.Dialect.class.getName()); + properties.put("hibernate.basic", "aValue" ); + properties.put(AvailableSettings.SESSION_FACTORY_NAME, "shouldNotShowUp"); + properties.put(AvailableSettings.HBM2DDL_AUTO, "false"); + properties.put("hibernate.temp.use_jdbc_metadata_defaults", "false"); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); exporter.setMetadataDescriptor(MetadataDescriptorFactory .createNativeDescriptor(null, null, properties)); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); - File file = new File(outputDir, "hibernate.cfg.xml"); - Assert.assertNull( + File file = new File(srcDir, "hibernate.cfg.xml"); + assertNull( FileUtil.findFirstString( Environment.SESSION_FACTORY_NAME, file )); - Assert.assertNotNull( + assertNotNull( FileUtil.findFirstString( "hibernate.basic\">aValue<", file )); - Assert.assertNull( + assertNull( FileUtil.findFirstString( Environment.HBM2DDL_AUTO, file )); - Assert.assertNull( + assertNull( FileUtil.findFirstString("hibernate.temp.use_jdbc_metadata_defaults", file )); exporter = new HibernateConfigurationExporter(); properties = exporter.getProperties(); - properties.setProperty( Environment.HBM2DDL_AUTO, "validator"); - properties.setProperty("hibernate.dialect", HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.HBM2DDL_AUTO, "validator"); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); exporter.setMetadataDescriptor(MetadataDescriptorFactory .createNativeDescriptor(null, null, properties)); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); - Assert.assertNotNull( + assertNotNull( FileUtil.findFirstString( Environment.HBM2DDL_AUTO, file )); exporter = new HibernateConfigurationExporter(); properties = exporter.getProperties(); - properties.setProperty( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); // Hack for seam-gen console configurations - properties.setProperty("hibernate.dialect", HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "org.hibernate.console.FakeTransactionManagerLookup"); // Hack for seam-gen console configurations + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); exporter.setMetadataDescriptor(MetadataDescriptorFactory .createNativeDescriptor(null, null, properties)); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); - Assert.assertNull( + assertNull( FileUtil.findFirstString( AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, file )); } @Test public void testFileExistence() { - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "hibernate.cfg.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "hibernate.cfg.xml") ); } @Test public void testArtifactCollection() { - Assert.assertEquals(1, cfgexporter.getArtifactCollector().getFileCount("cfg.xml")); + assertEquals(1, cfgexporter.getArtifactCollector().getFileCount("cfg.xml")); } - @SuppressWarnings("el-syntax") @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil.findFirstString("${",new File(outputDir, "hibernate.cfg.xml"))); + assertNull(FileUtil.findFirstString("${",new File(srcDir, "hibernate.cfg.xml"))); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2DaoTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2DaoTest/TestCase.java index eb5f7c4ac6..27d376b63a 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2DaoTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2DaoTest/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2DaoTest; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.IOException; @@ -14,11 +33,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -31,26 +48,26 @@ public class TestCase { "Author.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir; + private File srcDir; private File resourcesDir; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "src"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); POJOExporter javaExporter = new POJOExporter(); javaExporter.setMetadataDescriptor(metadataDescriptor); - javaExporter.setOutputDirectory(outputDir); + javaExporter.setOutputDirectory(srcDir); POJOExporter exporter = new DAOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.getProperties().setProperty("ejb3", "false"); exporter.getProperties().setProperty("jdk5", "true"); exporter.start(); @@ -60,47 +77,47 @@ public void setUp() throws Exception { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/ArticleHome.java")); + srcDir, "org/hibernate/tool/hbm2x/ArticleHome.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/AuthorHome.java")); + srcDir, "org/hibernate/tool/hbm2x/AuthorHome.java")); } @Test public void testCompilable() throws IOException { - File compiled = new File(temporaryFolder.getRoot(), "compiled"); + File compiled = new File(outputFolder, "compiled"); compiled.mkdir(); - FileUtil.generateNoopComparator(outputDir); - JavaUtil.compile(outputDir, compiled); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Article.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/ArticleHome.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Author.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/AuthorHome.class").exists()); - Assert.assertTrue(new File(compiled, "comparator/NoopComparator.class").exists()); + FileUtil.generateNoopComparator(srcDir); + JavaUtil.compile(srcDir, compiled); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Article.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/ArticleHome.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Author.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/AuthorHome.class").exists()); + assertTrue(new File(compiled, "comparator/NoopComparator.class").exists()); } @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/ArticleHome.java"))); - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/AuthorHome.java"))); } @Test public void testNamedQueries() { - Assert.assertTrue(FileUtil + assertTrue(FileUtil .findFirstString( "findByNameAndAddress", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/AuthorHome.java") ) .trim().startsWith("public List" )); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2EJBDaoTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2EJBDaoTest/TestCase.java index 5c95704957..3b88845dcc 100755 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2EJBDaoTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2EJBDaoTest/TestCase.java @@ -1,9 +1,28 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2EJBDaoTest; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -12,7 +31,6 @@ import javax.ejb.EJB; import javax.persistence.Persistence; -import org.apache.commons.logging.Log; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.hbm2x.DAOExporter; import org.hibernate.tool.hbm2x.POJOExporter; @@ -20,11 +38,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -37,26 +53,26 @@ public class TestCase { "Author.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; - private File resourcesDir = null; + private File srcDir; + private File resourcesDir; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "src"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); POJOExporter javaExporter = new POJOExporter(); javaExporter.setMetadataDescriptor(metadataDescriptor); - javaExporter.setOutputDirectory(outputDir); + javaExporter.setOutputDirectory(srcDir); POJOExporter exporter = new DAOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.getProperties().setProperty("ejb3", "true"); exporter.getProperties().setProperty("jdk5", "true"); exporter.start(); @@ -66,41 +82,40 @@ public void setUp() throws Exception { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/ArticleHome.java")); + srcDir, "org/hibernate/tool/hbm2x/ArticleHome.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, "org/hibernate/tool/hbm2x/AuthorHome.java")); + srcDir, "org/hibernate/tool/hbm2x/AuthorHome.java")); } @Test public void testCompilable() throws IOException { - File compiled = new File(temporaryFolder.getRoot(), "compiled"); + File compiled = new File(outputFolder, "compiled"); compiled.mkdir(); - FileUtil.generateNoopComparator(outputDir); + FileUtil.generateNoopComparator(srcDir); List jars = new ArrayList(); - jars.add(JavaUtil.resolvePathToJarFileFor(Log.class)); // for commons logging jars.add(JavaUtil.resolvePathToJarFileFor(Persistence.class)); // for jpa api jars.add(JavaUtil.resolvePathToJarFileFor(EJB.class)); // for javaee api - JavaUtil.compile(outputDir, compiled); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Article.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/ArticleHome.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Author.class").exists()); - Assert.assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/AuthorHome.class").exists()); - Assert.assertTrue(new File(compiled, "comparator/NoopComparator.class").exists()); + JavaUtil.compile(srcDir, compiled); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Article.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/ArticleHome.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/Author.class").exists()); + assertTrue(new File(compiled, "org/hibernate/tool/hbm2x/AuthorHome.class").exists()); + assertTrue(new File(compiled, "comparator/NoopComparator.class").exists()); } @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/ArticleHome.java"))); - Assert.assertNull(FileUtil + assertNull(FileUtil .findFirstString( "$", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/AuthorHome.java"))); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/TestCase.java index fb5870fb27..a9a7cb2dd6 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2HibernateDAOTest; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -11,7 +29,6 @@ import javax.persistence.Persistence; -import org.apache.commons.logging.Log; import org.hibernate.Version; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.hbm2x.DAOExporter; @@ -20,11 +37,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -37,26 +52,26 @@ public class TestCase { "Author.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private File outputDir = null; + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); POJOExporter javaExporter = new POJOExporter(); javaExporter.setMetadataDescriptor(metadataDescriptor); - javaExporter.setOutputDirectory(outputDir); + javaExporter.setOutputDirectory(srcDir); POJOExporter exporter = new DAOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.getProperties().setProperty("ejb3", "false"); exporter.getProperties().setProperty("jdk5", "true"); exporter.start(); @@ -66,23 +81,22 @@ public void setUp() throws Exception { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/ArticleHome.java") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/AuthorHome.java") ); } @Test public void testCompilable() throws IOException { - File compiled = new File(temporaryFolder.getRoot(), "compiled"); + File compiled = new File(outputFolder, "compiled"); compiled.mkdir(); - FileUtil.generateNoopComparator(outputDir); + FileUtil.generateNoopComparator(srcDir); List jars = new ArrayList(); - jars.add(JavaUtil.resolvePathToJarFileFor(Log.class)); // for commons logging jars.add(JavaUtil.resolvePathToJarFileFor(Persistence.class)); // for jpa api jars.add(JavaUtil.resolvePathToJarFileFor(Version.class)); // for hibernate core - JavaUtil.compile(outputDir, compiled, jars); + JavaUtil.compile(srcDir, compiled, jars); JUnitUtil.assertIsNonEmptyFile(new File( compiled, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/AuthorHome.class") ); @@ -102,12 +116,12 @@ public void testCompilable() throws IOException { @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", - new File(outputDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/ArticleHome.java"))); - Assert.assertNull(FileUtil.findFirstString( + new File(srcDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/ArticleHome.java"))); + assertNull(FileUtil.findFirstString( "$", - new File(outputDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/AuthorHome.java") ) ); + new File(srcDir, "org/hibernate/tool/hbm2x/Hbm2HibernateDAOTest/AuthorHome.java") ) ); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaConstructorTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaConstructorTest/TestCase.java index cf812b235a..1ccd15d943 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaConstructorTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaConstructorTest/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaConstructorTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.file.Files; import java.util.HashSet; @@ -22,11 +43,9 @@ import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -38,26 +57,26 @@ public class TestCase { "Constructors.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Metadata metadata = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); metadata = metadataDescriptor.createMetadata(); Exporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); } @@ -65,28 +84,28 @@ public void setUp() throws Exception { public void testCompilable() throws Exception { String constructorUsageResourcePath = "/org/hibernate/tool/hbm2x/Hbm2JavaConstructorTest/ConstructorUsage.java_"; File constructorUsageOrigin = new File(getClass().getResource(constructorUsageResourcePath).toURI()); - File constructorUsageDestination = new File(outputDir, "ConstructorUsage.java"); - File targetDir = new File(temporaryFolder.getRoot(), "compilerOutput" ); + File constructorUsageDestination = new File(srcDir, "ConstructorUsage.java"); + File targetDir = new File(outputFolder, "compilerOutput" ); targetDir.mkdir(); Files.copy(constructorUsageOrigin.toPath(), constructorUsageDestination.toPath()); - JavaUtil.compile(outputDir, targetDir); - Assert.assertTrue(new File(targetDir, "ConstructorUsage.class").exists()); - Assert.assertTrue(new File(targetDir, "Company.class").exists()); - Assert.assertTrue(new File(targetDir, "BigCompany.class").exists()); - Assert.assertTrue(new File(targetDir, "EntityAddress.class").exists()); + JavaUtil.compile(srcDir, targetDir); + assertTrue(new File(targetDir, "ConstructorUsage.class").exists()); + assertTrue(new File(targetDir, "Company.class").exists()); + assertTrue(new File(targetDir, "BigCompany.class").exists()); + assertTrue(new File(targetDir, "EntityAddress.class").exists()); } @Test public void testNoVelocityLeftOvers() { - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", - new File(outputDir, "Company.java" ) ) ); - Assert.assertNull(FileUtil.findFirstString( + new File(srcDir, "Company.java" ) ) ); + assertNull(FileUtil.findFirstString( "$", - new File(outputDir,"BigCompany.java" ) ) ); - Assert.assertNull(FileUtil.findFirstString( + new File(srcDir,"BigCompany.java" ) ) ); + assertNull(FileUtil.findFirstString( "$", - new File(outputDir,"EntityAddress.java" ) ) ); + new File(srcDir,"EntityAddress.java" ) ) ); } @Test @@ -95,31 +114,31 @@ public void testEntityConstructorLogic() { POJOClass company = c2j.getPOJOClass(metadata.getEntityBinding("Company")); List all = company.getPropertyClosureForFullConstructor(); assertNoDuplicates(all); - Assert.assertEquals(3, all.size()); + assertEquals(3, all.size()); List superCons = company.getPropertyClosureForSuperclassFullConstructor(); - Assert.assertEquals("company is a base class, should not have superclass cons",0, superCons.size()); + assertEquals(0, superCons.size(), "company is a base class, should not have superclass cons"); List subCons = company.getPropertiesForFullConstructor(); assertNoDuplicates(subCons); - Assert.assertEquals(3, subCons.size()); + assertEquals(3, subCons.size()); assertNoOverlap(superCons, subCons); POJOClass bigCompany = c2j.getPOJOClass(metadata.getEntityBinding("BigCompany")); List bigsuperCons = bigCompany.getPropertyClosureForSuperclassFullConstructor(); assertNoDuplicates(bigsuperCons); //assertEquals(3, bigsuperCons.size()); List bigsubCons = bigCompany.getPropertiesForFullConstructor(); - Assert.assertEquals(1, bigsubCons.size()); + assertEquals(1, bigsubCons.size()); assertNoOverlap(bigsuperCons, bigsubCons); List bigall = bigCompany.getPropertyClosureForFullConstructor(); assertNoDuplicates(bigall); - Assert.assertEquals(4, bigall.size()); + assertEquals(4, bigall.size()); PersistentClass classMapping = metadata.getEntityBinding("Person"); POJOClass person = c2j.getPOJOClass(classMapping); List propertiesForMinimalConstructor = person.getPropertiesForMinimalConstructor(); - Assert.assertEquals(2,propertiesForMinimalConstructor.size()); - Assert.assertFalse(propertiesForMinimalConstructor.contains(classMapping.getIdentifierProperty())); + assertEquals(2,propertiesForMinimalConstructor.size()); + assertFalse(propertiesForMinimalConstructor.contains(classMapping.getIdentifierProperty())); List propertiesForFullConstructor = person.getPropertiesForFullConstructor(); - Assert.assertEquals(2,propertiesForFullConstructor.size()); - Assert.assertFalse(propertiesForFullConstructor.contains(classMapping.getIdentifierProperty())); + assertEquals(2,propertiesForFullConstructor.size()); + assertFalse(propertiesForFullConstructor.contains(classMapping.getIdentifierProperty())); } @Test @@ -128,22 +147,22 @@ public void testMinimal() { metadata.getEntityBinding("BrandProduct"), new Cfg2JavaTool()); List propertiesForMinimalConstructor = bp.getPropertiesForMinimalConstructor(); - Assert.assertEquals(1,propertiesForMinimalConstructor.size()); + assertEquals(1,propertiesForMinimalConstructor.size()); List propertiesForFullConstructor = bp.getPropertiesForFullConstructor(); - Assert.assertEquals(2, propertiesForFullConstructor.size()); + assertEquals(2, propertiesForFullConstructor.size()); } private void assertNoDuplicates(List bigall) { Set set = new HashSet(); set.addAll(bigall); - Assert.assertEquals("list had duplicates!",set.size(),bigall.size()); + assertEquals(set.size(),bigall.size(), "list had duplicates!"); } private void assertNoOverlap(List first, List second) { Set set = new HashSet(); set.addAll(first); set.addAll(second); - Assert.assertEquals(set.size(),first.size()+second.size()); + assertEquals(set.size(),first.size()+second.size()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaDidirectionalIndexedCollectionMappingTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaDidirectionalIndexedCollectionMappingTest/TestCase.java index ccea98c70f..8fa5a9d9cd 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaDidirectionalIndexedCollectionMappingTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaDidirectionalIndexedCollectionMappingTest/TestCase.java @@ -1,20 +1,36 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaDidirectionalIndexedCollectionMappingTest; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.hbm2x.Exporter; import org.hibernate.tool.hbm2x.POJOExporter; import org.hibernate.tools.test.util.HibernateUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -26,30 +42,30 @@ public class TestCase { "GenericModel.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); } @Test public void testReflection() throws Exception { - Assert.assertTrue(new File(outputDir, "GenericObject.java").exists()); - Assert.assertTrue(new File(outputDir, "GenericValue.java").exists()); + assertTrue(new File(srcDir, "GenericObject.java").exists()); + assertTrue(new File(srcDir, "GenericValue.java").exists()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TestCase.java index b836db861d..cb9b387eae 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaEjb3Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -25,11 +46,9 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -44,27 +63,27 @@ public class TestCase { "Passenger.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private File outputDir = null; + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; private File resourcesDir = null; private Metadata metadata = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); metadata = metadataDescriptor.createMetadata(); - FileUtil.generateNoopComparator(outputDir); + FileUtil.generateNoopComparator(srcDir); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.setTemplatePath(new String[0]); exporter.getProperties().setProperty("ejb3", "true"); exporter.getProperties().setProperty("jdk5", "true"); @@ -74,41 +93,41 @@ public void setUp() throws Exception { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/Author.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/Article.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/Train.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/Passenger.java") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TransportationPk.java") ); } @Test public void testBasicComponent() { - Assert.assertEquals( + assertEquals( "@Embeddable", FileUtil.findFirstString( "@Embeddable", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/TransportationPk.java"))); } @Test public void testCompile() { - File compiled = new File(temporaryFolder.getRoot(), "compiled"); + File compiled = new File(outputFolder, "compiled"); compiled.mkdir(); List jars = new ArrayList(); jars.add(JavaUtil.resolvePathToJarFileFor(Persistence.class)); // for jpa api jars.add(JavaUtil.resolvePathToJarFileFor(Version.class)); // for hibernate core - JavaUtil.compile(outputDir, compiled, jars); + JavaUtil.compile(srcDir, compiled, jars); JUnitUtil.assertIsNonEmptyFile(new File( compiled, "comparator/NoopComparator.class") ); @@ -133,10 +152,10 @@ public void testCompile() { public void testEqualsHashCode() { PersistentClass classMapping = metadata.getEntityBinding("org.hibernate.tool.hbm2x.Hbm2JavaEjb3Test.Passenger"); POJOClass clazz = new Cfg2JavaTool().getPOJOClass(classMapping); - Assert.assertFalse(clazz.needsEqualsHashCode()); + assertFalse(clazz.needsEqualsHashCode()); classMapping = metadata.getEntityBinding("org.hibernate.tool.hbm2x.Hbm2JavaEjb3Test.Article"); clazz = new Cfg2JavaTool().getPOJOClass(classMapping); - Assert.assertTrue(clazz.needsEqualsHashCode()); + assertTrue(clazz.needsEqualsHashCode()); } @Test @@ -146,30 +165,30 @@ public void testAnnotationColumnDefaults() { POJOClass clazz = cfg2java.getPOJOClass(classMapping); Property p = classMapping.getProperty("content"); String string = clazz.generateAnnColumnAnnotation( p ); - Assert.assertNotNull(string); - Assert.assertEquals(-1, string.indexOf("unique=")); - Assert.assertTrue(string.indexOf("nullable=")>=0); - Assert.assertEquals(-1, string.indexOf("insertable=")); - Assert.assertEquals(-1, string.indexOf("updatable=")); - Assert.assertTrue(string.indexOf("length=10000")>0); + assertNotNull(string); + assertEquals(-1, string.indexOf("unique=")); + assertTrue(string.indexOf("nullable=")>=0); + assertEquals(-1, string.indexOf("insertable=")); + assertEquals(-1, string.indexOf("updatable=")); + assertTrue(string.indexOf("length=10000")>0); p = classMapping.getProperty("name"); string = clazz.generateAnnColumnAnnotation( p ); - Assert.assertNotNull(string); - Assert.assertEquals(-1, string.indexOf("unique=")); - Assert.assertTrue(string.indexOf("nullable=")>=0); - Assert.assertEquals(-1, string.indexOf("insertable=")); - Assert.assertTrue(string.indexOf("updatable=false")>0); - Assert.assertTrue(string.indexOf("length=100")>0); + assertNotNull(string); + assertEquals(-1, string.indexOf("unique=")); + assertTrue(string.indexOf("nullable=")>=0); + assertEquals(-1, string.indexOf("insertable=")); + assertTrue(string.indexOf("updatable=false")>0); + assertTrue(string.indexOf("length=100")>0); classMapping = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaEjb3Test.Train" ); clazz = cfg2java.getPOJOClass(classMapping); p = classMapping.getProperty( "name" ); string = clazz.generateAnnColumnAnnotation( p ); - Assert.assertNotNull(string); - Assert.assertTrue(string.indexOf("unique=true")>0); - Assert.assertTrue(string.indexOf("nullable=")>=0); - Assert.assertEquals(-1, string.indexOf("insertable=")); - Assert.assertEquals(-1,string.indexOf("updatable=")); - Assert.assertEquals(-1, string.indexOf("length=")); + assertNotNull(string); + assertTrue(string.indexOf("unique=true")>0); + assertTrue(string.indexOf("nullable=")>=0); + assertEquals(-1, string.indexOf("insertable=")); + assertEquals(-1,string.indexOf("updatable=")); + assertEquals(-1, string.indexOf("length=")); } @Test @@ -178,36 +197,36 @@ public void testEmptyCascade() { Cfg2JavaTool cfg2java = new Cfg2JavaTool(); EntityPOJOClass clazz = (EntityPOJOClass) cfg2java.getPOJOClass(classMapping); Property property = classMapping.getProperty( "author" ); - Assert.assertEquals(0, clazz.getCascadeTypes( property ).length); - Assert.assertEquals( + assertEquals(0, clazz.getCascadeTypes( property ).length); + assertEquals( null, FileUtil.findFirstString( "cascade={}", new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEjb3Test/Article.java") )); } @Test public void testAnnotationBuilder() { AnnotationBuilder builder = AnnotationBuilder.createAnnotation("SingleCleared").resetAnnotation( "Single" ); - Assert.assertEquals("@Single", builder.getResult()); + assertEquals("@Single", builder.getResult()); builder = AnnotationBuilder.createAnnotation("javax.persistence.OneToMany") .addAttribute("willbecleared", (String)null) .resetAnnotation("javax.persistence.OneToMany") .addAttribute("cascade", new String[] { "val1", "val2"}) .addAttribute("fetch", "singleValue"); - Assert.assertEquals("@javax.persistence.OneToMany(cascade={val1, val2}, fetch=singleValue)", builder.getResult()); + assertEquals("@javax.persistence.OneToMany(cascade={val1, val2}, fetch=singleValue)", builder.getResult()); builder = AnnotationBuilder.createAnnotation("javax.persistence.OneToMany"); builder.addAttribute("cascade", (String[])null); builder.addAttribute("fetch", (String)null); - Assert.assertEquals("@javax.persistence.OneToMany", builder.getResult()); + assertEquals("@javax.persistence.OneToMany", builder.getResult()); builder = AnnotationBuilder.createAnnotation("abc"); ArrayList list = new ArrayList(); list.add(new Integer(42)); list.add( new String("xxx") ); builder.addQuotedAttributes( "it", list.iterator() ); - Assert.assertEquals("@abc(it={\"42\", \"xxx\"})", builder.getResult()); + assertEquals("@abc(it={\"42\", \"xxx\"})", builder.getResult()); List columns = new ArrayList(); columns.add("first"); columns.add("second"); @@ -219,8 +238,8 @@ public String transform(String object) { }); constraint.addAttribute( "single", "value" ); String attribute = constraint.getAttributeAsString("columnNames"); - Assert.assertEquals("{\"first\", \"second\"}", attribute); - Assert.assertEquals("value", constraint.getAttributeAsString( "single" )); + assertEquals("{\"first\", \"second\"}", attribute); + assertEquals("value", constraint.getAttributeAsString( "single" )); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEqualsTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEqualsTest/TestCase.java index feb3618a99..9ba4dbf4d1 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEqualsTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaEqualsTest/TestCase.java @@ -1,5 +1,28 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaEqualsTest; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.FileWriter; import java.lang.reflect.InvocationHandler; @@ -16,11 +39,9 @@ import org.hibernate.tool.hbm2x.POJOExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { @@ -44,18 +65,18 @@ public class TestCase { " int getId(); "+ System.lineSeparator() + "} "; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { // create output folder - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); // export class ProxiedTestEntity.java and UnProxiedTestEntity File hbmXml = new File(resourcesDir, "testEntity.hbm.xml"); @@ -64,25 +85,26 @@ public void setUp() throws Exception { fileWriter.close(); Properties properties = new Properties(); properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, new File[] { hbmXml }, properties); Exporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.start(); // copy interface EntityProxy.java - File file = new File(outputDir, "org/hibernate/tool/hbm2x/Hbm2JavaEquals/TestEntityProxy.java"); + File file = new File(srcDir, "org/hibernate/tool/hbm2x/Hbm2JavaEquals/TestEntityProxy.java"); FileWriter writer = new FileWriter(file); writer.write(TEST_ENTITY_PROXY_JAVA); writer.close(); // compile the source files - JavaUtil.compile(outputDir); + JavaUtil.compile(srcDir); } @Test public void testEqualsWithoutProxy() throws Exception { // load the entity class and lookup the setId method - URL[] urls = new URL[] { outputDir.toURI().toURL() }; + URL[] urls = new URL[] { srcDir.toURI().toURL() }; ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader ucl = new URLClassLoader(urls, oldLoader ); Class entityClass = ucl.loadClass("org.hibernate.tool.hbm2x.Hbm2JavaEquals.UnProxiedTestEntity"); @@ -94,20 +116,20 @@ public void testEqualsWithoutProxy() throws Exception { // - 'false' when comparing against an object of a different class Object firstEntity = entityClass.newInstance(); setId.invoke(firstEntity, new Object[] { Integer.MAX_VALUE }); - Assert.assertTrue(firstEntity.equals(firstEntity)); - Assert.assertFalse(firstEntity.equals(null)); - Assert.assertFalse(firstEntity.equals(new Object())); + assertTrue(firstEntity.equals(firstEntity)); + assertFalse(firstEntity.equals(null)); + assertFalse(firstEntity.equals(new Object())); // create a second entity and check the 'normal behavior // - 'true' if the id property is the same // - 'false' if the id property is different Object secondEntity = entityClass.newInstance(); setId.invoke(secondEntity, new Object[] { Integer.MAX_VALUE }); - Assert.assertTrue(firstEntity.equals(secondEntity)); - Assert.assertTrue(secondEntity.equals(firstEntity)); + assertTrue(firstEntity.equals(secondEntity)); + assertTrue(secondEntity.equals(firstEntity)); setId.invoke(secondEntity, new Object[] { Integer.MIN_VALUE }); - Assert.assertFalse(firstEntity.equals(secondEntity)); - Assert.assertFalse(secondEntity.equals(firstEntity)); + assertFalse(firstEntity.equals(secondEntity)); + assertFalse(secondEntity.equals(firstEntity)); ucl.close(); } @@ -116,7 +138,7 @@ public void testEqualsWithoutProxy() throws Exception { public void testEqualsWithProxy() throws Exception { // load the entity and proxy classes, lookup the setId method and create a proxy object - URL[] urls = new URL[] { outputDir.toURI().toURL() }; + URL[] urls = new URL[] { srcDir.toURI().toURL() }; ClassLoader oldLoader = Thread.currentThread().getContextClassLoader(); URLClassLoader ucl = new URLClassLoader(urls, oldLoader ); Class entityClass = ucl.loadClass("org.hibernate.tool.hbm2x.Hbm2JavaEquals.ProxiedTestEntity"); @@ -134,28 +156,28 @@ public void testEqualsWithProxy() throws Exception { // - 'false' when comparing against an object of a different class (that is not the proxy class) Object firstEntity = entityClass.newInstance(); setId.invoke(firstEntity, new Object[] { Integer.MAX_VALUE }); - Assert.assertTrue(firstEntity.equals(firstEntity)); - Assert.assertFalse(firstEntity.equals(null)); - Assert.assertFalse(firstEntity.equals(new Object())); + assertTrue(firstEntity.equals(firstEntity)); + assertFalse(firstEntity.equals(null)); + assertFalse(firstEntity.equals(new Object())); // create a second proxied entity and check the 'normal behavior // - 'true' if the id property is the same // - 'false' if the id property is different Object secondEntity = entityClass.newInstance(); setId.invoke(secondEntity, new Object[] { Integer.MAX_VALUE }); - Assert.assertTrue(firstEntity.equals(secondEntity)); - Assert.assertTrue(secondEntity.equals(firstEntity)); + assertTrue(firstEntity.equals(secondEntity)); + assertTrue(secondEntity.equals(firstEntity)); setId.invoke(secondEntity, new Object[] { Integer.MIN_VALUE }); - Assert.assertFalse(firstEntity.equals(secondEntity)); - Assert.assertFalse(secondEntity.equals(firstEntity)); + assertFalse(firstEntity.equals(secondEntity)); + assertFalse(secondEntity.equals(firstEntity)); // compare both proxied entities with the proxy handler.id = Integer.MAX_VALUE; - Assert.assertTrue(firstEntity.equals(testEntityProxy)); - Assert.assertFalse(secondEntity.equals(testEntityProxy)); + assertTrue(firstEntity.equals(testEntityProxy)); + assertFalse(secondEntity.equals(testEntityProxy)); handler.id = Integer.MIN_VALUE; - Assert.assertFalse(firstEntity.equals(testEntityProxy)); - Assert.assertTrue(secondEntity.equals(testEntityProxy)); + assertFalse(firstEntity.equals(testEntityProxy)); + assertTrue(secondEntity.equals(testEntityProxy)); ucl.close(); } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaInitializationTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaInitializationTest/TestCase.java index 596661a580..cbca11ca2b 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaInitializationTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaInitializationTest/TestCase.java @@ -1,9 +1,31 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaInitializationTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; + import org.hibernate.boot.Metadata; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; @@ -11,11 +33,9 @@ import org.hibernate.tool.hbm2x.pojo.ImportContextImpl; import org.hibernate.tool.hbm2x.pojo.POJOClass; import org.hibernate.tools.test.util.HibernateUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -30,18 +50,18 @@ public class TestCase { "Passenger.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + private Metadata metadata = null; - @Before + @BeforeEach public void setUp() throws Exception { metadata = HibernateUtil .initializeMetadataDescriptor( this, HBM_XML_FILES, - temporaryFolder.getRoot()) + outputFolder) .createMetadata(); } @@ -51,47 +71,47 @@ public void testFieldInitializationAndTypeNames() { Cfg2JavaTool cfg2java = new Cfg2JavaTool(); POJOClass clazz = cfg2java.getPOJOClass(classMapping); Property p = classMapping.getProperty("AMap"); - Assert.assertEquals("all types should be fully qualified when no importcontext","java.util.Map",cfg2java.getJavaTypeName(p, true)); - Assert.assertEquals("Map",cfg2java.getJavaTypeName(p, true, clazz)); - Assert.assertEquals("new HashMap(0)", clazz.getFieldInitialization(p, true)); - Assert.assertEquals("new HashMap(0)", clazz.getFieldInitialization(p, false)); + assertEquals("java.util.Map",cfg2java.getJavaTypeName(p, true), "all types should be fully qualified when no importcontext"); + assertEquals("Map",cfg2java.getJavaTypeName(p, true, clazz)); + assertEquals("new HashMap(0)", clazz.getFieldInitialization(p, true)); + assertEquals("new HashMap(0)", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("aList"); - Assert.assertEquals("lists should not have the index visible in the declaration", "List
",cfg2java.getJavaTypeName(p, true, clazz)); - Assert.assertEquals("all types should be fully qualified when no importcontext","java.util.List",cfg2java.getJavaTypeName(p, true)); - Assert.assertEquals("new ArrayList
(0)", clazz.getFieldInitialization(p, true)); - Assert.assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); + assertEquals("List
",cfg2java.getJavaTypeName(p, true, clazz), "lists should not have the index visible in the declaration"); + assertEquals("java.util.List",cfg2java.getJavaTypeName(p, true), "all types should be fully qualified when no importcontext"); + assertEquals("new ArrayList
(0)", clazz.getFieldInitialization(p, true)); + assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("content"); - Assert.assertEquals("\"what can I say\"",clazz.getFieldInitialization(p, false)); + assertEquals("\"what can I say\"",clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("bagarticles"); - Assert.assertEquals("Should be a list via property-type", "java.util.List", cfg2java.getJavaTypeName( p, false )); - Assert.assertEquals("Should be a a generic'd list when generics=true", "java.util.List", cfg2java.getJavaTypeName( p, true )); - Assert.assertEquals("List
",cfg2java.getJavaTypeName(p, true, clazz)); - Assert.assertEquals("new ArrayList
(0)", clazz.getFieldInitialization(p, true)); - Assert.assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); + assertEquals("java.util.List", cfg2java.getJavaTypeName( p, false ), "Should be a list via property-type"); + assertEquals("java.util.List", cfg2java.getJavaTypeName( p, true ), "Should be a a generic'd list when generics=true"); + assertEquals("List
",cfg2java.getJavaTypeName(p, true, clazz)); + assertEquals("new ArrayList
(0)", clazz.getFieldInitialization(p, true)); + assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("bagstrings"); - Assert.assertEquals("Bag's are just a collection", "java.util.Collection", cfg2java.getJavaTypeName( p, false )); - Assert.assertEquals("Should be a a generic'd collection when generics=true", "java.util.Collection", cfg2java.getJavaTypeName( p, true )); - Assert.assertEquals("Collection",cfg2java.getJavaTypeName(p, true, clazz)); - Assert.assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, true)); - Assert.assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); + assertEquals("java.util.Collection", cfg2java.getJavaTypeName( p, false ), "Bag's are just a collection"); + assertEquals("java.util.Collection", cfg2java.getJavaTypeName( p, true ), "Should be a a generic'd collection when generics=true"); + assertEquals("Collection",cfg2java.getJavaTypeName(p, true, clazz)); + assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, true)); + assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("bagstrings"); - Assert.assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); + assertEquals("new ArrayList(0)", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("naturalSortedArticlesMap"); - Assert.assertEquals("java.util.SortedMap", cfg2java.getJavaTypeName( p, false)); - Assert.assertEquals("SortedMap", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); - Assert.assertEquals("new TreeMap()", clazz.getFieldInitialization(p, true)); - Assert.assertEquals("new TreeMap()", clazz.getFieldInitialization(p, false)); + assertEquals("java.util.SortedMap", cfg2java.getJavaTypeName( p, false)); + assertEquals("SortedMap", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); + assertEquals("new TreeMap()", clazz.getFieldInitialization(p, true)); + assertEquals("new TreeMap()", clazz.getFieldInitialization(p, false)); p = classMapping.getProperty("sortedArticlesMap"); - Assert.assertEquals("java.util.SortedMap", cfg2java.getJavaTypeName( p, false)); - Assert.assertEquals("SortedMap", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); - Assert.assertFalse(clazz.generateImports().contains("import comparator.NoopComparator;")); - Assert.assertEquals("new TreeMap(new NoopComparator())", clazz.getFieldInitialization(p, false)); - Assert.assertTrue(clazz.generateImports().contains("import comparator.NoopComparator;")); - Assert.assertEquals("new TreeMap(new NoopComparator())", clazz.getFieldInitialization(p, true)); + assertEquals("java.util.SortedMap", cfg2java.getJavaTypeName( p, false)); + assertEquals("SortedMap", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); + assertFalse(clazz.generateImports().contains("import comparator.NoopComparator;")); + assertEquals("new TreeMap(new NoopComparator())", clazz.getFieldInitialization(p, false)); + assertTrue(clazz.generateImports().contains("import comparator.NoopComparator;")); + assertEquals("new TreeMap(new NoopComparator())", clazz.getFieldInitialization(p, true)); p = classMapping.getProperty("sortedArticlesSet"); - Assert.assertEquals("java.util.SortedSet", cfg2java.getJavaTypeName( p, false)); - Assert.assertEquals("SortedSet
", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); - Assert.assertEquals("new TreeSet
(new NoopComparator())", clazz.getFieldInitialization(p, true)); + assertEquals("java.util.SortedSet", cfg2java.getJavaTypeName( p, false)); + assertEquals("SortedSet
", cfg2java.getJavaTypeName( p, true, new ImportContextImpl("") )); + assertEquals("new TreeSet
(new NoopComparator())", clazz.getFieldInitialization(p, true)); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/DummyDateType.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/DummyDateType.java index 43fbf89ea5..3cbb1147b5 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/DummyDateType.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/DummyDateType.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaTest; import java.io.Serializable; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/TestCase.java index c8678b4a29..d77264dcab 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/Hbm2JavaTest/TestCase.java @@ -1,9 +1,30 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.Hbm2JavaTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.file.Files; import java.util.HashMap; @@ -31,12 +52,10 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author max @@ -54,26 +73,26 @@ public class TestCase { "Passenger.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + private Metadata metadata = null; private MetadataDescriptor metadataDescriptor = null; - private File outputDir = null; + private File scDir = null; private File resourcesDir = null; private ArtifactCollector artifactCollector = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + scDir = new File(outputFolder, "output"); + scDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); metadata = metadataDescriptor.createMetadata(); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(scDir); artifactCollector = new ArtifactCollector(); exporter.setArtifactCollector(artifactCollector); exporter.start(); @@ -82,60 +101,60 @@ public void setUp() throws Exception { @Test public void testFileExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Customer.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/LineItem.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Order.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Train.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Passenger.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Product.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "generated/BaseHelloWorld.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "HelloUniverse.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/FatherComponent.java")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/ChildComponent.java")); - Assert.assertEquals(15, artifactCollector.getFileCount("java")); + assertEquals(15, artifactCollector.getFileCount("java")); } // TODO Re-enable this test: HBX-1248 - @Ignore + @Disabled @Test public void testCompilable() throws Exception { String helloWorldResourcePath = "/org/hibernate/tool/hbm2x/Hbm2JavaTest/HelloWorld.java_"; File helloWorldOrigin = new File(getClass().getResource(helloWorldResourcePath).toURI()); - File helloWorldDestination = new File(outputDir, "HelloWorld.java"); - File targetDir = new File(temporaryFolder.getRoot(), "compilerOutput" ); + File helloWorldDestination = new File(scDir, "HelloWorld.java"); + File targetDir = new File(outputFolder, "compilerOutput" ); targetDir.mkdir(); Files.copy(helloWorldOrigin.toPath(), helloWorldDestination.toPath()); - JavaUtil.compile(outputDir, targetDir); - Assert.assertTrue(new File(targetDir, "HelloWorld.class").exists()); + JavaUtil.compile(scDir, targetDir); + assertTrue(new File(targetDir, "HelloWorld.class").exists()); } // TODO Implement HBX-606 so that the following test succeeds - @Ignore + @Disabled @Test public void testParentComponentFailureExpected() { File file = new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/FatherComponent.java"); - Assert.assertEquals( + assertEquals( "test", FileUtil.findFirstString( "testParent", @@ -144,30 +163,30 @@ public void testParentComponentFailureExpected() { @Test public void testNoFreeMarkerLeftOvers() { - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Customer.java"))); - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/LineItem.java"))); - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Order.java"))); - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Product.java"))); - Assert.assertNull(FileUtil.findFirstString( + assertNull(FileUtil.findFirstString( "$", new File( - outputDir, + scDir, "org/hibernate/tool/hbm2x/Hbm2JavaTest/Address.java"))); } @@ -176,36 +195,36 @@ public void testPackageName() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass classMapping = metadata.getEntityBinding("org.hibernate.tool.hbm2x.Hbm2JavaTest.Order"); POJOClass pc = c2j.getPOJOClass(classMapping); - Assert.assertEquals( "org.hibernate.tool.hbm2x.Hbm2JavaTest", pc.getPackageName() ); - Assert.assertEquals( "package org.hibernate.tool.hbm2x.Hbm2JavaTest;", pc.getPackageDeclaration() ); - Assert.assertEquals( - "did not honor generated-class", + assertEquals( "org.hibernate.tool.hbm2x.Hbm2JavaTest", pc.getPackageName() ); + assertEquals( "package org.hibernate.tool.hbm2x.Hbm2JavaTest;", pc.getPackageDeclaration() ); + assertEquals( "package generated;", c2j.getPOJOClass(metadata.getEntityBinding("HelloWorld")) - .getPackageDeclaration()); + .getPackageDeclaration(), + "did not honor generated-class"); } // TODO Re-enable this test: HBX-1242 - @Ignore + @Disabled @Test public void testFieldNotThere() { - Assert.assertNull(FileUtil.findFirstString( - "notgenerated", + assertNull(FileUtil.findFirstString( + "notgenerated", new File( - outputDir, + scDir, "HelloUniverse.java"))); } @Test public void testJavaDoc() { Cfg2JavaTool c2j = new Cfg2JavaTool(); - Assert.assertEquals( " * test", c2j.toJavaDoc( "test", 0 ) ); - Assert.assertEquals( " * test", c2j.toJavaDoc( "test", 2 ) ); - Assert.assertEquals( " * test\n * me", c2j.toJavaDoc( "test\nme", 2 ) ); + assertEquals( " * test", c2j.toJavaDoc( "test", 0 ) ); + assertEquals( " * test", c2j.toJavaDoc( "test", 2 ) ); + assertEquals( " * test\n * me", c2j.toJavaDoc( "test\nme", 2 ) ); PersistentClass local = metadata.getEntityBinding( "HelloWorld" ); POJOClass pc = c2j.getPOJOClass(local); - Assert.assertEquals( " * Hey there", pc.getClassJavaDoc( "fallback", 0 ) ); - Assert.assertEquals( + assertEquals( " * Hey there", pc.getClassJavaDoc( "fallback", 0 ) ); + assertEquals( " * Test Field Description", pc.getFieldJavaDoc(local.getIdentifierProperty(), 0 ) ); } @@ -213,11 +232,11 @@ public void testJavaDoc() { @Test public void testExtraCode() { Cfg2JavaTool c2j = new Cfg2JavaTool(); - Assert.assertFalse(c2j.hasMetaAttribute( + assertFalse(c2j.hasMetaAttribute( metadata.getEntityBinding("HelloWorld" ), "class-code" ) ); PersistentClass classMapping = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); - Assert.assertEquals( + assertEquals( "// extra code line 1\n// extra code line 2\n{ Collator.getInstance(); }", c2j.getPOJOClass(classMapping).getExtraClassCode() ); } @@ -227,8 +246,8 @@ public void testScope() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); - Assert.assertEquals( "public strictfp", c2j.getClassModifiers( pc ) ); - Assert.assertEquals("public", c2j.getClassModifiers(metadata.getEntityBinding( "HelloWorld" ) ) ); + assertEquals( "public strictfp", c2j.getClassModifiers( pc ) ); + assertEquals("public", c2j.getClassModifiers(metadata.getEntityBinding( "HelloWorld" ) ) ); } @Test @@ -236,8 +255,8 @@ public void testDeclarationType() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); - Assert.assertEquals( "class", c2j.getPOJOClass(pc).getDeclarationType() ); - Assert.assertEquals( "interface", c2j.getPOJOClass(metadata.getEntityBinding( "HelloWorld" ) ).getDeclarationType() ); + assertEquals( "class", c2j.getPOJOClass(pc).getDeclarationType() ); + assertEquals( "interface", c2j.getPOJOClass(metadata.getEntityBinding( "HelloWorld" ) ).getDeclarationType() ); } @Test @@ -246,7 +265,7 @@ public void testTypeName() { PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); Property property = pc.getProperty( "lineItems" ); - Assert.assertEquals( "java.util.Collection", c2j.getJavaTypeName( property, false ) ); + assertEquals( "java.util.Collection", c2j.getJavaTypeName( property, false ) ); } @Test @@ -255,34 +274,34 @@ public void testUseRawTypeNullability() { PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Product" ); Property property = pc.getProperty( "numberAvailable" ); - Assert.assertFalse( property.getValue().isNullable() ); - Assert.assertEquals( - "typename should be used when rawtypemode", + assertFalse( property.getValue().isNullable() ); + assertEquals( "int", - c2j.getJavaTypeName( property, false ) ); + c2j.getJavaTypeName( property, false ), + "typename should be used when rawtypemode"); property = pc.getProperty( "minStock" ); - Assert.assertTrue( property.getValue().isNullable() ); - Assert.assertEquals( - "typename should be used when rawtypemode", + assertTrue( property.getValue().isNullable() ); + assertEquals( "long", - c2j.getJavaTypeName( property, false ) ); + c2j.getJavaTypeName( property, false ), + "typename should be used when rawtypemode"); property = pc.getProperty( "otherStock" ); - Assert.assertFalse( property.getValue().isNullable() ); - Assert.assertEquals( - "type should still be overriden by meta attribute", + assertFalse( property.getValue().isNullable() ); + assertEquals( "java.lang.Integer", - c2j.getJavaTypeName( property, false ) ); + c2j.getJavaTypeName( property, false ), + "type should still be overriden by meta attribute"); property = pc.getIdentifierProperty(); - Assert.assertFalse( property.getValue().isNullable() ); - Assert.assertEquals( - "wrappers should be used by default", + assertFalse( property.getValue().isNullable() ); + assertEquals( "long", - c2j.getJavaTypeName( property, false ) ); + c2j.getJavaTypeName( property, false ), + "wrappers should be used by default"); pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer" ); Component identifier = (Component) pc.getIdentifier(); - Assert.assertFalse(((Property) identifier.getPropertyIterator().next() ) + assertFalse(((Property) identifier.getPropertyIterator().next() ) .getValue().isNullable() ); - Assert.assertEquals( "long", c2j.getJavaTypeName( property, false ) ); + assertEquals( "long", c2j.getJavaTypeName( property, false ) ); } @Test @@ -290,22 +309,22 @@ public void testExtendsImplements() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); - Assert.assertEquals( null, c2j.getPOJOClass(pc).getExtends() ); + assertEquals( null, c2j.getPOJOClass(pc).getExtends() ); POJOClass entityPOJOClass = c2j.getPOJOClass(metadata.getEntityBinding("HelloWorld" )); - Assert.assertEquals( "Comparable", entityPOJOClass.getExtends() ); - Assert.assertNull( - "should be interface which cannot have implements", - entityPOJOClass.getImplements() ); - Assert.assertEquals( - "should be interface which cannot have implements", + assertEquals( "Comparable", entityPOJOClass.getExtends() ); + assertNull( + entityPOJOClass.getImplements(), + "should be interface which cannot have implements"); + assertEquals( "", - entityPOJOClass.getImplementsDeclaration() ); + entityPOJOClass.getImplementsDeclaration(), + "should be interface which cannot have implements"); PersistentClass base = new RootClass(null); base.setClassName( "Base" ); PersistentClass sub = new SingleTableSubclass( base, null ); sub.setClassName( "Sub" ); - Assert.assertEquals( null, c2j.getPOJOClass(base).getExtends() ); - Assert.assertEquals( "Base", c2j.getPOJOClass(sub).getExtends() ); + assertEquals( null, c2j.getPOJOClass(base).getExtends() ); + assertEquals( "Base", c2j.getPOJOClass(sub).getExtends() ); Map m = new HashMap(); MetaAttribute attribute = new MetaAttribute( "extends" ); attribute.addValue( "x" ); @@ -315,13 +334,13 @@ public void testExtendsImplements() { attribute.addValue( "true" ); m.put( attribute.getName(), attribute ); sub.setMetaAttributes( m ); - Assert.assertEquals( "Base,x,y", c2j.getPOJOClass(sub).getExtends() ); + assertEquals( "Base,x,y", c2j.getPOJOClass(sub).getExtends() ); m = new HashMap(); attribute = new MetaAttribute( "implements" ); attribute.addValue( "intf" ); m.put( attribute.getName(), attribute ); base.setMetaAttributes( m ); - Assert.assertEquals( "intf,java.io.Serializable", c2j.getPOJOClass(base).getImplements() ); + assertEquals( "intf,java.io.Serializable", c2j.getPOJOClass(base).getImplements() ); } @Test @@ -331,9 +350,9 @@ public void testDeclarationName() { "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); PersistentClass hw = metadata.getEntityBinding( "HelloWorld" ); POJOClass epc = c2j.getPOJOClass(pc); - Assert.assertEquals( "Order", epc.getDeclarationName() ); + assertEquals( "Order", epc.getDeclarationName() ); epc = c2j.getPOJOClass(hw); - Assert.assertEquals( "BaseHelloWorld", epc.getDeclarationName() ); + assertEquals( "BaseHelloWorld", epc.getDeclarationName() ); } @Test @@ -341,11 +360,11 @@ public void testAsArguments() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); - Assert.assertEquals( + assertEquals( "java.util.Calendar orderDate, java.math.BigDecimal total, org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer customer, java.util.Collection lineItems", c2j.asParameterList( pc.getPropertyIterator(), false, new NoopImportContext() )); - Assert.assertEquals( + assertEquals( "orderDate, total, customer, lineItems", c2j.asArgumentList( pc.getPropertyIterator() ) ); } @@ -356,13 +375,13 @@ public void testPropertiesForFullConstructor() { PersistentClass pc = metadata.getEntityBinding( "HelloWorld" ); POJOClass pjc = c2j.getPOJOClass(pc); List wl = pjc.getPropertiesForFullConstructor(); - Assert.assertEquals( 3, wl.size() ); + assertEquals( 3, wl.size() ); PersistentClass uni = metadata.getEntityBinding( "HelloUniverse" ); pjc = c2j.getPOJOClass(uni); List local = pjc.getPropertyClosureForFullConstructor(); - Assert.assertEquals( 6, local.size() ); + assertEquals( 6, local.size() ); for(int i=0;i iter = pjc.getToStringPropertiesIterator(); // in HelloWorld.hbm.xml there're 2 Properties for toString - Assert.assertEquals( "id", (iter.next() ).getName() ); - Assert.assertEquals( "hello", (iter.next() ).getName() ); - Assert.assertFalse( iter.hasNext() ); + assertEquals( "id", (iter.next() ).getName() ); + assertEquals( "hello", (iter.next() ).getName() ); + assertFalse( iter.hasNext() ); pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Order" ); pjc = c2j.getPOJOClass(pc); - Assert.assertFalse( pjc.needsToString() ); + assertFalse( pjc.needsToString() ); pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer" ); Component c = (Component) pc.getProperty( "addressComponent" ) .getValue(); POJOClass cc = c2j.getPOJOClass(c); - Assert.assertTrue( cc.needsToString() ); + assertTrue( cc.needsToString() ); iter = cc.getToStringPropertiesIterator(); // in Customer.hbm.xml there's 1 Property for toString - Assert.assertEquals( "city", (iter.next() ).getName() ); - Assert.assertFalse( iter.hasNext() ); + assertEquals( "city", (iter.next() ).getName() ); + assertFalse( iter.hasNext() ); } @Test public void testImportOfSameName() { ImportContext ic = new ImportContextImpl("foobar"); - Assert.assertEquals("CascadeType", ic.importType("javax.persistence.CascadeType")); - Assert.assertEquals("org.hibernate.annotations.CascadeType", ic.importType("org.hibernate.annotations.CascadeType")); - Assert.assertTrue("The hibernate annotation should not be imported to avoid name clashes", ic.generateImports().indexOf("hibernate")<0); + assertEquals("CascadeType", ic.importType("javax.persistence.CascadeType")); + assertEquals("org.hibernate.annotations.CascadeType", ic.importType("org.hibernate.annotations.CascadeType")); + assertTrue(ic.generateImports().indexOf("hibernate")<0, "The hibernate annotation should not be imported to avoid name clashes"); } @Test public void testImporter() { ImportContext context = new ImportContextImpl( "org.hibernate" ); - Assert.assertEquals("byte", context.importType("byte")); - Assert.assertEquals("Session", context.importType("org.hibernate.Session")); - Assert.assertEquals("Long", context.importType("java.lang.Long")); - Assert.assertEquals("org.test.Session", context.importType("org.test.Session")); - Assert.assertEquals("Entity", context.importType("org.test.Entity")); - Assert.assertEquals("org.other.test.Entity", context.importType("org.other.test.Entity")); - Assert.assertEquals("Collection", context.importType("java.util.Collection")); - Assert.assertEquals("Map", context.importType("java.util.Map")); - Assert.assertEquals("Collection[]", context.importType("java.util.Collection[]")); - Assert.assertEquals("Map", context.importType("java.util.Map")); + assertEquals("byte", context.importType("byte")); + assertEquals("Session", context.importType("org.hibernate.Session")); + assertEquals("Long", context.importType("java.lang.Long")); + assertEquals("org.test.Session", context.importType("org.test.Session")); + assertEquals("Entity", context.importType("org.test.Entity")); + assertEquals("org.other.test.Entity", context.importType("org.other.test.Entity")); + assertEquals("Collection", context.importType("java.util.Collection")); + assertEquals("Map", context.importType("java.util.Map")); + assertEquals("Collection[]", context.importType("java.util.Collection[]")); + assertEquals("Map", context.importType("java.util.Map")); String string = context.generateImports(); - Assert.assertTrue(string.indexOf("import org.hibernate.Session;")<0); - Assert.assertTrue(string.indexOf("import org.test.Entity;")>0); - Assert.assertTrue("Entity can only be imported once", string.indexOf("import org.other.test.Entity;")<0); - Assert.assertFalse(string.indexOf("<")>=0); - Assert.assertEquals("Outer.Entity", context.importType("org.test.Outer$Entity")); - Assert.assertEquals("org.other.test.Outer.Entity", context.importType("org.other.test.Outer$Entity")); - Assert.assertEquals("Collection", context.importType("java.util.Collection")); - Assert.assertEquals("Map", context.importType("java.util.Map")); - Assert.assertEquals("Collection[]", context.importType("java.util.Collection[]")); - Assert.assertEquals("Map", context.importType("java.util.Map")); + assertTrue(string.indexOf("import org.hibernate.Session;")<0); + assertTrue(string.indexOf("import org.test.Entity;")>0); + assertTrue(string.indexOf("import org.other.test.Entity;")<0, "Entity can only be imported once"); + assertFalse(string.indexOf("<")>=0); + assertEquals("Outer.Entity", context.importType("org.test.Outer$Entity")); + assertEquals("org.other.test.Outer.Entity", context.importType("org.other.test.Outer$Entity")); + assertEquals("Collection", context.importType("java.util.Collection")); + assertEquals("Map", context.importType("java.util.Map")); + assertEquals("Collection[]", context.importType("java.util.Collection[]")); + assertEquals("Map", context.importType("java.util.Map")); //assertEquals("Test.Entry", context.importType("org.hibernate.Test.Entry")); what should be the behavior for this ? - Assert.assertEquals("Test.Entry", context.importType("org.hibernate.Test$Entry")); - Assert.assertEquals("Map.Entry", context.importType("java.util.Map$Entry")); - Assert.assertEquals("Entry", context.importType("java.util.Map.Entry")); // we can't detect that it is the same class here unless we try an load all strings so we fall back to default class name. - Assert.assertEquals("List", context.importType( "java.util.List" )); - Assert.assertEquals("List", context.importType( "java.util.List" )); + assertEquals("Test.Entry", context.importType("org.hibernate.Test$Entry")); + assertEquals("Map.Entry", context.importType("java.util.Map$Entry")); + assertEquals("Entry", context.importType("java.util.Map.Entry")); // we can't detect that it is the same class here unless we try an load all strings so we fall back to default class name. + assertEquals("List", context.importType( "java.util.List" )); + assertEquals("List", context.importType( "java.util.List" )); string = context.generateImports(); - Assert.assertTrue(string.indexOf("import java.util.Map")>=0); - Assert.assertTrue(string.indexOf("import java.utilMap$")<0); - Assert.assertTrue(string.indexOf("$")<0); + assertTrue(string.indexOf("import java.util.Map")>=0); + assertTrue(string.indexOf("import java.utilMap$")<0); + assertTrue(string.indexOf("$")<0); } @Test @@ -440,20 +459,20 @@ public void testEqualsHashCode() { Cfg2JavaTool c2j = new Cfg2JavaTool(); PersistentClass pc = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer" ); POJOClass pjc = c2j.getPOJOClass((Component) pc.getProperty("addressComponent").getValue()); - Assert.assertTrue( pjc.needsEqualsHashCode() ); + assertTrue( pjc.needsEqualsHashCode() ); Iterator iter = pjc.getEqualsHashCodePropertiesIterator(); // in HelloWorld.hbm.xml there're 2 Properties for toString - Assert.assertEquals( "streetAddress1", iter.next().getName() ); - Assert.assertEquals( "city", iter.next().getName() ); - Assert.assertEquals( "verified", iter.next().getName() ); - Assert.assertFalse( iter.hasNext() ); + assertEquals( "streetAddress1", iter.next().getName() ); + assertEquals( "city", iter.next().getName() ); + assertEquals( "verified", iter.next().getName() ); + assertFalse( iter.hasNext() ); } // TODO Re-enable this test: HBX-1249 - @Ignore + @Disabled @Test public void testGenerics() throws Exception { - File genericsSource = new File(temporaryFolder.getRoot(), "genericssource"); + File genericsSource = new File(outputFolder, "genericssource"); POJOExporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(genericsSource); @@ -461,23 +480,23 @@ public void testGenerics() throws Exception { exporter.setArtifactCollector(artifactCollector); exporter.getProperties().setProperty("jdk5", "true"); exporter.start(); - File genericsTarget = new File(temporaryFolder.getRoot(), "genericstarget" ); + File genericsTarget = new File(outputFolder, "genericstarget" ); genericsTarget.mkdir(); String helloWorldResourcePath = "/org/hibernate/tool/hbm2x/Hbm2JavaTest/HelloWorld.java_"; File helloWorldOrigin = new File(getClass().getResource(helloWorldResourcePath).toURI()); - File helloWorldDestination = new File(outputDir, "HelloWorld.java"); + File helloWorldDestination = new File(scDir, "HelloWorld.java"); Files.copy(helloWorldOrigin.toPath(), helloWorldDestination.toPath()); JavaUtil.compile(genericsSource, genericsTarget); - Assert.assertTrue(new File(genericsTarget, "HelloWorld.class").exists()); + assertTrue(new File(genericsTarget, "HelloWorld.class").exists()); } - @Ignore + @Disabled @Test public void testDynamicComponent() { PersistentClass classMapping = metadata.getEntityBinding( "org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer"); - Assert.assertEquals( + assertEquals( "java.util.Map", new Cfg2JavaTool().getJavaTypeName( classMapping.getProperty("dynaMap"), false)); @@ -485,17 +504,17 @@ public void testDynamicComponent() { @Test public void testCapitializaiton() { - Assert.assertEquals("Mail", BasicPOJOClass.beanCapitalize("Mail")); - Assert.assertEquals("Mail", BasicPOJOClass.beanCapitalize("mail")); - Assert.assertEquals("eMail", BasicPOJOClass.beanCapitalize("eMail")); - Assert.assertEquals("EMail", BasicPOJOClass.beanCapitalize("EMail")); + assertEquals("Mail", BasicPOJOClass.beanCapitalize("Mail")); + assertEquals("Mail", BasicPOJOClass.beanCapitalize("mail")); + assertEquals("eMail", BasicPOJOClass.beanCapitalize("eMail")); + assertEquals("EMail", BasicPOJOClass.beanCapitalize("EMail")); } @Test public void testUserTypes() { PersistentClass classMapping = metadata.getEntityBinding("org.hibernate.tool.hbm2x.Hbm2JavaTest.Customer"); Property property = classMapping.getProperty("customDate"); - Assert.assertEquals("java.sql.Date", new Cfg2JavaTool().getJavaTypeName(property, false)); + assertEquals("java.sql.Date", new Cfg2JavaTool().getJavaTypeName(property, false)); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HibernateMappingExporterTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HibernateMappingExporterTest/TestCase.java index 5eb9a55ed6..fcddd3a60e 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HibernateMappingExporterTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/HibernateMappingExporterTest/TestCase.java @@ -1,17 +1,39 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.HibernateMappingExporterTest; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.FileWriter; import java.util.Properties; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class TestCase { @@ -24,31 +46,32 @@ public class TestCase { " "+ " "; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + @Test public void testStart() throws Exception { - File resources = new File(temporaryFolder.getRoot(), "resources"); + File resources = new File(outputFolder, "resources"); resources.mkdir(); File fooHbmXmlOrigin = new File(resources, "origin.hbm.xml"); FileWriter writer = new FileWriter(fooHbmXmlOrigin); writer.write(FOO_HBM_XML); writer.close(); Properties properties = new Properties(); - properties.setProperty("hibernate.dialect", HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, new File[] { fooHbmXmlOrigin }, properties); - final File outputDir = new File(temporaryFolder.getRoot(), "output"); + final File outputDir = new File(outputFolder, "output"); outputDir.mkdir(); HibernateMappingExporter exporter = new HibernateMappingExporter(); exporter.setMetadataDescriptor(metadataDescriptor); exporter.setOutputDirectory(outputDir); final File fooHbmXml = new File(outputDir, "Foo.hbm.xml"); - Assert.assertFalse(fooHbmXml.exists()); + assertFalse(fooHbmXml.exists()); exporter.start(); - Assert.assertTrue(fooHbmXml.exists()); - Assert.assertTrue(fooHbmXml.delete()); + assertTrue(fooHbmXml.exists()); + assertTrue(fooHbmXml.delete()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/OtherCfg2HbmTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/OtherCfg2HbmTest/TestCase.java index 169a5991a1..dc28ef4e67 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/OtherCfg2HbmTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/OtherCfg2HbmTest/TestCase.java @@ -1,20 +1,38 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.OtherCfg2HbmTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.boot.Metadata; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -23,11 +41,11 @@ import org.hibernate.tools.test.util.FileUtil; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; /** * @author max @@ -43,69 +61,70 @@ public class TestCase { "HelloWorld.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - private File outputDir = null; + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testFileExistence() { - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/Order.hbm.xml") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "org/hibernate/tool/hbm2x/Product.hbm.xml") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "HelloWorld.hbm.xml") ); - JUnitUtil.assertIsNonEmptyFile(new File(outputDir, "HelloUniverse.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "org/hibernate/tool/hbm2x/Order.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "org/hibernate/tool/hbm2x/Product.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "HelloWorld.hbm.xml") ); + JUnitUtil.assertIsNonEmptyFile(new File(srcDir, "HelloUniverse.hbm.xml") ); } @Test public void testReadable() { - StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); - ssrb.applySetting(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); Properties properties = new Properties(); properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); File[] hbmFiles = new File[4]; - hbmFiles[0] = new File(outputDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml"); - hbmFiles[1] = new File(outputDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml"); - hbmFiles[2] = new File(outputDir, "org/hibernate/tool/hbm2x/Order.hbm.xml"); - hbmFiles[3] = new File(outputDir, "org/hibernate/tool/hbm2x/Product.hbm.xml"); + hbmFiles[0] = new File(srcDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml"); + hbmFiles[1] = new File(srcDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml"); + hbmFiles[2] = new File(srcDir, "org/hibernate/tool/hbm2x/Order.hbm.xml"); + hbmFiles[3] = new File(srcDir, "org/hibernate/tool/hbm2x/Product.hbm.xml"); Metadata metadata = MetadataDescriptorFactory .createNativeDescriptor(null, hbmFiles, properties) .createMetadata(); - Assert.assertNotNull(metadata); + assertNotNull(metadata); } @Test public void testNoVelocityLeftOvers() { - Assert.assertEquals(null, FileUtil.findFirstString("$",new File(outputDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml") ) ); - Assert.assertEquals(null, FileUtil.findFirstString("$",new File(outputDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml") ) ); - Assert.assertEquals(null, FileUtil.findFirstString("$",new File(outputDir, "org/hibernate/tool/hbm2x/Order.hbm.xml") ) ); - Assert.assertEquals(null, FileUtil.findFirstString("$",new File(outputDir, "org/hibernate/tool/hbm2x/Product.hbm.xml") ) ); + assertEquals(null, FileUtil.findFirstString("$",new File(srcDir, "org/hibernate/tool/hbm2x/Customer.hbm.xml") ) ); + assertEquals(null, FileUtil.findFirstString("$",new File(srcDir, "org/hibernate/tool/hbm2x/LineItem.hbm.xml") ) ); + assertEquals(null, FileUtil.findFirstString("$",new File(srcDir, "org/hibernate/tool/hbm2x/Order.hbm.xml") ) ); + assertEquals(null, FileUtil.findFirstString("$",new File(srcDir, "org/hibernate/tool/hbm2x/Product.hbm.xml") ) ); } @Test - public void testVersioning() throws DocumentException { - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(new File(outputDir, "org/hibernate/tool/hbm2x/Product.hbm.xml")); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/version"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one version element", 1, list.size()); + public void testVersioning() throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(new File(srcDir, "org/hibernate/tool/hbm2x/Product.hbm.xml")); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/version") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one version element"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/PropertiesTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/PropertiesTest/TestCase.java index d5e099b816..f1a3ca2ed9 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/PropertiesTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/PropertiesTest/TestCase.java @@ -1,19 +1,39 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.PropertiesTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.nio.file.Files; -import java.util.List; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.hbm2x.ArtifactCollector; import org.hibernate.tool.hbm2x.Exporter; @@ -23,11 +43,12 @@ import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Josh Moore josh.moore@gmx.de @@ -39,29 +60,29 @@ public class TestCase { "Properties.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + private ArtifactCollector artifactCollector; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { artifactCollector = new ArtifactCollector(); - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter exporter = new POJOExporter(); exporter.setMetadataDescriptor(metadataDescriptor); - exporter.setOutputDirectory(outputDir); + exporter.setOutputDirectory(srcDir); exporter.setArtifactCollector(artifactCollector); Exporter hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.setArtifactCollector(artifactCollector); exporter.start(); hbmexporter.start(); @@ -69,50 +90,47 @@ public void setUp() throws Exception { @Test public void testNoGenerationOfEmbeddedPropertiesComponent() { - Assert.assertEquals(2, artifactCollector.getFileCount("java")); - Assert.assertEquals(2, artifactCollector.getFileCount("hbm.xml")); + assertEquals(2, artifactCollector.getFileCount("java")); + assertEquals(2, artifactCollector.getFileCount("hbm.xml")); } @Test - public void testGenerationOfEmbeddedProperties() { - File outputXml = new File(outputDir, "properties/PPerson.hbm.xml"); + public void testGenerationOfEmbeddedProperties() throws Exception { + File outputXml = new File(srcDir, "properties/PPerson.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document; - try { - document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/properties"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one properties element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"emergencyContact"); - Assert.assertNotNull( - FileUtil.findFirstString( - "name", - new File(outputDir, "properties/PPerson.java" ))); - Assert.assertNull( - "Embedded component/properties should not show up in .java", - FileUtil.findFirstString( - "emergencyContact", - new File(outputDir, "properties/PPerson.java" ))); - } catch (DocumentException e) { - Assert.fail("Can't parse file " + outputXml.getAbsolutePath()); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/properties") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one properties element"); + Element element = (Element) nodeList.item(0); + assertEquals(element.getAttribute( "name" ),"emergencyContact"); + assertNotNull( + FileUtil.findFirstString( + "name", + new File(srcDir, "properties/PPerson.java" ))); + assertNull( + FileUtil.findFirstString( + "emergencyContact", + new File(srcDir, "properties/PPerson.java" )), + "Embedded component/properties should not show up in .java"); } @Test public void testCompilable() throws Exception { String propertiesUsageResourcePath = "/org/hibernate/tool/hbm2x/PropertiesTest/PropertiesUsage.java_"; File propertiesUsageOrigin = new File(getClass().getResource(propertiesUsageResourcePath).toURI()); - File propertiesUsageDestination = new File(outputDir, "properties/PropertiesUsage.java"); - File targetDir = new File(temporaryFolder.getRoot(), "compilerOutput" ); + File propertiesUsageDestination = new File(srcDir, "properties/PropertiesUsage.java"); + File targetDir = new File(outputFolder, "compilerOutput" ); targetDir.mkdir(); Files.copy(propertiesUsageOrigin.toPath(), propertiesUsageDestination.toPath()); - JavaUtil.compile(outputDir, targetDir); - Assert.assertTrue(new File(targetDir, "properties/PCompany.class").exists()); - Assert.assertTrue(new File(targetDir, "properties/PPerson.class").exists()); - Assert.assertTrue(new File(targetDir, "properties/PropertiesUsage.class").exists()); + JavaUtil.compile(srcDir, targetDir); + assertTrue(new File(targetDir, "properties/PCompany.class").exists()); + assertTrue(new File(targetDir, "properties/PPerson.class").exists()); + assertTrue(new File(targetDir, "properties/PropertiesUsage.class").exists()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.java index dd1e0c6aaa..d43ef2c004 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.AbstractTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.java index 77d943fb06..2f15f4db35 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.AbstractTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/TestCase.java index 0e29910da7..e32f31494b 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/TestCase.java @@ -1,32 +1,38 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.AbstractTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -34,11 +40,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -50,71 +57,71 @@ public class TestCase { "Car.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.hbm.xml") ); } @Test - public void testAbstractPresent() { + public void testAbstractPresent() throws Exception { File outputXml = new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document; - try { - document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one class element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertNotNull("Abstract attrinute was not exported.", node.attribute( "abstract" )); - Assert.assertEquals(node.attribute( "abstract" ).getText(),"true"); - } catch (DocumentException e) { - Assert.fail("Can't parse file " + outputXml.getAbsolutePath()); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one class element"); + Element node = (Element)nodeList.item(0); + assertNotNull(node.getAttribute("abstract"), "Abstract attrinute was not exported."); + assertEquals(node.getAttribute("abstract"), "true"); } + @Test public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/Car.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/AbstractTest/CarPart.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.java index c22d13fa09..f1c6f414df 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.BackrefTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.java index 5a06a40539..a6fe612a49 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.BackrefTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/TestCase.java index 5ea48cfd51..9c3b4039c3 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/TestCase.java @@ -1,21 +1,28 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.BackrefTest; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.ArrayList; import java.util.Iterator; @@ -31,11 +38,9 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author Dmitry Geraskov @@ -47,36 +52,36 @@ public class TestCase { "Car.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private Metadata metadata = null; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "src"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); metadata = metadataDescriptor.createMetadata(); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.hbm.xml") ); } @@ -88,23 +93,24 @@ public void testBackrefPresent() { while (iterator.hasNext() && !hasBackrefs) { hasBackrefs = (iterator.next() instanceof Backref); } - Assert.assertTrue("Class mapping should create Backref for this testcase", hasBackrefs); + assertTrue(hasBackrefs, "Class mapping should create Backref for this testcase"); } @Test public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/Car.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/BackrefTest/CarPart.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmToolTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmToolTest/TestCase.java index 9ee4abc683..7590a36832 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmToolTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Cfg2HbmToolTest/TestCase.java @@ -1,6 +1,28 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.Cfg2HbmToolTest; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.hibernate.mapping.JoinedSubclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.RootClass; @@ -8,8 +30,7 @@ import org.hibernate.mapping.Subclass; import org.hibernate.mapping.UnionSubclass; import org.hibernate.tool.hbm2x.Cfg2HbmTool; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author Dmitry Geraskov @@ -21,11 +42,11 @@ public class TestCase { public void testNeedsTable(){ Cfg2HbmTool c2h = new Cfg2HbmTool(); PersistentClass pc = new RootClass(null); - Assert.assertTrue(c2h.needsTable(pc)); - Assert.assertTrue(c2h.needsTable(new JoinedSubclass(pc, null))); - Assert.assertTrue(c2h.needsTable(new UnionSubclass(pc, null))); - Assert.assertFalse(c2h.needsTable(new SingleTableSubclass(pc, null))); - Assert.assertFalse(c2h.needsTable(new Subclass(pc, null))); + assertTrue(c2h.needsTable(pc)); + assertTrue(c2h.needsTable(new JoinedSubclass(pc, null))); + assertTrue(c2h.needsTable(new UnionSubclass(pc, null))); + assertFalse(c2h.needsTable(new SingleTableSubclass(pc, null))); + assertFalse(c2h.needsTable(new Subclass(pc, null))); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.java index 908a3491d4..e2beb80225 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.CompositeElementTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/FooComponent.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/FooComponent.java index a7f5ebfdb3..9afc590a3d 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/FooComponent.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/FooComponent.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.CompositeElementTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/GlarchProxy.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/GlarchProxy.java index e5df1fb63a..1aa9f47a72 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/GlarchProxy.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/GlarchProxy.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.CompositeElementTest; import java.util.List; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/TestCase.java index 1b6689c631..7c37acee17 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/TestCase.java @@ -1,32 +1,38 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.CompositeElementTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -34,11 +40,13 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -50,35 +58,35 @@ public class TestCase { "Glarch.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Glarch.hbm.xml") ); } @@ -86,41 +94,55 @@ public void testAllFilesExistence() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Fee.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Glarch.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testCompositeElementNode() throws DocumentException { + public void testCompositeElementNode() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/CompositeElementTest/Glarch.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/list"); - Element node = (Element) xpath.selectNodes(document).get(1); //second list - List list = node.elements("composite-element"); - Assert.assertEquals("Expected to get one composite-element element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals("Expected to get two property element", 2, node.elements("property").size()); - - node = node.element("many-to-one"); - Assert.assertEquals(node.attribute( "name" ).getText(),"fee"); - Assert.assertEquals(node.attribute( "cascade" ).getText(),"all"); - //TODO: assertEquals(node.attribute( "outer-join" ).getText(),"true"); - node = node.getParent();//composite-element - node = node.element("nested-composite-element"); - Assert.assertEquals(node.attribute( "name" ).getText(),"subcomponent"); - Assert.assertEquals(node.attribute( "class" ).getText(),"org.hibernate.tool.hbm2x.hbm2hbmxml.CompositeElementTest.FooComponent"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/list") + .evaluate(document, XPathConstants.NODESET); + Element secondList = (Element)nodeList.item(1); + NodeList compositeElementList = secondList.getElementsByTagName("composite-element"); + assertEquals(1, compositeElementList.getLength(), "Expected to get one composite-element element"); + Element compositeElement = (Element)compositeElementList.item(0); + NodeList compositeElementChildNodes = compositeElement.getChildNodes(); + int amountOfProperties = 0; + for (int i = 0; i < compositeElementChildNodes.getLength(); i++) { + Node node = compositeElementChildNodes.item(i); + if ("property".equals(node.getNodeName())) amountOfProperties++; + } + assertEquals(2, amountOfProperties, "Expected to get two property element"); + NodeList manyToOneList = secondList.getElementsByTagName("many-to-one"); + assertEquals(1, manyToOneList.getLength()); + Element manyToOneElement = (Element)manyToOneList.item(0); + assertEquals("fee", manyToOneElement.getAttribute("name")); + assertEquals("all", manyToOneElement.getAttribute("cascade")); + NodeList nestedCompositeElementList = compositeElement.getElementsByTagName("nested-composite-element"); + assertEquals(1, nestedCompositeElementList.getLength()); + Element nestedCompositeElement = (Element)nestedCompositeElementList.item(0); + assertEquals("subcomponent", nestedCompositeElement.getAttribute("name")); + assertEquals( + "org.hibernate.tool.hbm2x.hbm2hbmxml.CompositeElementTest.FooComponent", + nestedCompositeElement.getAttribute("class")); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.java index ba73297aef..3c24bd11bb 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.DynamicComponentTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/FooComponent.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/FooComponent.java index 0076010d78..8a9687b5c5 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/FooComponent.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/FooComponent.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.DynamicComponentTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/GlarchProxy.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/GlarchProxy.java index 1fac2cfe33..28bb1eb6d8 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/GlarchProxy.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/GlarchProxy.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.DynamicComponentTest; import java.util.List; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/TestCase.java index 4ab3213bf1..20f5f26bca 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/TestCase.java @@ -1,32 +1,38 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.DynamicComponentTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -34,11 +40,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -50,35 +57,35 @@ public class TestCase { "Glarch.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Glarch.hbm.xml") ); } @@ -86,46 +93,53 @@ public void testAllFilesExistence() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Fee.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Glarch.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testClassProxy() throws DocumentException { + public void testClassProxy() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Glarch.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one class element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute("proxy").getText(),"org.hibernate.tool.hbm2x.hbm2hbmxml.DynamicComponentTest.GlarchProxy"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one class element"); + Element element = (Element) nodeList.item(0); + assertEquals(element.getAttribute("proxy"),"org.hibernate.tool.hbm2x.hbm2hbmxml.DynamicComponentTest.GlarchProxy"); } @Test - public void testDynamicComponentNode() throws DocumentException { + public void testDynamicComponentNode() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/DynamicComponentTest/Glarch.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/dynamic-component"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one dynamic-component element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"dynaBean"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/dynamic-component") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one dynamic-component element"); + Element element = (Element) nodeList.item(0); + assertEquals(element.getAttribute( "name" ),"dynaBean"); } - + } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Address.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Address.java new file mode 100644 index 0000000000..48ad11ae6a --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Address.java @@ -0,0 +1,69 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.FormulaTest; + +public class Address { + + private AddressId addressId; + private String street; + private String city; + private String state; + private String zip; + private Customer customer; + + public Customer getCustomer() { + return customer; + } + public void setCustomer(Customer customer) { + this.customer = customer; + } + + 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 getStreet() { + return street; + } + public void setStreet(String street) { + this.street = street; + } + public String getZip() { + return zip; + } + public void setZip(String zip) { + this.zip = zip; + } + public AddressId getAddressId() { + return addressId; + } + public void setAddressId(AddressId addressId) { + this.addressId = addressId; + } +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/AddressId.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/AddressId.java new file mode 100644 index 0000000000..f7efc64057 --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/AddressId.java @@ -0,0 +1,59 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.FormulaTest; + +public class AddressId { + private String type; + private String addressId; + + public AddressId(String type, String customerId) { + this.addressId = customerId; + this.type = type; + } + + public AddressId() {} + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getAddressId() { + return addressId; + } + public void setAddressId(String customerId) { + this.addressId = customerId; + } + public boolean equals(Object other) { + if ( !(other instanceof AddressId) ) return false; + AddressId add = (AddressId) other; + return type.equals(add.type) && addressId.equals(add.addressId); + } + public int hashCode() { + return addressId.hashCode() + type.hashCode(); + } + + public String toString() { + return type + '#' + addressId; + } + +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Customer.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Customer.java new file mode 100644 index 0000000000..a7ef84bba6 --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Customer.java @@ -0,0 +1,54 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.FormulaTest; + +public class Customer { + + private String name; + private String customerId; + private Address billingAddress; + private Address shippingAddress; + + public Address getBillingAddress() { + return billingAddress; + } + public void setBillingAddress(Address billingAddress) { + this.billingAddress = billingAddress; + } + public String getCustomerId() { + return customerId; + } + public void setCustomerId(String customerId) { + this.customerId = customerId; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public Address getShippingAddress() { + return shippingAddress; + } + public void setShippingAddress(Address shippingAddress) { + this.shippingAddress = shippingAddress; + } +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/TestCase.java new file mode 100644 index 0000000000..8c53617b17 --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/TestCase.java @@ -0,0 +1,90 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.FormulaTest; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.File; +import java.util.ArrayList; +import java.util.Properties; + +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; +import org.hibernate.tool.hbm2x.Exporter; +import org.hibernate.tool.hbm2x.HibernateMappingExporter; +import org.hibernate.tools.test.util.HibernateUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * @author koen + */ +public class TestCase { + + private static final String[] HBM_XML_FILES = new String[] { + "Customer.hbm.xml" + }; + + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; + private File resourcesDir = null; + + private Exporter hbmexporter = null; + + @BeforeEach + public void setUp() throws Exception { + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); + resourcesDir.mkdir(); + MetadataDescriptor metadataDescriptor = HibernateUtil + .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); + hbmexporter = new HibernateMappingExporter(); + hbmexporter.setMetadataDescriptor(metadataDescriptor); + hbmexporter.setOutputDirectory(srcDir); + hbmexporter.start(); + } + + @Test + public void testReadable() { + ArrayList files = new ArrayList(4); + files.add(new File( + srcDir, + "/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/Customer.hbm.xml")); + files.add(new File( + srcDir, + "/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/BillingAddress.hbm.xml")); + files.add(new File( + srcDir, + "/org/hibernate/tool/hbm2x/hbm2hbmxml/FormulaTest/ShippingAddress.hbm.xml")); + Properties properties = new Properties(); + properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.setProperty(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); + MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory + .createNativeDescriptor(null, files.toArray(new File[2]), properties); + assertNotNull(metadataDescriptor.createMetadata()); + } + +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/TestCase.java index c34238f2be..5a63ae711b 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/TestCase.java @@ -1,34 +1,53 @@ -//$Id$ - -/* - * Tests for generating the HBM documents from the Configuration data structure. - * The generated XML document will be validated and queried to make sure the - * basic structure is correct in each test. +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; -import java.util.List; -import org.dom4j.Attribute; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.Node; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.hbm2x.Exporter; import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tool.hbm2x.HibernateMappingGlobalSettings; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; /** * Initial implentation based on the Hbm2XTest class. @@ -57,53 +76,53 @@ public static class Persister { "ClassFullAttribute.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private MetadataDescriptor metadataDescriptor = null; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml") ); - Assert.assertFalse(new File( - outputDir, + assertFalse(new File( + srcDir, "org/hibernate/tool/cfg2hbm/GeneralHbmSettings.hbm.xml").exists() ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicCompositeId.hbm.xml") ); } @Test public void testArtifactCollection() { - Assert.assertEquals( - "4 mappings + 1 global", + assertEquals( 5, - hbmexporter.getArtifactCollector().getFileCount("hbm.xml")); + hbmexporter.getArtifactCollector().getFileCount("hbm.xml"), + "4 mappings + 1 global"); } /** @@ -118,22 +137,22 @@ public void testGlobalSettingsGeneratedDatabase() throws Exception { hgs.setCatalogName("mycatalog"); Exporter gsExporter = new HibernateMappingExporter(); gsExporter.setMetadataDescriptor(metadataDescriptor); - gsExporter.setOutputDirectory(outputDir); + gsExporter.setOutputDirectory(srcDir); ( (HibernateMappingExporter)gsExporter).setGlobalSettings(hgs); gsExporter.start(); File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - Element root = document.getRootElement(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + Element root = document.getDocumentElement(); // There are 7 attributes because there are defaults defined by the DTD makes up the missing entries - Assert.assertEquals("Unexpected number of hibernate-mapping elements ", 7, root.attributeCount() ); - Assert.assertEquals("Unexpected package name", "org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.attribute("package").getStringValue() ); - Assert.assertEquals("Unexpected schema name", "myschema", root.attribute("schema").getStringValue() ); - Assert.assertEquals("Unexpected mycatalog name", "mycatalog", root.attribute("catalog").getStringValue() ); + assertEquals(7, root.getAttributes().getLength(), "Unexpected number of hibernate-mapping elements "); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.getAttribute("package"), "Unexpected package name"); + assertEquals("myschema", root.getAttribute("schema"), "Unexpected schema name"); + assertEquals("mycatalog", root.getAttribute("catalog"), "Unexpected mycatalog name"); } /** @@ -148,107 +167,120 @@ public void testGlobalSettingsGeneratedAccessAndCascadeNonDefault() throws Exce hgs.setDefaultCascade("save-update"); Exporter gbsExporter = new HibernateMappingExporter(); gbsExporter.setMetadataDescriptor(metadataDescriptor); - gbsExporter.setOutputDirectory(outputDir); + gbsExporter.setOutputDirectory(srcDir); ( (HibernateMappingExporter)gbsExporter).setGlobalSettings(hgs); gbsExporter.start(); File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - Element root = document.getRootElement(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + Element root = document.getDocumentElement(); // There are 5 attributes because there are non-defaults not set for this test - Assert.assertEquals("Unexpected number of hibernate-mapping elements ", 5, root.attributeCount() ); - Assert.assertEquals("Unexpected package name", "org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.attribute("package").getStringValue() ); - Assert.assertEquals("Unexpected access setting", "field", root.attribute("default-access").getStringValue() ); - Assert.assertEquals("Unexpected cascade setting", "save-update", root.attribute("default-cascade").getStringValue() ); + assertEquals(5, root.getAttributes().getLength(), "Unexpected number of hibernate-mapping elements "); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.getAttribute("package"), "Unexpected package name"); + assertEquals("field", root.getAttribute("default-access"), "Unexpected access setting"); + assertEquals("save-update", root.getAttribute("default-cascade"), "Unexpected cascade setting"); } @Test - public void testMetaAttributes() throws DocumentException { + public void testMetaAttributes() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/meta"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one meta element", 2, list.size()); - Node node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"Basic"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/id/meta"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one meta element", 1, list.size()); - node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"basicId"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/property/meta"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one meta element", 1, list.size()); - node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"description"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set/meta"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one meta element", 1, list.size()); - node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"anotherone"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/meta") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get one meta element"); + Node node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"Basic"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/id/meta") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one meta element"); + node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"basicId"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/property/meta") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one meta element"); + node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"description"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set/meta") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one meta element"); + node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"anotherone"); } @Test - public void testCollectionAttributes() throws DocumentException { + public void testCollectionAttributes() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one set element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals("delete, update", node.attributeValue("cascade")); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one set element"); + Element node = (Element) nodeList.item(0); + assertEquals("delete, update", node.getAttribute("cascade")); } @Test - public void testComments() throws DocumentException { + public void testComments() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/ClassFullAttribute.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/comment"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one comment element", 1, list.size()); - Node node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"A comment for ClassFullAttribute"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/property/column/comment"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one comment element", 1, list.size()); - node = (Node) list.get(0); - Assert.assertEquals(node.getText(),"columnd comment"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/comment") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one comment element"); + Node node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"A comment for ClassFullAttribute"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/property/column/comment") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one comment element"); + node = (Node) nodeList.item(0); + assertEquals(node.getTextContent(),"columnd comment"); } @Test - public void testNoComments() throws DocumentException { + public void testNoComments() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/comment"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get no comment element", list.size(), 0); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/property/column/comment"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get no comment element", 0, list.size()); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/comment") + .evaluate(document, XPathConstants.NODESET); + assertEquals(nodeList.getLength(), 0, "Expected to get no comment element"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/property/column/comment") + .evaluate(document, XPathConstants.NODESET); + assertEquals(0, nodeList.getLength(), "Expected to get no comment element"); } /** @@ -264,22 +296,22 @@ public void testGlobalSettingsGeneratedAccessAndCascadeDefault() throws Excepti hgs.setDefaultCascade("none"); Exporter gbsExporter = new HibernateMappingExporter(); gbsExporter.setMetadataDescriptor(metadataDescriptor); - gbsExporter.setOutputDirectory(outputDir); + gbsExporter.setOutputDirectory(srcDir); ( (HibernateMappingExporter)gbsExporter).setGlobalSettings(hgs); gbsExporter.start(); File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - Element root = document.getRootElement(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + Element root = document.getDocumentElement(); // There are 5 attributes because there are non-defaults not set for this test - Assert.assertEquals("Unexpected number of hibernate-mapping elements ", 5, root.attributeCount() ); - Assert.assertEquals("Unexpected package name", "org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.attribute("package").getStringValue() ); - Assert.assertEquals("Unexpected access setting", "property", root.attribute("default-access").getStringValue() ); - Assert.assertEquals("Unexpected cascade setting", "none", root.attribute("default-cascade").getStringValue() ); + assertEquals(5, root.getAttributes().getLength(), "Unexpected number of hibernate-mapping elements "); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.getAttribute("package"), "Unexpected package name"); + assertEquals("property", root.getAttribute("default-access"), "Unexpected access setting"); + assertEquals("none", root.getAttribute("default-cascade"), "Unexpected cascade setting"); } /** @@ -295,257 +327,280 @@ public void testGlobalSettingsLasyAndAutoImportNonDefault() throws Exception { hgs.setAutoImport(false); Exporter gbsExporter = new HibernateMappingExporter(); gbsExporter.setMetadataDescriptor(metadataDescriptor); - gbsExporter.setOutputDirectory(outputDir); + gbsExporter.setOutputDirectory(srcDir); ( (HibernateMappingExporter)gbsExporter).setGlobalSettings(hgs); gbsExporter.start(); File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - Element root = document.getRootElement(); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + Element root = document.getDocumentElement(); // There are 5 attributes because there are non-defaults not set for this test - Assert.assertEquals("Unexpected number of hibernate-mapping elements ", 5, root.attributeCount() ); - Assert.assertEquals("Unexpected package name", "org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.attribute("package").getStringValue() ); - Assert.assertEquals("Unexpected access setting", "false", root.attribute("default-lazy").getStringValue() ); - Assert.assertEquals("Unexpected cascade setting", "false", root.attribute("auto-import").getStringValue() ); + assertEquals(5, root.getAttributes().getLength(), "Unexpected number of hibernate-mapping elements "); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest", root.getAttribute("package"), "Unexpected package name"); + assertEquals("false", root.getAttribute("default-lazy"), "Unexpected access setting"); + assertEquals("false", root.getAttribute("auto-import"), "Unexpected cascade setting"); } @Test public void testIdGeneratorHasNotArgumentParameters() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicGlobals.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and it has no arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/id/generator"); - List list = xpath.selectNodes(document); - Assert.assertTrue("Expected to get one generator element", list.size() == 1); - Attribute genAtt = ( (Element)list.get(0) ).attribute("class"); - Assert.assertEquals("Unexpected generator class name", "assigned", genAtt.getStringValue() ); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/id/generator/param"); - list = xpath.selectNodes(document); - Assert.assertTrue("Expected to get no generator param elements", list.size() == 0); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/id/generator") + .evaluate(document, XPathConstants.NODESET); + assertTrue(nodeList.getLength() == 1, "Expected to get one generator element"); + Node genAtt = ( (Element)nodeList.item(0)).getAttributeNode("class"); + assertEquals("assigned", genAtt.getTextContent(), "Unexpected generator class name"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/id/generator/param") + .evaluate(document, XPathConstants.NODESET); + assertTrue(nodeList.getLength() == 0, "Expected to get no generator param elements"); } @Test public void testIdGeneratorHasArgumentParameters() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/id/generator"); - List list = xpath.selectNodes(document); - Assert.assertTrue("Expected to get one generator element", list.size() == 1); - Attribute genAtt = ( (Element)list.get(0) ).attribute("class"); - Assert.assertEquals("Unexpected generator class name", "org.hibernate.id.TableHiLoGenerator", genAtt.getStringValue() ); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/id/generator/param"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get correct number of generator param elements", 2, list.size() ); - Element tableElement = (Element)list.get(0); - Attribute paramTableAtt = tableElement.attribute("name"); - Element columnElement = (Element)list.get(1); - Attribute paramColumnAtt = columnElement.attribute("name"); - if(paramTableAtt.getStringValue().equals("column")) { + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/id/generator") + .evaluate(document, XPathConstants.NODESET); + assertTrue(nodeList.getLength() == 1, "Expected to get one generator element"); + Node genAtt = ( (Element)nodeList.item(0)).getAttributeNode("class"); + assertEquals("org.hibernate.id.TableHiLoGenerator", genAtt.getTextContent(), "Unexpected generator class name"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/id/generator/param") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get correct number of generator param elements"); + Element tableElement = (Element)nodeList.item(0); + Attr paramTableAtt = tableElement.getAttributeNode("name"); + Element columnElement = (Element)nodeList.item(1); + Attr paramColumnAtt = columnElement.getAttributeNode("name"); + if(paramTableAtt.getTextContent().equals("column")) { // to make sure the order of the elements doesn't matter. Element tempElement = tableElement; - Attribute temp = paramTableAtt; + Attr temp = paramTableAtt; paramTableAtt = paramColumnAtt; tableElement = columnElement; paramColumnAtt = temp; columnElement = tempElement; } - Assert.assertEquals("Unexpected generator param name", "table", paramTableAtt.getStringValue() ); - Assert.assertEquals("Unexpected generator param name", "column", paramColumnAtt.getStringValue() ); - Assert.assertEquals("Unexpected param value for table", "uni_table", tableElement.getStringValue() ); - Assert.assertEquals("Unexpected param value for column", "next_hi_value", columnElement.getStringValue() ); + assertEquals("table", paramTableAtt.getTextContent(), "Unexpected generator param name"); + assertEquals("column", paramColumnAtt.getTextContent(), "Unexpected generator param name"); + assertEquals("uni_table", tableElement.getTextContent(), "Unexpected param value for table"); + assertEquals("next_hi_value", columnElement.getTextContent(), "Unexpected param value for column"); } @Test public void testGeneralHbmSettingsQuery() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/query"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get correct number of query elements", 2, list.size() ); - Attribute genAtt = ( (Element)list.get(0) ).attribute("name"); - Assert.assertEquals("Unexpected query name", "test_query_1", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(0) ).attribute("flush-mode"); - Assert.assertNull("Expected flush-mode value to be null", genAtt); - genAtt = ( (Element)list.get(1) ).attribute("name"); - Assert.assertEquals("Unexpected query name", "test_query_2", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(1) ).attribute("flush-mode"); - Assert.assertEquals("Unexpected flush-mode value", "auto", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(1) ).attribute("cacheable"); - Assert.assertEquals("Unexpected cacheable value", "true", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(1) ).attribute("cache-region"); - Assert.assertEquals("Unexpected cache-region value", "myregion", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(1) ).attribute("fetch-size"); - Assert.assertEquals("Unexpected fetch-size value", "10", genAtt.getStringValue() ); - genAtt = ( (Element)list.get(1) ).attribute("timeout"); - Assert.assertEquals("Unexpected timeout value", "1000", genAtt.getStringValue() ); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/query") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get correct number of query elements"); + Attr genAtt = ( (Element)nodeList.item(0) ).getAttributeNode("name"); + assertEquals("test_query_1", genAtt.getTextContent(), "Unexpected query name"); + genAtt = ( (Element)nodeList.item(0) ).getAttributeNode("flush-mode"); + assertNull(genAtt, "Expected flush-mode value to be null"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("name"); + assertEquals("test_query_2", genAtt.getTextContent(), "Unexpected query name"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("flush-mode"); + assertEquals("auto", genAtt.getTextContent(), "Unexpected flush-mode value"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("cacheable"); + assertEquals("true", genAtt.getTextContent(), "Unexpected cacheable value"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("cache-region"); + assertEquals("myregion", genAtt.getTextContent(), "Unexpected cache-region value"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("fetch-size"); + assertEquals("10", genAtt.getTextContent(), "Unexpected fetch-size value"); + genAtt = ( (Element)nodeList.item(1) ).getAttributeNode("timeout"); + assertEquals("1000", genAtt.getTextContent(), "Unexpected timeout value"); } @Test public void testGeneralHbmSettingsSQLQueryBasic() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get correct number of query elements", 6, list.size() ); - xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_1\"]"); - list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_1' not to be null", node); - Attribute genAtt = node.attribute("flush-mode"); - Assert.assertNull("Expected flush-mode value to be null", genAtt); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query") + .evaluate(document, XPathConstants.NODESET); + assertEquals(6, nodeList.getLength(), "Expected to get correct number of query elements"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_1\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_1' not to be null"); + Attr genAtt = node.getAttributeNode("flush-mode"); + assertNull(genAtt, "Expected flush-mode value to be null"); } @Test public void testGeneralHbmSettingsSQLQueryAllAttributes() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_2\"]"); - List list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_2' not to be null", node); - Attribute genAtt = node.attribute("name"); - Assert.assertEquals("Unexpected query name", "test_sqlquery_2", genAtt.getStringValue() ); - genAtt = node.attribute("flush-mode"); - Assert.assertEquals("Unexpected flush-mode value", "auto", genAtt.getStringValue() ); - genAtt = node.attribute("cacheable"); - Assert.assertEquals("Unexpected cacheable value", "true", genAtt.getStringValue() ); - genAtt = node.attribute("cache-region"); - Assert.assertEquals("Unexpected cache-region value", "myregion", genAtt.getStringValue() ); - genAtt = node.attribute("fetch-size"); - Assert.assertEquals("Unexpected fetch-size value", "10", genAtt.getStringValue() ); - genAtt = node.attribute("timeout"); - Assert.assertEquals("Unexpected timeout value", "1000", genAtt.getStringValue() ); - Element syncTable = node.element("synchronize"); - Assert.assertNull("Expected synchronize element to be null", syncTable); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_2\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_2' not to be null"); + Attr genAtt = node.getAttributeNode("name"); + assertEquals("test_sqlquery_2", genAtt.getTextContent(), "Unexpected query name"); + genAtt = node.getAttributeNode("flush-mode"); + assertEquals("auto", genAtt.getTextContent(), "Unexpected flush-mode value"); + genAtt = node.getAttributeNode("cacheable"); + assertEquals("true", genAtt.getTextContent(), "Unexpected cacheable value"); + genAtt = node.getAttributeNode("cache-region"); + assertEquals("myregion", genAtt.getTextContent(), "Unexpected cache-region value"); + genAtt = node.getAttributeNode("fetch-size"); + assertEquals("10", genAtt.getTextContent(), "Unexpected fetch-size value"); + genAtt = node.getAttributeNode("timeout"); + assertEquals("1000", genAtt.getTextContent(), "Unexpected timeout value"); + Element syncTable = (Element)node.getElementsByTagName("synchronize").item(0); + assertNull(syncTable, "Expected synchronize element to be null"); } @Test public void testGeneralHbmSettingsSQLQuerySynchronize() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_3\"]"); - List list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_3' not to be null", node); - Attribute genAtt = node.attribute("name"); - Assert.assertEquals("Unexpected query name", "test_sqlquery_3", genAtt.getStringValue() ); - Element syncTable = node.element("synchronize"); - Assert.assertNotNull("Expected synchronize element to not be null", syncTable); - genAtt = syncTable.attribute("table"); - Assert.assertEquals("Unexpected table value for synchronize element", "mytable", genAtt.getStringValue() ); - Element returnEl = node.element("return"); - Assert.assertNull("Expected return element to be null", returnEl); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_3\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_3' not to be null"); + Attr genAtt = node.getAttributeNode("name"); + assertEquals("test_sqlquery_3", genAtt.getTextContent(), "Unexpected query name"); + Element syncTable = (Element)node.getElementsByTagName("synchronize").item(0); + assertNotNull(syncTable, "Expected synchronize element to not be null"); + genAtt = syncTable.getAttributeNode("table"); + assertEquals("mytable", genAtt.getTextContent(), "Unexpected table value for synchronize element"); + Element returnEl = (Element)node.getElementsByTagName("return").item(0); + assertNull(returnEl, "Expected return element to be null"); } @Test public void testGeneralHbmSettingsSQLQueryWithReturnRoot() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_4\"]"); - List list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_4' not to be null", node); - Attribute genAtt = node.attribute("name"); - Assert.assertEquals("Unexpected query name", "test_sqlquery_4", genAtt.getStringValue() ); - Element returnEl = node.element("return"); - Assert.assertNotNull("Expected return element to not be null", returnEl); - genAtt = returnEl.attribute("alias"); - Assert.assertEquals("Unexpected alias value for return element", "e", genAtt.getStringValue() ); - genAtt = returnEl.attribute("class"); - Assert.assertEquals("Unexpected class value for return element", "org.hibernate.tool.hbm2x.hbm2hbmxml.BasicGlobals", genAtt.getStringValue()); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_4\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_4' not to be null"); + Attr genAtt = node.getAttributeNode("name"); + assertEquals(genAtt.getTextContent(), "test_sqlquery_4", "Unexpected query name"); + Element returnEl = (Element)node.getElementsByTagName("return").item(0); + assertNotNull(returnEl, "Expected return element to not be null"); + genAtt = returnEl.getAttributeNode("alias"); + assertEquals("e", genAtt.getTextContent(), "Unexpected alias value for return element"); + genAtt = returnEl.getAttributeNode("class"); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.BasicGlobals", genAtt.getTextContent(), "Unexpected class value for return element"); } @Test public void testGeneralHbmSettingsSQLQueryWithReturnRole() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_5\"]"); - List list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_5' not to be null", node); - Attribute genAtt = node.attribute("name"); - Assert.assertEquals("Unexpected query name", "test_sqlquery_5", genAtt.getStringValue() ); - Element returnEl = node.element("return-join"); - Assert.assertNotNull("Expected return element to not be null", returnEl); - genAtt = returnEl.attribute("alias"); - Assert.assertEquals("Unexpected alias value for return element", "e", genAtt.getStringValue() ); - genAtt = returnEl.attribute("property"); - Assert.assertEquals("Unexpected property role value for return element", "e.age", genAtt.getStringValue()); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_5\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_5' not to be null"); + Attr genAtt = node.getAttributeNode("name"); + assertEquals("test_sqlquery_5", genAtt.getTextContent(), "Unexpected query name"); + Element returnEl = (Element)node.getElementsByTagName("return-join").item(0); + assertNotNull(returnEl, "Expected return element to not be null"); + genAtt = returnEl.getAttributeNode("alias"); + assertEquals("e", genAtt.getTextContent(), "Unexpected alias value for return element"); + genAtt = returnEl.getAttributeNode("property"); + assertEquals("e.age", genAtt.getTextContent(), "Unexpected property role value for return element"); } @Test public void testGeneralHbmSettingsSQLQueryWithReturnCollection() throws Exception { File outputXml = new File( - outputDir, + srcDir, "GeneralHbmSettings.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - Document document = xmlReader.read(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); // Validate the Generator and that it does have arguments - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/sql-query[@name=\"test_sqlquery_6\"]"); - List list = xpath.selectNodes(document); - Element node = (Element)list.get(0); - Assert.assertNotNull("Expected sql-query named 'test_sqlquery_6' not to be null", node); - Attribute genAtt = node.attribute("name"); - Assert.assertEquals("Unexpected query name", "test_sqlquery_6", genAtt.getStringValue()); - Element returnEl = node.element("load-collection"); - Assert.assertNotNull("Expected return element to not be null", returnEl); - genAtt = returnEl.attribute("alias"); - Assert.assertEquals("Unexpected alias value for return element", "e", genAtt.getStringValue()); - genAtt = returnEl.attribute("role"); - Assert.assertEquals("Unexpected collection role value for return element", "org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest.BasicGlobals.price", genAtt.getStringValue()); - genAtt = returnEl.attribute("lock-mode"); - Assert.assertEquals("Unexpected class lock-mode for return element", "none", genAtt.getStringValue()); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/sql-query[@name=\"test_sqlquery_6\"]") + .evaluate(document, XPathConstants.NODESET); + Element node = (Element)nodeList.item(0); + assertNotNull(node, "Expected sql-query named 'test_sqlquery_6' not to be null"); + Attr genAtt = node.getAttributeNode("name"); + assertEquals("test_sqlquery_6", genAtt.getTextContent(), "Unexpected query name"); + Element returnEl = (Element)node.getElementsByTagName("load-collection").item(0); + assertNotNull(returnEl, "Expected return element to not be null"); + genAtt = returnEl.getAttributeNode("alias"); + assertEquals("e", genAtt.getTextContent(), "Unexpected alias value for return element"); + genAtt = returnEl.getAttributeNode("role"); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.Hbm2HbmXmlTest.BasicGlobals.price", genAtt.getTextContent(), "Unexpected collection role value for return element"); + genAtt = returnEl.getAttributeNode("lock-mode"); + assertEquals("none", genAtt.getTextContent(), "Unexpected class lock-mode for return element"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.java index 3c2aa42d43..bc315e6bee 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.IdBagTest; public class Group { diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/TestCase.java index a895a6cd47..4353ebfa21 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/TestCase.java @@ -1,32 +1,39 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.IdBagTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -34,11 +41,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -50,44 +58,44 @@ public class TestCase { "UserGroup.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { - Assert.assertFalse(new File( - outputDir, + assertFalse(new File( + srcDir, "/GeneralHbmSettings.hbm.xml").exists()); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.hbm.xml")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.hbm.xml")); } @Test public void testArtifactCollection() { - Assert.assertEquals( + assertEquals( 2, hbmexporter.getArtifactCollector().getFileCount("hbm.xml")); } @@ -96,60 +104,60 @@ public void testArtifactCollection() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.hbm.xml")); files.add(new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/Group.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testIdBagAttributes() { + public void testIdBagAttributes() throws Exception { File outputXml = new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document; - try { - document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/idbag"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one idbag element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "table" ).getText(),"`UserGroups`"); - Assert.assertEquals(node.attribute( "name" ).getText(),"groups"); - Assert.assertEquals(node.attribute( "lazy" ).getText(),"false"); - Assert.assertEquals(node.attribute( "access" ).getText(),"field"); - } catch (DocumentException e) { - Assert.fail("Can't parse file " + outputXml.getAbsolutePath()); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/idbag") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one idbag element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "table" ),"`UserGroups`"); + assertEquals(node.getAttribute( "name" ),"groups"); + assertEquals(node.getAttribute( "lazy" ),"false"); + assertEquals(node.getAttribute( "access" ),"field"); } @Test - public void testCollectionId() throws DocumentException { + public void testCollectionId() throws Exception { File outputXml = new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.hbm.xml"); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/idbag/collection-id"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one collection-id element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "column" ).getText(),"userGroupId"); - Assert.assertEquals(node.attribute( "type" ).getText(),"long"); - list = node.elements("generator"); - Assert.assertEquals("Expected to get one generator element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "class" ).getText(),"increment"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/idbag/collection-id") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one collection-id element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "column" ),"userGroupId"); + assertEquals(node.getAttribute( "type" ),"long"); + nodeList = node.getElementsByTagName("generator"); + assertEquals(1, nodeList.getLength(), "Expected to get one generator element"); + node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "class" ),"increment"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.java index 4f603a3e5f..4047d4b10a 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/IdBagTest/User.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.IdBagTest; import java.util.ArrayList; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/TestCase.java index 9897bceca4..1051cb5375 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/TestCase.java @@ -1,23 +1,39 @@ -//$Id$ - /* - * Tests for generating the HBM documents from the Configuration data structure. - * The generated XML document will be validated and queried to make sure the - * basic structure is correct in each test. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.InheritanceTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -25,12 +41,13 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * this test should be fixed to have a proper model. currently a mix of subclass/joinedsubclass is in play. @@ -43,47 +60,47 @@ public class TestCase { "Aliens.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { - Assert.assertFalse(new File( - outputDir, + assertFalse(new File( + srcDir, "GeneralHbmSettings.hbm.xml").exists() ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Human.hbm.xml")); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Alien.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Animal.hbm.xml") ); } @Test public void testArtifactCollection() { - Assert.assertEquals( + assertEquals( 3, hbmexporter.getArtifactCollector().getFileCount("hbm.xml")); } @@ -91,56 +108,55 @@ public void testArtifactCollection() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Alien.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Human.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Animal.hbm.xml")); Properties properties = new Properties(); properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[3]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } // TODO Re-enable this test: HBX-1247 - @Ignore + @Disabled @Test - public void testComment() { + public void testComment() throws Exception { File outputXml = new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Alien.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document; - try { - document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/joined-subclass/comment"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one comment element", 1, list.size()); - } catch (DocumentException e) { - Assert.fail("Can't parse file " + outputXml.getAbsolutePath()); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/joined-subclass/comment") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one comment element"); } @Test - public void testDiscriminator() throws DocumentException { + public void testDiscriminator() throws Exception { File outputXml = new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/InheritanceTest/Animal.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/discriminator"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one discriminator element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "type" ).getText(), "string"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/discriminator") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one discriminator element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "type" ), "string"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Child.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Child.java new file mode 100644 index 0000000000..ed82ae0f91 --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Child.java @@ -0,0 +1,66 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.JoinTest; + +/** + * @author gavin + */ +public class Child { + private Long id; + private String name; + private Parent parent; + /** + * @return Returns the id. + */ + public Long getId() { + return id; + } + /** + * @param id The id to set. + */ + public void setId(Long id) { + this.id = id; + } + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + /** + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } + /** + * @return Returns the parent. + */ + public Parent getParent() { + return parent; + } + /** + * @param parent The parent to set. + */ + public void setParent(Parent parent) { + this.parent = parent; + } +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Parent.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Parent.java new file mode 100644 index 0000000000..97285a43ac --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Parent.java @@ -0,0 +1,69 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.JoinTest; + +import java.util.Collection; +import java.util.HashSet; + +/** + * @author gavin + */ +public class Parent { + private Long id; + private String name; + private Collection children = new HashSet(); + /** + * @return Returns the children. + */ + public Collection getChildren() { + return children; + } + /** + * @param children The children to set. + */ + public void setChildren(Collection children) { + this.children = children; + } + /** + * @return Returns the id. + */ + public Long getId() { + return id; + } + /** + * @param id The id to set. + */ + public void setId(Long id) { + this.id = id; + } + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + /** + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/TestCase.java new file mode 100644 index 0000000000..201d9dec1a --- /dev/null +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/TestCase.java @@ -0,0 +1,87 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.JoinTest; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.io.File; +import java.util.ArrayList; +import java.util.Properties; + +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.tool.api.metadata.MetadataDescriptor; +import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; +import org.hibernate.tool.hbm2x.Exporter; +import org.hibernate.tool.hbm2x.HibernateMappingExporter; +import org.hibernate.tools.test.util.HibernateUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * @author koen + */ +public class TestCase { + + private static final String[] HBM_XML_FILES = new String[] { + "Parent.hbm.xml" + }; + + @TempDir + public File outputFolder = new File("output"); + + private File srcDir = null; + private File resourcesDir = null; + + private Exporter hbmexporter = null; + + @BeforeEach + public void setUp() throws Exception { + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); + resourcesDir.mkdir(); + MetadataDescriptor metadataDescriptor = HibernateUtil + .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); + hbmexporter = new HibernateMappingExporter(); + hbmexporter.setMetadataDescriptor(metadataDescriptor); + hbmexporter.setOutputDirectory(srcDir); + hbmexporter.start(); + } + + @Test + public void testReadable() { + ArrayList files = new ArrayList(4); + files.add(new File( + srcDir, + "/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Parent.hbm.xml")); + files.add(new File( + srcDir, + "/org/hibernate/tool/hbm2x/hbm2hbmxml/JoinTest/Child.hbm.xml")); + Properties properties = new Properties(); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); + MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory + .createNativeDescriptor(null, files.toArray(new File[2]), properties); + assertNotNull(metadataDescriptor.createMetadata()); + } + +} diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.java index 1ca5787c4a..8b3c316e55 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ListArrayTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/FooComponent.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/FooComponent.java index d87cb38fb5..e6e6eac27f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/FooComponent.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/FooComponent.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ListArrayTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.java index 1a0635e9a7..5ef4556f91 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ListArrayTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/GlarchProxy.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/GlarchProxy.java index 17be373c87..6a7918144f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/GlarchProxy.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/GlarchProxy.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ListArrayTest; import java.util.List; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/TestCase.java index 09fdbef2f1..b48b729fdb 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/TestCase.java @@ -1,32 +1,38 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ListArrayTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -34,11 +40,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -50,33 +57,33 @@ public class TestCase { "Glarch.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml") ); } @@ -84,79 +91,89 @@ public void testAllFilesExistence() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Fee.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testListNode() throws DocumentException { + public void testListNode() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/list"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get two list element", 2, list.size()); - Element node = (Element) list.get(1); //second list - Assert.assertEquals("fooComponents", node.attribute( "name" ).getText()); - Assert.assertEquals("true", node.attribute( "lazy" ).getText()); - Assert.assertEquals("all", node.attribute( "cascade" ).getText()); - list = node.elements("list-index"); - Assert.assertEquals("Expected to get one list-index element", 1, list.size()); - list = ((Element) list.get(0)).elements("column"); - Assert.assertEquals("Expected to get one column element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals("tha_indecks", node.attribute( "name" ).getText()); - node = node.getParent().getParent();//list - list = node.elements("composite-element"); - Assert.assertEquals("Expected to get one composite-element element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals("Expected to get two property element", 2, node.elements("property").size()); - node = node.element("many-to-one"); - Assert.assertEquals("fee", node.attribute( "name" ).getText()); - Assert.assertEquals("all", node.attribute( "cascade" ).getText()); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/list") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get two list element"); + Element node = (Element) nodeList.item(1); //second list + assertEquals("fooComponents", node.getAttribute( "name" )); + assertEquals("true", node.getAttribute( "lazy" )); + assertEquals("all", node.getAttribute( "cascade" )); + nodeList = node.getElementsByTagName("list-index"); + assertEquals(1, nodeList.getLength(), "Expected to get one list-index element"); + nodeList = ((Element) nodeList.item(0)).getElementsByTagName("column"); + assertEquals(1, nodeList.getLength(), "Expected to get one column element"); + node = (Element) nodeList.item(0); + assertEquals("tha_indecks", node.getAttribute( "name" )); + node = (Element)node.getParentNode().getParentNode();//list + nodeList = node.getElementsByTagName("composite-element"); + assertEquals(1, nodeList.getLength(), "Expected to get one composite-element element"); + node = (Element) nodeList.item(0); + int propertyCount = 0; + nodeList = node.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + if ("property".equals(nodeList.item(i).getNodeName())) propertyCount++; + } + assertEquals(2, propertyCount, "Expected to get two property element"); + node = (Element)node.getElementsByTagName("many-to-one").item(0); + assertEquals("fee", node.getAttribute( "name" )); + assertEquals("all", node.getAttribute( "cascade" )); //TODO :assertEquals(node.attribute( "outer-join" ).getText(),"true"); - node = node.getParent();//composite-element - node = node.element("nested-composite-element"); - Assert.assertEquals("subcomponent", node.attribute( "name" ).getText()); - Assert.assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.ListArrayTest.FooComponent", node.attribute( "class" ).getText()); + node = (Element)node.getParentNode();//composite-element + node = (Element)node.getElementsByTagName("nested-composite-element").item(0); + assertEquals("subcomponent", node.getAttribute( "name" )); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.ListArrayTest.FooComponent", node.getAttribute( "class" )); } @Test - public void testArrayNode() throws DocumentException { + public void testArrayNode() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/array"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one array element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals("proxyArray", node.attribute( "name" ).getText()); - Assert.assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.ListArrayTest.GlarchProxy", node.attribute( "element-class" ).getText()); - list = node.elements("list-index"); - Assert.assertEquals("Expected to get one list-index element", 1, list.size()); - list = ((Element) list.get(0)).elements("column"); - Assert.assertEquals("Expected to get one column element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals("array_indecks", node.attribute( "name" ).getText()); - node = node.getParent().getParent();//array - list = node.elements("one-to-many"); - Assert.assertEquals("Expected to get one 'one-to-many' element", 1, list.size()); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/array") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one array element"); + Element node = (Element) nodeList.item(0); + assertEquals("proxyArray", node.getAttribute( "name" )); + assertEquals("org.hibernate.tool.hbm2x.hbm2hbmxml.ListArrayTest.GlarchProxy", node.getAttribute( "element-class" )); + nodeList = node.getElementsByTagName("list-index"); + assertEquals(1, nodeList.getLength(), "Expected to get one list-index element"); + nodeList = ((Element) nodeList.item(0)).getElementsByTagName("column"); + assertEquals(1, nodeList.getLength(), "Expected to get one column element"); + node = (Element) nodeList.item(0); + assertEquals("array_indecks", node.getAttribute( "name" )); + node = (Element)node.getParentNode().getParentNode();//array + nodeList = node.getElementsByTagName("one-to-many"); + assertEquals(1, nodeList.getLength(), "Expected to get one 'one-to-many' element"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.java index bdb9a052f5..83566d1098 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.java @@ -1,4 +1,23 @@ -//$Id: Group.java 7085 2005-06-08 17:59:47Z oneovthafew $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ManyToManyTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/TestCase.java index d19f6bd7eb..1b228d9418 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/TestCase.java @@ -1,23 +1,39 @@ -//$Id$ - /* - * Tests for generating the HBM documents from the Configuration data structure. - * The generated XML document will be validated and queried to make sure the - * basic structure is correct in each test. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ManyToManyTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -25,11 +41,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; public class TestCase { @@ -37,44 +54,44 @@ public class TestCase { "UserGroup.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private Exporter hbmexporter = null; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { - Assert.assertFalse(new File( - outputDir, + assertFalse(new File( + srcDir, "GeneralHbmSettings.hbm.xml") .exists() ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.hbm.xml") ); } @Test public void testArtifactCollection() { - Assert.assertEquals( + assertEquals( 2, hbmexporter.getArtifactCollector().getFileCount("hbm.xml")); } @@ -83,86 +100,92 @@ public void testArtifactCollection() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[2]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testManyToMany() throws DocumentException { + public void testManyToMany() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set/many-to-many"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one many-to-many element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "entity-name" ).getText(),"org.hibernate.tool.hbm2x.hbm2hbmxml.ManyToManyTest.Group"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one set element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "table" ).getText(),"UserGroup"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set/many-to-many") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one many-to-many element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "entity-name" ),"org.hibernate.tool.hbm2x.hbm2hbmxml.ManyToManyTest.Group"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one set element"); + node = (Element)nodeList.item(0); + assertEquals(node.getAttribute( "table" ),"UserGroup"); } @Test - public void testCompositeId() throws DocumentException { + public void testCompositeId() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.hbm.xml"); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one class element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute("table").getText(), "`Group`"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/composite-id"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one composite-id element", 1, list.size()); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/composite-id/key-property"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get two key-property elements", 2, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute("name").getText(), "name"); - node = (Element) list.get(1); - Assert.assertEquals(node.attribute("name").getText(), "org"); + JUnitUtil.assertIsNonEmptyFile(outputXml); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one class element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute("table"), "`Group`"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/composite-id") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one composite-id element"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/composite-id/key-property") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get two key-property elements"); + node = (Element) nodeList.item(0); + assertEquals(node.getAttribute("name"), "name"); + node = (Element) nodeList.item(1); + assertEquals(node.getAttribute("name"), "org"); } @Test - public void testSetAttributes() { + public void testSetAttributes() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/Group.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document; - try { - document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one set element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute("table").getText(), "UserGroup"); - Assert.assertEquals(node.attribute("name").getText(), "users"); - Assert.assertEquals(node.attribute("inverse").getText(), "true"); - Assert.assertEquals(node.attribute("lazy").getText(), "extra"); - } catch (DocumentException e) { - Assert.fail("Can't parse file " + outputXml.getAbsolutePath()); - } + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one set element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute("table"), "UserGroup"); + assertEquals(node.getAttribute("name"), "users"); + assertEquals(node.getAttribute("inverse"), "true"); + assertEquals(node.getAttribute("lazy"), "extra"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.java index d56f0b106d..a45ef84f1e 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/User.java @@ -1,4 +1,23 @@ -//$Id: User.java 7085 2005-06-08 17:59:47Z oneovthafew $ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.ManyToManyTest; import java.io.ObjectStreamClass; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Address.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Address.java index 0dfa7b3645..5f5b0b7b4f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Address.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Address.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.MapAndAnyTest; import java.util.Set; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Person.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Person.java index 65042d30ac..1bfa8b6d3b 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Person.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/Person.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.MapAndAnyTest; /** diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/TestCase.java index 537e48523e..441740e60f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/TestCase.java @@ -1,32 +1,39 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.MapAndAnyTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.ArrayList; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.boot.Metadata; import org.hibernate.cfg.AvailableSettings; import org.hibernate.mapping.Any; @@ -38,11 +45,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -55,42 +63,42 @@ public class TestCase { "Person.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private Exporter hbmexporter = null; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Metadata metadata = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); metadata = metadataDescriptor.createMetadata(); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/ComplexPropertyValue.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/IntegerPropertyValue.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/StringPropertyValue.hbm.xml") ); JUnitUtil.assertIsNonEmptyFile(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/PropertySet.hbm.xml") ); } @@ -98,111 +106,116 @@ public void testAllFilesExistence() { public void testReadable() { ArrayList files = new ArrayList(4); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/ComplexPropertyValue.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/IntegerPropertyValue.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/StringPropertyValue.hbm.xml")); files.add(new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/PropertySet.hbm.xml")); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files.toArray(new File[4]), properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testAnyNode() throws DocumentException { + public void testAnyNode() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/PropertySet.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/any"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one any element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"someSpecificProperty"); - Assert.assertEquals(node.attribute( "id-type" ).getText(),"long"); - Assert.assertEquals(node.attribute( "meta-type" ).getText(),"string"); - Assert.assertEquals(node.attribute( "cascade" ).getText(), "all"); - Assert.assertEquals(node.attribute( "access" ).getText(), "field"); - list = node.elements("column"); - Assert.assertEquals("Expected to get two column elements", 2, list.size()); - list = node.elements("meta-value"); - Assert.assertEquals("Expected to get three meta-value elements", 3, list.size()); - node = (Element) list.get(0); - String className = node.attribute( "class" ).getText(); - Assert.assertNotNull("Expected class attribute in meta-value", className); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/any") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one any element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "name" ),"someSpecificProperty"); + assertEquals(node.getAttribute( "id-type" ),"long"); + assertEquals(node.getAttribute( "meta-type" ),"string"); + assertEquals(node.getAttribute( "cascade" ), "all"); + assertEquals(node.getAttribute( "access" ), "field"); + nodeList = node.getElementsByTagName("column"); + assertEquals(2, nodeList.getLength(), "Expected to get two column elements"); + nodeList = node.getElementsByTagName("meta-value"); + assertEquals(3, nodeList.getLength(), "Expected to get three meta-value elements"); + node = (Element) nodeList.item(0); + String className = node.getAttribute( "class" ); + assertNotNull(className, "Expected class attribute in meta-value"); if (className.indexOf("IntegerPropertyValue") > 0){ - Assert.assertEquals(node.attribute( "value" ).getText(),"I"); + assertEquals(node.getAttribute( "value" ),"I"); } else if (className.indexOf("StringPropertyValue") > 0){ - Assert.assertEquals(node.attribute( "value" ).getText(),"S"); + assertEquals(node.getAttribute( "value" ),"S"); } else { - Assert.assertTrue(className.indexOf("ComplexPropertyValue") > 0); - Assert.assertEquals(node.attribute( "value" ).getText(),"C"); + assertTrue(className.indexOf("ComplexPropertyValue") > 0); + assertEquals(node.getAttribute( "value" ),"C"); } } @Test public void testMetaValueRead() throws Exception{ PersistentClass pc = metadata.getEntityBinding("org.hibernate.tool.hbm2x.hbm2hbmxml.MapAndAnyTest.Person"); - Assert.assertNotNull(pc); + assertNotNull(pc); Property prop = pc.getProperty("data"); - Assert.assertNotNull(prop); - Assert.assertTrue(prop.getValue() instanceof Any); + assertNotNull(prop); + assertTrue(prop.getValue() instanceof Any); Any any = (Any) prop.getValue(); - Assert.assertTrue("Expected to get one meta-value element", any.getMetaValues() != null); - Assert.assertEquals("Expected to get one meta-value element", 1, any.getMetaValues().size()); + assertTrue(any.getMetaValues() != null, "Expected to get one meta-value element"); + assertEquals(1, any.getMetaValues().size(), "Expected to get one meta-value element"); } @Test - public void testMapManyToAny() throws DocumentException { - File outputXml = new File(outputDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/PropertySet.hbm.xml"); + public void testMapManyToAny() throws Exception { + File outputXml = new File(srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest/PropertySet.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/map"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one any element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"generalProperties"); - Assert.assertEquals(node.attribute( "table" ).getText(),"T_GEN_PROPS"); - Assert.assertEquals(node.attribute( "lazy" ).getText(),"true"); - Assert.assertEquals(node.attribute( "cascade" ).getText(), "all"); - Assert.assertEquals(node.attribute( "access" ).getText(), "field"); - list = node.elements("key"); - Assert.assertEquals("Expected to get one key element", 1, list.size()); - list = node.elements("map-key"); - Assert.assertEquals("Expected to get one map-key element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "type" ).getText(),"string"); - list = node.elements("column"); - Assert.assertEquals("Expected to get one column element", 1, list.size()); - node = node.getParent();//map - list = node.elements("many-to-any"); - Assert.assertEquals("Expected to get one many-to-any element", 1, list.size()); - node = (Element) list.get(0); - list = node.elements("column"); - Assert.assertEquals("Expected to get two column elements", 2, list.size()); - list = node.elements("meta-value"); - Assert.assertEquals("Expected to get two meta-value elements", 2, list.size()); - node = (Element) list.get(0); - String className = node.attribute( "class" ).getText(); - Assert.assertNotNull("Expected class attribute in meta-value", className); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/map") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one any element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "name" ),"generalProperties"); + assertEquals(node.getAttribute( "table" ),"T_GEN_PROPS"); + assertEquals(node.getAttribute( "lazy" ),"true"); + assertEquals(node.getAttribute( "cascade" ), "all"); + assertEquals(node.getAttribute( "access" ), "field"); + nodeList = node.getElementsByTagName("key"); + assertEquals(1, nodeList.getLength(), "Expected to get one key element"); + nodeList = node.getElementsByTagName("map-key"); + assertEquals(1, nodeList.getLength(), "Expected to get one map-key element"); + node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "type" ),"string"); + nodeList = node.getElementsByTagName("column"); + assertEquals(1, nodeList.getLength(), "Expected to get one column element"); + node = (Element)node.getParentNode();//map + nodeList = node.getElementsByTagName("many-to-any"); + assertEquals(1, nodeList.getLength(), "Expected to get one many-to-any element"); + node = (Element) nodeList.item(0); + nodeList = node.getElementsByTagName("column"); + assertEquals(2, nodeList.getLength(), "Expected to get two column elements"); + nodeList = node.getElementsByTagName("meta-value"); + assertEquals(2, nodeList.getLength(), "Expected to get two meta-value elements"); + node = (Element) nodeList.item(0); + String className = node.getAttribute( "class" ); + assertNotNull(className, "Expected class attribute in meta-value"); if (className.indexOf("IntegerPropertyValue") > 0){ - Assert.assertEquals(node.attribute( "value" ).getText(),"I"); + assertEquals(node.getAttribute( "value" ),"I"); } else { - Assert.assertTrue(className.indexOf("StringPropertyValue") > 0); - Assert.assertEquals(node.attribute( "value" ).getText(),"S"); + assertTrue(className.indexOf("StringPropertyValue") > 0); + assertEquals(node.getAttribute( "value" ),"S"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.java index 136ec9f30f..0e973468ba 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.OneToOneTest; public class Address { diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.java index 2f24e2ca10..83fb219005 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.java @@ -1,3 +1,23 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.OneToOneTest; public class Person { diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/TestCase.java index 249238d390..925d60215f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/TestCase.java @@ -1,22 +1,38 @@ -//$Id$ - -/* - * Tests for generating the HBM documents from the Configuration data structure. - * The generated XML document will be validated and queried to make sure the - * basic structure is correct in each test. +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.OneToOneTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -24,11 +40,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; @@ -38,45 +55,45 @@ public class TestCase { "PersonAddressOneToOnePrimaryKey.hbm.xml" }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; private Exporter hbmexporter = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @Test public void testAllFilesExistence() { - Assert.assertFalse(new File( - outputDir, "GeneralHbmSettings.hbm.xml") + assertFalse(new File( + srcDir, "GeneralHbmSettings.hbm.xml") .exists()); JUnitUtil.assertIsNonEmptyFile( new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.hbm.xml")); JUnitUtil.assertIsNonEmptyFile( new File( - outputDir, + srcDir, "/org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.hbm.xml")); } @Test public void testArtifactCollection() { - Assert.assertEquals( + assertEquals( 2, hbmexporter.getArtifactCollector().getFileCount("hbm.xml")); } @@ -84,43 +101,47 @@ public void testArtifactCollection() { @Test public void testReadable() { File personHbmXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.hbm.xml"); File addressHbmXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.hbm.xml"); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); File[] files = new File[] { personHbmXml, addressHbmXml }; MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files, properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } - public void testOneToOne() throws DocumentException { - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); + public void testOneToOne() throws Exception { File xmlFile = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Person.hbm.xml"); - Document document = xmlReader.read(xmlFile); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/one-to-one"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one-to-one element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"address"); - Assert.assertEquals(node.attribute( "constrained" ).getText(),"false"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(xmlFile); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/one-to-one") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one-to-one element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "name" ),"address"); + assertEquals(node.getAttribute( "constrained" ),"false"); xmlFile = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/OneToOneTest/Address.hbm.xml"); - document = xmlReader.read(xmlFile); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/one-to-one"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one set element", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"person"); - Assert.assertEquals(node.attribute( "constrained" ).getText(),"true"); - Assert.assertEquals(node.attribute( "access" ).getText(), "field"); + document = db.parse(xmlFile); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/one-to-one") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one set element"); + node = (Element)nodeList.item(0); + assertEquals(node.getAttribute( "name" ),"person"); + assertEquals(node.getAttribute( "constrained" ),"true"); + assertEquals(node.getAttribute( "access" ), "field"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.java index c98b066c8a..86f57699eb 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.java @@ -1,4 +1,23 @@ -//$Id$ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.SetElementTest; import java.util.SortedSet; diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/TestCase.java index 04b46f381a..d8a178f62f 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/TestCase.java @@ -1,31 +1,37 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.SetElementTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.io.File; -import java.util.List; import java.util.Properties; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -33,11 +39,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -49,24 +56,24 @@ public class TestCase { "Search.hbm.xml", }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); private Exporter hbmexporter = null; - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @@ -74,70 +81,76 @@ public void setUp() throws Exception { public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile( new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.hbm.xml")); } @Test public void testReadable() { File searchHbmXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.hbm.xml"); Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); File[] files = new File[] { searchHbmXml }; MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files, properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testKey() throws DocumentException { + public void testKey() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set/key"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one key element", 1, list.size()); - Element node = (Element) list.get(0); - if (node.attribute( "column" ) != null){//implied attribute - Assert.assertEquals(node.attribute( "column" ).getText(),"searchString"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set/key") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one key element"); + Element node = (Element)nodeList.item(0); + if (node.getAttribute( "column" ) != null && !"".equals(node.getAttribute("column"))) {//implied attribute + assertEquals(node.getAttribute( "column" ),"searchString"); } else { - node = node.element("column"); - Assert.assertEquals(node.attribute( "name" ).getText(),"searchString"); + node = (Element)node.getElementsByTagName("column").item(0); + assertEquals(node.getAttribute( "name" ),"searchString"); } } @Test - public void testSetElement() throws DocumentException { + public void testSetElement() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/SetElementTest/Search.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one set element", 1, list.size()); - Element node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(),"searchResults"); - Assert.assertEquals(node.attribute( "access" ).getText(),"field"); - xpath = DocumentHelper.createXPath("//hibernate-mapping/class/set/element"); - list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one element 'element'", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "type" ).getText(), "string"); - list = node.selectNodes("column"); - Assert.assertEquals("Expected to get one element 'column'", 1, list.size()); - node = (Element) list.get(0); - Assert.assertEquals(node.attribute( "name" ).getText(), "text"); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one set element"); + Element node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "name" ),"searchResults"); + assertEquals(node.getAttribute( "access" ),"field"); + nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/set/element") + .evaluate(document, XPathConstants.NODESET); + assertEquals(1, nodeList.getLength(), "Expected to get one element 'element'"); + node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "type" ), "string"); + nodeList = node.getElementsByTagName("column"); + assertEquals(1, nodeList.getLength(), "Expected to get one element 'column'"); + node = (Element) nodeList.item(0); + assertEquals(node.getAttribute( "name" ), "text"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/TestCase.java index 7764ed443e..631082a091 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/TestCase.java @@ -1,34 +1,41 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.hbm2x.hbm2hbmxml.TypeParamsTest; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; -import org.dom4j.Document; -import org.dom4j.DocumentException; -import org.dom4j.DocumentHelper; -import org.dom4j.Element; -import org.dom4j.XPath; -import org.dom4j.io.SAXReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + import org.hibernate.cfg.AvailableSettings; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; @@ -36,11 +43,12 @@ import org.hibernate.tool.hbm2x.HibernateMappingExporter; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JUnitUtil; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; /** * @author Dmitry Geraskov @@ -52,23 +60,23 @@ public class TestCase { "Order.hbm.xml", }; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - private File outputDir = null; + private File srcDir = null; private File resourcesDir = null; - @Before + @BeforeEach public void setUp() throws Exception { - outputDir = new File(temporaryFolder.getRoot(), "output"); - outputDir.mkdir(); - resourcesDir = new File(temporaryFolder.getRoot(), "resources"); + srcDir = new File(outputFolder, "output"); + srcDir.mkdir(); + resourcesDir = new File(outputFolder, "resources"); resourcesDir.mkdir(); MetadataDescriptor metadataDescriptor = HibernateUtil .initializeMetadataDescriptor(this, HBM_XML_FILES, resourcesDir); Exporter hbmexporter = new HibernateMappingExporter(); hbmexporter.setMetadataDescriptor(metadataDescriptor); - hbmexporter.setOutputDirectory(outputDir); + hbmexporter.setOutputDirectory(srcDir); hbmexporter.start(); } @@ -76,7 +84,7 @@ public void setUp() throws Exception { public void testAllFilesExistence() { JUnitUtil.assertIsNonEmptyFile( new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/Order.hbm.xml")); } @@ -84,71 +92,74 @@ public void testAllFilesExistence() { public void testReadable() { File orderHbmXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/Order.hbm.xml"); Properties properties = new Properties(); properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.setProperty(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); File[] files = new File[] { orderHbmXml }; MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, files, properties); - Assert.assertNotNull(metadataDescriptor.createMetadata()); + assertNotNull(metadataDescriptor.createMetadata()); } @Test - public void testTypeParamsElements() throws DocumentException { + public void testTypeParamsElements() throws Exception { File outputXml = new File( - outputDir, + srcDir, "org/hibernate/tool/hbm2x/hbm2hbmxml/TypeParamsTest/Order.hbm.xml"); JUnitUtil.assertIsNonEmptyFile(outputXml); - SAXReader xmlReader = new SAXReader(); - xmlReader.setValidation(true); - Document document = xmlReader.read(outputXml); - XPath xpath = DocumentHelper.createXPath("//hibernate-mapping/class/property"); - List list = xpath.selectNodes(document); - Assert.assertEquals("Expected to get one property element", 2, list.size()); - Element statusElement = (Element) list.get(0); - Element nameElement = (Element) list.get(1); - if(!statusElement.attribute( "name" ).getText().equals("status")) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(outputXml); + XPath xpath = XPathFactory.newInstance().newXPath(); + NodeList nodeList = (NodeList)xpath + .compile("//hibernate-mapping/class/property") + .evaluate(document, XPathConstants.NODESET); + assertEquals(2, nodeList.getLength(), "Expected to get one property element"); + Element statusElement = (Element) nodeList.item(0); + Element nameElement = (Element) nodeList.item(1); + if(!statusElement.getAttribute( "name" ).equals("status")) { Element temp = nameElement; nameElement = statusElement; statusElement = temp; } - Assert.assertEquals(statusElement.attribute( "name" ).getText(),"status"); - list = statusElement.elements("type"); - Assert.assertEquals("Expected to get one type element", 1, list.size()); - list = ((Element) list.get(0)).elements("param"); - Assert.assertEquals("Expected to get 5 params elements", list.size(), 5); + assertEquals(statusElement.getAttribute( "name" ),"status"); + nodeList = statusElement.getElementsByTagName("type"); + assertEquals( 1, nodeList.getLength(), "Expected to get one type element"); + nodeList = ((Element) nodeList.item(0)).getElementsByTagName("param"); + assertEquals(nodeList.getLength(), 5, "Expected to get 5 params elements"); Map params = new HashMap(); - for (int i = 0; i < list.size(); i++) { - Element param = (Element) list.get(i); - params.put(param.attribute( "name" ).getText(), param.getText()); + for (int i = 0; i < nodeList.getLength(); i++) { + Element param = (Element) nodeList.item(i); + params.put(param.getAttribute( "name" ), param.getTextContent()); } Set set = params.keySet(); - Assert.assertEquals("Expected to get 5 different params elements", params.size(), 5); - Assert.assertTrue( - "Can't find 'catalog' param", - set.contains("catalog")); - Assert.assertEquals("", params.get("catalog")); - Assert.assertTrue( - "Can't find 'column' param", - set.contains("column")); - Assert.assertEquals("STATUS", params.get("column")); - Assert.assertTrue( - "Can't find 'table' param", - set.contains("table")); - Assert.assertEquals("ORDERS", params.get("table")); - Assert.assertTrue( - "Can't find 'schema' param", - set.contains("schema")); - Assert.assertEquals("", params.get("schema")); - Assert.assertTrue( - "Can't find 'enumClass' param", - set.contains("enumClass")); - Assert.assertEquals( + assertEquals(params.size(), 5, "Expected to get 5 different params elements"); + assertTrue( + set.contains("catalog"), + "Can't find 'catalog' param"); + assertEquals("", params.get("catalog")); + assertTrue( + set.contains("column"), + "Can't find 'column' param"); + assertEquals("STATUS", params.get("column")); + assertTrue( + set.contains("table"), + "Can't find 'table' param"); + assertEquals("ORDERS", params.get("table")); + assertTrue( + set.contains("schema"), + "Can't find 'schema' param"); + assertEquals("", params.get("schema")); + assertTrue( + set.contains("enumClass"), + "Can't find 'enumClass' param"); + assertEquals( "org.hibernate.tool.hbm2x.hbm2hbmxml.Order$Status", params.get("enumClass")); - Assert.assertTrue("property name should not have any type element",nameElement.elements("type").isEmpty()); - Assert.assertEquals(nameElement.attribute("type").getText(), "string"); + assertTrue(nameElement.getElementsByTagName("type").getLength() == 0, "property name should not have any type element"); + assertEquals(nameElement.getAttribute("type"), "string"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/CompletionHelperTest/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/CompletionHelperTest/TestCase.java index bd3426938c..265e5f85fe 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/CompletionHelperTest/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/CompletionHelperTest/TestCase.java @@ -1,29 +1,33 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ide.completion.CompletionHelperTest; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.List; import org.hibernate.tool.ide.completion.CompletionHelper; import org.hibernate.tool.ide.completion.EntityNameReference; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author leon @@ -36,17 +40,17 @@ public void testGetCanonicalPath() { qts.add(new EntityNameReference("Article", "art")); qts.add(new EntityNameReference("art.descriptions", "descr")); qts.add(new EntityNameReference("descr.name", "n")); - Assert.assertEquals("Invalid path", "Article/descriptions/name/locale", CompletionHelper.getCanonicalPath(qts, "n.locale")); - Assert.assertEquals("Invalid path", "Article/descriptions", CompletionHelper.getCanonicalPath(qts, "descr")); + assertEquals("Article/descriptions/name/locale", CompletionHelper.getCanonicalPath(qts, "n.locale"), "Invalid path"); + assertEquals("Article/descriptions", CompletionHelper.getCanonicalPath(qts, "descr"), "Invalid path"); // qts.clear(); qts.add(new EntityNameReference("com.company.Clazz", "clz")); qts.add(new EntityNameReference("clz.attr", "a")); - Assert.assertEquals("Invalid path", "com.company.Clazz/attr", CompletionHelper.getCanonicalPath(qts, "a")); + assertEquals("com.company.Clazz/attr", CompletionHelper.getCanonicalPath(qts, "a"), "Invalid path"); // qts.clear(); qts.add(new EntityNameReference("Agga", "a")); - Assert.assertEquals("Invalid path", "Agga", CompletionHelper.getCanonicalPath(qts, "a")); + assertEquals("Agga", CompletionHelper.getCanonicalPath(qts, "a"), "Invalid path"); } @Test diff --git a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/HqlAnalyzer/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/HqlAnalyzer/TestCase.java index 115106a566..053f2c1923 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/HqlAnalyzer/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/HqlAnalyzer/TestCase.java @@ -1,30 +1,36 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ide.completion.HqlAnalyzer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.List; import org.hibernate.tool.ide.completion.EntityNameReference; import org.hibernate.tool.ide.completion.HQLAnalyzer; import org.hibernate.tool.ide.completion.SubQuery; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author leon @@ -119,24 +125,24 @@ public void testVisibleSubQueries() { public void doTestVisibleSubQueries(String query, int size) { char[] cs = query.replaceAll("\\|", "").toCharArray(); List visible = new HQLAnalyzer().getVisibleSubQueries(cs, query.indexOf("|")); - Assert.assertEquals("Invalid visible query size", size, visible.size()); + assertEquals(size, visible.size(), "Invalid visible query size"); } private void doTestSubQueries(String query, int size) { List l = new HQLAnalyzer().getSubQueries(query.toCharArray(), 0).subQueries; - Assert.assertEquals("Incorrent subqueries count", size, l.size()); + assertEquals(size, l.size(), "Incorrent subqueries count"); } private void doTestPrefix(String query, String prefix) { - Assert.assertEquals(prefix, HQLAnalyzer.getEntityNamePrefix(query.toCharArray(), query.indexOf("|"))); + assertEquals(prefix, HQLAnalyzer.getEntityNamePrefix(query.toCharArray(), query.indexOf("|"))); } private void doTestShouldShowTables(String query, boolean expectedValue) { char[] ch = query.replaceAll("\\|", "").toCharArray(); if (expectedValue) { - Assert.assertTrue(new HQLAnalyzer().shouldShowEntityNames(ch, getCaretPosition(query))); + assertTrue(new HQLAnalyzer().shouldShowEntityNames(ch, getCaretPosition(query))); } else { - Assert.assertFalse(new HQLAnalyzer().shouldShowEntityNames(ch, getCaretPosition(query))); + assertFalse(new HQLAnalyzer().shouldShowEntityNames(ch, getCaretPosition(query))); } } @@ -251,12 +257,12 @@ public void testVisibleTablesInQueries() { private void doTestVisibleTables(String query, String[] types, String aliases[]) { char[] toCharArray = query.replaceAll("\\|", "").toCharArray(); List qts = new HQLAnalyzer().getVisibleEntityNames(toCharArray, getCaretPosition(query)); - Assert.assertEquals("Incorrect table count", types.length, qts.size()); + assertEquals(types.length, qts.size(), "Incorrect table count"); int i = 0; for (Iterator iter = qts.iterator(); iter.hasNext();) { EntityNameReference qt = iter.next(); - Assert.assertEquals("Incorrect query table type [" + i + "]", types[i], qt.getEntityName()); - Assert.assertEquals("Incorrect query table alias [" + i + "]", aliases[i++], qt.getAlias()); + assertEquals(types[i], qt.getEntityName(), "Incorrect query table type [" + i + "]"); + assertEquals(aliases[i++], qt.getAlias(), "Incorrect query table alias [" + i + "]"); } } diff --git a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/ModelCompletion/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/ModelCompletion/TestCase.java index 5fb4d66184..18afff6f67 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/ide/completion/ModelCompletion/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/ide/completion/ModelCompletion/TestCase.java @@ -1,22 +1,29 @@ /* - * 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. + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. * - * 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. + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at * - * 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. + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.ide.completion.ModelCompletion; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.net.URL; import java.net.URLClassLoader; @@ -39,13 +46,12 @@ import org.hibernate.tool.ide.completion.IHQLCompletionRequestor; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JavaUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * @author leon @@ -77,17 +83,17 @@ public boolean accept(HQLCompletionProposal proposal) { public void completionFailure(String errorMessage) {} } - @ClassRule - public static TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public static File outputFolder = new File("output"); + private Metadata metadata; private ConfigurationCompletion cc; private ClassLoader originalClassLoader = null; - @BeforeClass + @BeforeAll public static void beforeClass() throws Exception { - File folder = temporaryFolder.getRoot(); File originFolder = new File(TestCase.class .getClassLoader() @@ -95,7 +101,7 @@ public static void beforeClass() throws Exception { .toURI()) .getParentFile(); File destinationFolder = new File( - folder, + outputFolder, "org/hibernate/tool/ide/completion/ModelCompletion"); destinationFolder.mkdirs(); for (File f : originFolder.listFiles()) { @@ -106,21 +112,21 @@ public static void beforeClass() throws Exception { new File(destinationFolder, f.getName()).toPath()); } } - JavaUtil.compile(temporaryFolder.getRoot()); + JavaUtil.compile(outputFolder); } - @Before + @BeforeEach public void setUp() throws Exception { originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( new URLClassLoader( - new URL[] { temporaryFolder.getRoot().toURI().toURL() }, + new URL[] { outputFolder.toURI().toURL() }, originalClassLoader)); metadata = buildMetadata(); cc = new ConfigurationCompletion(metadata); } - @After + @AfterEach public void tearDown() throws Exception { Thread.currentThread().setContextClassLoader(originalClassLoader); } @@ -129,28 +135,28 @@ public void tearDown() throws Exception { public void testGetMappedClasses() { Collector hcc = new Collector(); cc.getMatchingImports("", hcc); - Assert.assertEquals("Invalid entity names count", 11, hcc.getCompletionProposals().length); + assertEquals(11, hcc.getCompletionProposals().length, "Invalid entity names count"); hcc.clear(); cc.getMatchingImports( " ", hcc ); - Assert.assertTrue("Space prefix should have no classes", hcc.getCompletionProposals().length==0); + assertTrue(hcc.getCompletionProposals().length==0, "Space prefix should have no classes"); hcc.clear(); cc.getMatchingImports( "pro", hcc ); - Assert.assertTrue("Completion should not be case sensitive", hcc.getCompletionProposals().length==2); + assertTrue(hcc.getCompletionProposals().length==2, "Completion should not be case sensitive"); hcc.clear(); cc.getMatchingImports( "StoreC", hcc ); - Assert.assertEquals("Invalid entity names count", 1, hcc.getCompletionProposals().length); - Assert.assertEquals("StoreCity should have been found", "StoreCity", hcc.getCompletionProposals()[0].getSimpleName()); + assertEquals(1, hcc.getCompletionProposals().length, "Invalid entity names count"); + assertEquals("StoreCity", hcc.getCompletionProposals()[0].getSimpleName(), "StoreCity should have been found"); hcc.clear(); cc.getMatchingImports( "NotThere", hcc ); - Assert.assertTrue(hcc.getCompletionProposals().length==0); + assertTrue(hcc.getCompletionProposals().length==0); hcc.clear(); cc.getMatchingImports( "Uni", hcc ); - Assert.assertEquals("Universe", hcc.getCompletionProposals()[0].getSimpleName()); + assertEquals(hcc.getCompletionProposals()[0].getSimpleName(), "Universe"); } @@ -201,26 +207,26 @@ public void testKeywordFunction() { HQLCompletionProposal[] completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(4, completionProposals.length); - Assert.assertEquals("alse", completionProposals[0].getCompletion()); + assertEquals(4, completionProposals.length); + assertEquals("alse", completionProposals[0].getCompletion()); hcc.clear(); cc.getMatchingFunctions( "ma", 2, hcc ); completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); - Assert.assertEquals("x", completionProposals[0].getCompletion()); + assertEquals(1, completionProposals.length); + assertEquals("x", completionProposals[0].getCompletion()); hcc.clear(); cc.getMatchingKeywords("FR", 3, hcc); completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); + assertEquals(1, completionProposals.length); hcc.clear(); cc.getMatchingFunctions( "MA", 2, hcc ); completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); + assertEquals(1, completionProposals.length); } @@ -234,16 +240,16 @@ public void testUnmappedClassFields() { private void doTestFields(HQLCompletionProposal[] proposals, String[] fields) { if (fields == null || fields.length==0) { - Assert.assertTrue("No fields should have been found", proposals.length==0); + assertTrue(proposals.length==0, "No fields should have been found"); return; } - Assert.assertEquals("Invalid field count", fields.length, proposals.length); + assertEquals(fields.length, proposals.length, "Invalid field count"); for (int j = 0; j < fields.length; j++) { String f = fields[j]; HQLCompletionProposal proposal = proposals[j]; - Assert.assertEquals("Invalid field name at " + j, f, proposal.getSimpleName()); - Assert.assertEquals("Invalid kind at " + j, proposal.getCompletionKind(), HQLCompletionProposal.PROPERTY); + assertEquals(f, proposal.getSimpleName(), "Invalid field name at " + j); + assertEquals(proposal.getCompletionKind(), HQLCompletionProposal.PROPERTY, "Invalid kind at " + j); } } @@ -295,25 +301,27 @@ private void doTestUnaliasedProductQuery(final String query) { cc.getMatchingProperties( cc.getCanonicalPath(visible, "owner"), "f", hcc ); HQLCompletionProposal[] completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); - Assert.assertEquals("firstName", completionProposals[0].getSimpleName()); + assertEquals(1, completionProposals.length); + assertEquals("firstName", completionProposals[0].getSimpleName()); hcc.clear(); cc.getMatchingProperties( cc.getCanonicalPath(visible, "owner"), "l", hcc ); completionProposals = hcc.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); - Assert.assertEquals("lastName", completionProposals[0].getSimpleName()); + assertEquals(1, completionProposals.length); + assertEquals("lastName", completionProposals[0].getSimpleName()); hcc.clear(); cc.getMatchingProperties( cc.getCanonicalPath(visible, "owner"), "", hcc ); - Assert.assertEquals(3, hcc.getCompletionProposals().length); + assertEquals(3, hcc.getCompletionProposals().length); hcc.clear(); cc.getMatchingProperties( cc.getCanonicalPath(visible, "owner"), "g", hcc ); - Assert.assertEquals(0, hcc.getCompletionProposals().length); + assertEquals(0, hcc.getCompletionProposals().length); } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testBasicFrom() { Collector c = new Collector(); @@ -326,15 +334,15 @@ public void testBasicFrom() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(11, completionProposals.length); + assertEquals(11, completionProposals.length); for (int i = 0; i < completionProposals.length; i++) { HQLCompletionProposal proposal = completionProposals[i]; - Assert.assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(proposal.getReplaceStart(), proposal.getReplaceEnd()); // nothing to replace - Assert.assertNotNull(proposal.getShortEntityName()); - Assert.assertNotNull(proposal.getEntityName()); + assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(proposal.getReplaceStart(), proposal.getReplaceEnd()); // nothing to replace + assertNotNull(proposal.getShortEntityName()); + assertNotNull(proposal.getEntityName()); //assertNotNull(proposal.getShortEntityName()); } @@ -345,10 +353,12 @@ public void testBasicFrom() { completionProposals = c.getCompletionProposals(); - Assert.assertEquals(11, completionProposals.length); + assertEquals(11, completionProposals.length); } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testFromNonWhitespace() { Collector c = new Collector(); @@ -364,24 +374,26 @@ public void testFromNonWhitespace() { caretPosition = getCaretPosition(query); hqlEval.codeComplete(query, caretPosition, c); completionProposals = c.getCompletionProposals(); - Assert.assertEquals("should get results after a nonwhitespace separator", 11, completionProposals.length); + assertEquals(11, completionProposals.length, "should get results after a nonwhitespace separator"); c.clear(); query = "from Store s where "; caretPosition = getCaretPosition(query); hqlEval.codeComplete(query, caretPosition, c); completionProposals = c.getCompletionProposals(); - Assert.assertTrue(completionProposals.length > 0); + assertTrue(completionProposals.length > 0); c.clear(); query = "from Store s where ("; caretPosition = getCaretPosition(query); hqlEval.codeComplete(query, caretPosition, c); completionProposals = c.getCompletionProposals(); - Assert.assertTrue(completionProposals.length > 0); + assertTrue(completionProposals.length > 0); } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testFromWithTabs() { Collector c = new Collector(); @@ -398,15 +410,17 @@ public void testFromWithTabs() { caretPosition = query.indexOf(codeCompletionPlaceMarker); hqlEval.codeComplete(query, caretPosition, c); completionProposals = c.getCompletionProposals(); - Assert.assertTrue(completionProposals.length == 0); + assertTrue(completionProposals.length == 0); c.clear(); query = query.replace('\t', ' '); hqlEval.codeComplete(query, caretPosition, c); completionProposals = c.getCompletionProposals(); - Assert.assertTrue(completionProposals.length > 0); + assertTrue(completionProposals.length > 0); } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testBasicFromPartialEntityName() { Collector c = new Collector(); @@ -419,46 +433,50 @@ public void testBasicFromPartialEntityName() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(2, completionProposals.length); - Assert.assertEquals("Product", completionProposals[0].getSimpleName()); - Assert.assertEquals("duct", completionProposals[0].getCompletion()); - Assert.assertEquals("ProductOwnerAddress", completionProposals[1].getSimpleName()); - Assert.assertEquals("ductOwnerAddress", completionProposals[1].getCompletion()); + assertEquals(2, completionProposals.length); + assertEquals("Product", completionProposals[0].getSimpleName()); + assertEquals("duct", completionProposals[0].getCompletion()); + assertEquals("ProductOwnerAddress", completionProposals[1].getSimpleName()); + assertEquals("ductOwnerAddress", completionProposals[1].getCompletion()); for (int i = 0; i < completionProposals.length; i++) { HQLCompletionProposal proposal = completionProposals[i]; - Assert.assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); + assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); } } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testBasicFromPartialDifferentCaseEntityName() { - Collector c = new Collector(); - - IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); - - String query = "from pro| "; - int caretPosition = getCaretPosition(query); - hqlEval.codeComplete(query, caretPosition, c); - - HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - - Assert.assertEquals(2, completionProposals.length); - Assert.assertEquals("Product", completionProposals[0].getSimpleName()); - Assert.assertEquals("Product", completionProposals[0].getCompletion()); - Assert.assertEquals("ProductOwnerAddress", completionProposals[1].getSimpleName()); - Assert.assertEquals("ProductOwnerAddress", completionProposals[1].getCompletion()); - for (int i = 0; i < completionProposals.length; i++) { + Collector c = new Collector(); + + IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); + + String query = "from pro| "; + int caretPosition = getCaretPosition(query); + hqlEval.codeComplete(query, caretPosition, c); + + HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); + + assertEquals(2, completionProposals.length); + assertEquals("Product", completionProposals[0].getSimpleName()); + assertEquals("Product", completionProposals[0].getCompletion()); + assertEquals("ProductOwnerAddress", completionProposals[1].getSimpleName()); + assertEquals("ProductOwnerAddress", completionProposals[1].getCompletion()); + for (int i = 0; i < completionProposals.length; i++) { HQLCompletionProposal proposal = completionProposals[i]; - Assert.assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition-3, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); + assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition-3, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); } } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testDottedFromPartialEntityName() { Collector c = new Collector(); @@ -471,69 +489,71 @@ public void testDottedFromPartialEntityName() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(5, completionProposals.length); + assertEquals(5, completionProposals.length); for (int i = 0; i < completionProposals.length; i++) { HQLCompletionProposal proposal = completionProposals[i]; - Assert.assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); - Assert.assertTrue(proposal.getCompletion().startsWith( "ool.ide.completion" )); + assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); + assertTrue(proposal.getCompletion().startsWith( "ool.ide.completion" )); } } @Test public void testBadInputBeforeCursor() { - Collector c = new Collector(); - - IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); - - String query = "from org.;hibernate.t| "; - int caretPosition = getCaretPosition(query); + Collector c = new Collector(); + + IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); + + String query = "from org.;hibernate.t| "; + int caretPosition = getCaretPosition(query); hqlEval.codeComplete(query, caretPosition, c); - - HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - - Assert.assertEquals(0, completionProposals.length); + + HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); + + assertEquals(0, completionProposals.length); } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testBadInputAfterCursor() { - Collector c = new Collector(); - - IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); - - String query = "from org.hibernate.t| ;"; - int caretPosition = getCaretPosition(query); + Collector c = new Collector(); + + IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); + + String query = "from org.hibernate.t| ;"; + int caretPosition = getCaretPosition(query); hqlEval.codeComplete(query, caretPosition, c); HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(5, completionProposals.length); + assertEquals(5, completionProposals.length); } @Test public void testAliasRef() { - Collector c = new Collector(); - - IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); - - String query = "from Product as pr_od where pr_|"; - int caretPosition = getCaretPosition(query); + Collector c = new Collector(); + + IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); + + String query = "from Product as pr_od where pr_|"; + int caretPosition = getCaretPosition(query); hqlEval.codeComplete(getCleanQuery(query), caretPosition, c); HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); + assertEquals(1, completionProposals.length); HQLCompletionProposal proposal = completionProposals[0]; - Assert.assertEquals( "od", proposal.getCompletion()); - Assert.assertEquals(HQLCompletionProposal.ALIAS_REF, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); - Assert.assertEquals("org.hibernate.tool.ide.completion.ModelCompletion.Product", proposal.getEntityName()); + assertEquals( "od", proposal.getCompletion()); + assertEquals(HQLCompletionProposal.ALIAS_REF, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); + assertEquals("org.hibernate.tool.ide.completion.ModelCompletion.Product", proposal.getEntityName()); } @@ -543,28 +563,28 @@ private String getCleanQuery(String query) { @Test public void testBasicPropertyNames() { - Collector c = new Collector(); - - IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); - - String query = "from Product as p where p.v|"; //TODO: is non-aliased references allowed ? - int caretPosition = getCaretPosition(query); + Collector c = new Collector(); + + IHQLCodeAssist hqlEval = new HQLCodeAssist(metadata); + + String query = "from Product as p where p.v|"; //TODO: is non-aliased references allowed ? + int caretPosition = getCaretPosition(query); hqlEval.codeComplete(getCleanQuery(query), caretPosition, c); HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(1, completionProposals.length); + assertEquals(1, completionProposals.length); HQLCompletionProposal proposal = completionProposals[0]; - Assert.assertEquals( "ersion", proposal.getCompletion()); - Assert.assertEquals(HQLCompletionProposal.PROPERTY, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); + assertEquals( "ersion", proposal.getCompletion()); + assertEquals(HQLCompletionProposal.PROPERTY, proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); //TODO: keep a path/context assertEquals("Product", proposal.getShortEntityName()); - Assert.assertEquals("org.hibernate.tool.ide.completion.ModelCompletion.Product", proposal.getEntityName()); - Assert.assertEquals("version", proposal.getPropertyName()); - Assert.assertNotNull(proposal.getProperty()); - Assert.assertEquals(proposal.getPropertyName(), proposal.getProperty().getName()); + assertEquals("org.hibernate.tool.ide.completion.ModelCompletion.Product", proposal.getEntityName()); + assertEquals("version", proposal.getPropertyName()); + assertNotNull(proposal.getProperty()); + assertEquals(proposal.getPropertyName(), proposal.getProperty().getName()); } @@ -581,8 +601,8 @@ public void testComponentPropertyNames() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(3, completionProposals.length); - Assert.assertNotNull(completionProposals[0]); + assertEquals(3, completionProposals.length); + assertNotNull(completionProposals[0]); c.clear(); @@ -592,7 +612,7 @@ public void testComponentPropertyNames() { completionProposals = c.getCompletionProposals(); - Assert.assertEquals(3, completionProposals.length); + assertEquals(3, completionProposals.length); c.clear(); @@ -602,11 +622,12 @@ public void testComponentPropertyNames() { completionProposals = c.getCompletionProposals(); - Assert.assertEquals(3, completionProposals.length); + assertEquals(3, completionProposals.length); - } + // TODO HBX-2063: Investigate and reenable + @Disabled @Test public void testInFromAfterEntityAlias() { Collector c = new Collector(); @@ -619,13 +640,13 @@ public void testInFromAfterEntityAlias() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertEquals(11, completionProposals.length); + assertEquals(11, completionProposals.length); HQLCompletionProposal proposal = completionProposals[0]; - Assert.assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); + assertEquals(HQLCompletionProposal.ENTITY_NAME, proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); } @@ -641,13 +662,13 @@ public void testKeywordsFunctions() { HQLCompletionProposal[] completionProposals = c.getCompletionProposals(); - Assert.assertTrue(completionProposals.length>0); + assertTrue(completionProposals.length>0); for (int i = 0; i < completionProposals.length; i++) { HQLCompletionProposal proposal = completionProposals[i]; - Assert.assertTrue(HQLCompletionProposal.KEYWORD==proposal.getCompletionKind() || HQLCompletionProposal.FUNCTION==proposal.getCompletionKind()); - Assert.assertEquals(caretPosition, proposal.getCompletionLocation()); - Assert.assertEquals(caretPosition, proposal.getReplaceStart()); - Assert.assertEquals(caretPosition, proposal.getReplaceEnd()); + assertTrue(HQLCompletionProposal.KEYWORD==proposal.getCompletionKind() || HQLCompletionProposal.FUNCTION==proposal.getCompletionKind()); + assertEquals(caretPosition, proposal.getCompletionLocation()); + assertEquals(caretPosition, proposal.getReplaceStart()); + assertEquals(caretPosition, proposal.getReplaceEnd()); } } @@ -658,7 +679,8 @@ protected int getCaretPosition(String str) { private Metadata buildMetadata() { StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); - ssrb.applySetting(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + ssrb.applySetting(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + ssrb.applySetting(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); MetadataSources metadataSources = new MetadataSources() .addInputStream(getClass().getResourceAsStream("Product.hbm.xml")) .addInputStream(getClass().getResourceAsStream("Store.hbm.xml")) diff --git a/test/nodb/src/test/java/org/hibernate/tool/jdbc2cfg/DefaultReverseEngineeringStrategy/TestCase.java b/test/nodb/src/test/java/org/hibernate/tool/jdbc2cfg/DefaultReverseEngineeringStrategy/TestCase.java index c1c53d2fca..d160c57111 100644 --- a/test/nodb/src/test/java/org/hibernate/tool/jdbc2cfg/DefaultReverseEngineeringStrategy/TestCase.java +++ b/test/nodb/src/test/java/org/hibernate/tool/jdbc2cfg/DefaultReverseEngineeringStrategy/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-12-01 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.DefaultReverseEngineeringStrategy; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.sql.Types; import java.util.ArrayList; import java.util.List; @@ -14,8 +32,7 @@ import org.hibernate.cfg.reveng.ReverseEngineeringStrategy; import org.hibernate.cfg.reveng.TableIdentifier; import org.hibernate.mapping.Column; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author max @@ -28,70 +45,70 @@ public class TestCase { @Test public void testColumnKeepCase() { - Assert.assertEquals("name", rns.columnToPropertyName(null, "name") ); - Assert.assertEquals("nameIsValid", rns.columnToPropertyName(null, "nameIsValid") ); + assertEquals("name", rns.columnToPropertyName(null, "name") ); + assertEquals("nameIsValid", rns.columnToPropertyName(null, "nameIsValid") ); } @Test public void testColumnUpperToLower() { - Assert.assertEquals("name", rns.columnToPropertyName(null, "NAME") ); - Assert.assertEquals("name", rns.columnToPropertyName(null, "Name") ); + assertEquals("name", rns.columnToPropertyName(null, "NAME") ); + assertEquals("name", rns.columnToPropertyName(null, "Name") ); } @Test public void testColumnRemoveChars() { - Assert.assertEquals("name", rns.columnToPropertyName(null, "_Name") ); - Assert.assertEquals("name", rns.columnToPropertyName(null, "_name") ); - Assert.assertEquals("name", rns.columnToPropertyName(null, "_name") ); + assertEquals("name", rns.columnToPropertyName(null, "_Name") ); + assertEquals("name", rns.columnToPropertyName(null, "_name") ); + assertEquals("name", rns.columnToPropertyName(null, "_name") ); } @Test public void testColumnToCamelCase() { - Assert.assertEquals("labelForField", rns.columnToPropertyName(null, "LABEL_FOR_FIELD") ); - Assert.assertEquals("nameToMe", rns.columnToPropertyName(null, "_name-To-Me") ); + assertEquals("labelForField", rns.columnToPropertyName(null, "LABEL_FOR_FIELD") ); + assertEquals("nameToMe", rns.columnToPropertyName(null, "_name-To-Me") ); } @Test public void testColumnChangeCamelCase() { - Assert.assertEquals("labelForField", rns.columnToPropertyName(null, "LabelForField") ); + assertEquals("labelForField", rns.columnToPropertyName(null, "LabelForField") ); } @Test public void testTableKeepCase() { - Assert.assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("SickPatients") ) ); + assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("SickPatients") ) ); } @Test public void testTableUpperToLower() { - Assert.assertEquals("Patients", rns.tableToClassName(new TableIdentifier("PATIENTS") ) ); - Assert.assertEquals("Patients", rns.tableToClassName(new TableIdentifier("patients") ) ); + assertEquals("Patients", rns.tableToClassName(new TableIdentifier("PATIENTS") ) ); + assertEquals("Patients", rns.tableToClassName(new TableIdentifier("patients") ) ); } @Test public void testTableRemoveChars() { - Assert.assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_Patients") ) ); - Assert.assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_patients") ) ); - Assert.assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_patients") ) ); - Assert.assertEquals("PatientInterventions", rns.tableToClassName(new TableIdentifier("_PATIENT_INTERVENTIONS") ) ); + assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_Patients") ) ); + assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_patients") ) ); + assertEquals("Patients", rns.tableToClassName(new TableIdentifier("_patients") ) ); + assertEquals("PatientInterventions", rns.tableToClassName(new TableIdentifier("_PATIENT_INTERVENTIONS") ) ); } @Test public void testTableToCamelCase() { - Assert.assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("Sick_Patients") ) ); - Assert.assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("_Sick-Patients") ) ); + assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("Sick_Patients") ) ); + assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("_Sick-Patients") ) ); } @Test public void testTableKeepCamelCase() { - Assert.assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("SickPatients") ) ); + assertEquals("SickPatients", rns.tableToClassName(new TableIdentifier("SickPatients") ) ); } @Test public void testBasicForeignKeyNames() { - Assert.assertEquals("products", rns.foreignKeyToCollectionName("something", new TableIdentifier("product"), null, new TableIdentifier("order"), null, true ) ); - Assert.assertEquals("willies", rns.foreignKeyToCollectionName("something", new TableIdentifier("willy"), null, new TableIdentifier("order"), null, true ) ); - Assert.assertEquals("boxes", rns.foreignKeyToCollectionName("something", new TableIdentifier("box"), null, new TableIdentifier("order"), null, true ) ); - Assert.assertEquals("order", rns.foreignKeyToEntityName("something", new TableIdentifier("product"), null, new TableIdentifier("order"), null, true ) ); + assertEquals("products", rns.foreignKeyToCollectionName("something", new TableIdentifier("product"), null, new TableIdentifier("order"), null, true ) ); + assertEquals("willies", rns.foreignKeyToCollectionName("something", new TableIdentifier("willy"), null, new TableIdentifier("order"), null, true ) ); + assertEquals("boxes", rns.foreignKeyToCollectionName("something", new TableIdentifier("box"), null, new TableIdentifier("order"), null, true ) ); + assertEquals("order", rns.foreignKeyToEntityName("something", new TableIdentifier("product"), null, new TableIdentifier("order"), null, true ) ); } @Test @@ -106,9 +123,9 @@ public String tableToClassName(TableIdentifier tableIdentifier) { custom.setSettings( new ReverseEngineeringSettings(custom) ); TableIdentifier productTable = new TableIdentifier("product"); - Assert.assertEquals("ProductImpl", custom.tableToClassName( productTable )); + assertEquals("ProductImpl", custom.tableToClassName( productTable )); - Assert.assertEquals("productImpls", custom.foreignKeyToCollectionName("something", productTable, null, new TableIdentifier("order"), null, true ) ); + assertEquals("productImpls", custom.foreignKeyToCollectionName("something", productTable, null, new TableIdentifier("order"), null, true ) ); /*assertEquals("willies", custom.foreignKeyToCollectionName("something", new TableIdentifier("willy"), null, new TableIdentifier("order"), null, true ) ); assertEquals("boxes", custom.foreignKeyToCollectionName("something", new TableIdentifier("box"), null, new TableIdentifier("order"), null, true ) ); assertEquals("order", custom.foreignKeyToEntityName("something", productTable, null, new TableIdentifier("order"), null, true ) );*/ @@ -124,34 +141,34 @@ public void testForeignKeyNamesToPropertyNames() { TableIdentifier toTable = new TableIdentifier("address"); List toColumns = new ArrayList(); - Assert.assertEquals("address", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, true) ); - Assert.assertEquals("companies", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, true) ); + assertEquals("address", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, true) ); + assertEquals("companies", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, true) ); fkName = "billing"; fromColumns.clear(); fromColumns.add(new Column("bill_adr") ); - Assert.assertEquals("addressByBillAdr", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); - Assert.assertEquals("companiesForBillAdr", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); + assertEquals("addressByBillAdr", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); + assertEquals("companiesForBillAdr", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); fromColumns.add(new Column("bill_adrtype") ); - Assert.assertEquals("addressByBilling", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); - Assert.assertEquals("companiesForBilling", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); + assertEquals("addressByBilling", rns.foreignKeyToEntityName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); + assertEquals("companiesForBilling", rns.foreignKeyToCollectionName(fkName, fromTable, fromColumns, toTable, toColumns, false) ); } @Test public void testPreferredTypes() { - Assert.assertEquals("int",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, false, false)); - Assert.assertEquals("because nullable it should not be int", "java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, true, false)); - Assert.assertEquals("java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.NUMERIC,0,9,0, true, false)); - Assert.assertEquals("java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, true, false)); - Assert.assertEquals("serializable",rns.columnToHibernateTypeName(new TableIdentifier("sdf"), "bogus",-567,0,0,0, false, false)); + assertEquals("int",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, false, false)); + assertEquals("java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, true, false), "because nullable it should not be int"); + assertEquals("java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.NUMERIC,0,9,0, true, false)); + assertEquals("java.lang.Integer",rns.columnToHibernateTypeName(null, "bogus",Types.INTEGER,0,0,0, true, false)); + assertEquals("serializable",rns.columnToHibernateTypeName(new TableIdentifier("sdf"), "bogus",-567,0,0,0, false, false)); - Assert.assertEquals("string",rns.columnToHibernateTypeName(new TableIdentifier("sdf"), "bogus",12,0,0,0, false, false)); + assertEquals("string",rns.columnToHibernateTypeName(new TableIdentifier("sdf"), "bogus",12,0,0,0, false, false)); } @Test public void testReservedKeywordsHandling() { - Assert.assertEquals("class_", rns.columnToPropertyName(new TableIdentifier("blah"), "class")); + assertEquals("class_", rns.columnToPropertyName(new TableIdentifier("blah"), "class")); } } diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/TopDown.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/TopDown.hbm.xml index df2640ea90..768dd54b2e 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/TopDown.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/TopDown.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/hibernate.properties b/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/hibernate.properties index 7c3d06795d..7dbd997fa3 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/hibernate.properties +++ b/test/nodb/src/test/resources/org/hibernate/tool/ant/Exception/hibernate.properties @@ -1 +1,2 @@ -hibernate.dialect org.hibernate.dialect.H2Dialect \ No newline at end of file +hibernate.dialect org.hibernate.tools.test.util.HibernateUtil$Dialect +hibernate.connection.provider_class org.hibernate.tools.test.util.HibernateUtil$ConnectionProvider \ No newline at end of file diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/TopDown.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/TopDown.hbm.xml index df2640ea90..768dd54b2e 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/TopDown.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/TopDown.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/hibernate.cfg.xml b/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/hibernate.cfg.xml index fd86520f7e..c8e60ae9e3 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/hibernate.cfg.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ant/NoConnInfoExport/hibernate.cfg.xml @@ -4,7 +4,7 @@ "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> - org.h2.Driver - org.hibernate.dialect.H2Dialect + org.hibernate.tools.test.util.HibernateUtil$Dialect + org.hibernate.tools.test.util.HibernateUtil$ConnectionProvider diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/Customer.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/Customer.hbm.xml index edd80ff689..fdc909ef28 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/Customer.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/Customer.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/HelloWorld.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/HelloWorld.hbm.xml index 8c4356fb7e..1154536904 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/HelloWorld.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/DocExporterTest/HelloWorld.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> + + + + + + + + + + + + + + 'BILLING' + + + + + 'SHIPPING' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml index 16f2a4e978..329f804fd8 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/Basic.hbm.xml @@ -1,13 +1,13 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> - @@ -24,24 +24,24 @@ next_hi_value - - description - + - + - + - anotherone + anotherone - + diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicCompositeId.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicCompositeId.hbm.xml index a84fb49183..61302ff3d6 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicCompositeId.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/Hbm2HbmXmlTest/BasicCompositeId.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml index 813dac45ae..25e83cbc7a 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ListArrayTest/Glarch.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/UserGroup.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/UserGroup.hbm.xml index 4da25805f0..d8aa8e27eb 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/UserGroup.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/hbm2x/hbm2hbmxml/ManyToManyTest/UserGroup.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/City.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/City.hbm.xml index a685453b2b..156ecb7007 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/City.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/City.hbm.xml @@ -1,6 +1,6 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Product.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Product.hbm.xml index 1b83e2f516..8ceb587ace 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Product.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Product.hbm.xml @@ -1,6 +1,6 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/ProductOwnerAddress.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/ProductOwnerAddress.hbm.xml index 2acf2e0514..c52c608321 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/ProductOwnerAddress.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/ProductOwnerAddress.hbm.xml @@ -1,6 +1,6 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Store.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Store.hbm.xml index 9e32e387e9..ae2dc5e0d1 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Store.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/Store.hbm.xml @@ -1,6 +1,6 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/StoreCity.hbm.xml b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/StoreCity.hbm.xml index db806a886f..92c597c355 100644 --- a/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/StoreCity.hbm.xml +++ b/test/nodb/src/test/resources/org/hibernate/tool/ide/completion/ModelCompletion/StoreCity.hbm.xml @@ -1,6 +1,6 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/oracle/pom.xml b/test/oracle/pom.xml index d04014beb9..9b83bd6cb0 100644 --- a/test/oracle/pom.xml +++ b/test/oracle/pom.xml @@ -8,7 +8,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-oracle @@ -17,17 +17,17 @@ - junit - junit - - - com.oracle.jdbc + com.oracle.ojdbc ojdbc8 org.hibernate hibernate-tools-tests-common - + + org.junit.jupiter + junit-jupiter-engine + + diff --git a/test/oracle/readme.txt b/test/oracle/readme.txt index e55ac50cb7..c6acab6d7e 100644 --- a/test/oracle/readme.txt +++ b/test/oracle/readme.txt @@ -6,29 +6,28 @@ To do this on your own machine execute the following steps: 1. Install Docker. -2. Pull the Docker image of the Oracle DB: 'docker pull sath89/oracle-12c' +2. Pull the Docker image of the Oracle DB: 'docker pull store/oracle/database-enterprise:12.2.0.1-slim' -3. Start the database: 'docker run -d -p 8080:8080 -p 1521:1521 sath89/oracle-12c'. +3. Start the database: 'docker run --name oracle -d -p 1521:1521 store/oracle/database-enterprise:12.2.0.1-slim'. This step takes a while the first time. Use 'docker logs' and specify the id of your docker container to monitor the progress. When the logs say 'Database is ready to use' you can move to step 4. -4. Connect to the database using your favorite client (e.g. DBeaver: http://dbeaver.jkiss.org) +4. Connect to the database: 'docker exec -it oracle bash -c "source /home/oracle/.bashrc; sqlplus sys/Oradoc_db1@ORCLPDB1 as sysdba"' +Alternatively you can use your favorite database client (e.g. DBeaver: http://dbeaver.jkiss.org) hostname: localhost port: 1521 -service name: xe.oracle.docker -username: system -password: oracle -The complete JDBC URL is: jdbc:oracle:thin:@//localhost:1521/xe.oracle.docker +service name: ORCLPDB1.localdomain +username: SYS +password: Oradoc_db1 +role: SYSDBA +The complete JDBC URL is: jdbc:oracle:thin:@//localhost:1521/ORCLPDB1.localdomain 5. Create the Hibernate Tools test ('HTT') database. You can do this by executing the following SQL: - -create user HTT - identified by HTT - default tablespace USERS - temporary tablespace TEMP - quota unlimited on USERS; +create user HTT identified by HTT; grant all privileges to HTT with admin option; 6. You can now connect with username 'HTT' and password 'HTT' and verify the existence of the 'HTT' schema. -If that is the case you are ready to run the tests. \ No newline at end of file +If that is the case you are ready to run the tests. + +7. Run only the Oracle tests using the 'oracle' profile: mvn clean test -P oracle \ No newline at end of file diff --git a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java b/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java deleted file mode 100644 index 33bf9a57e7..0000000000 --- a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Created on 2004-12-01 - * - */ -package org.hibernate.tool.jdbc2cfg.CompositeIdOrder; - -import java.sql.SQLException; -import java.util.Iterator; - -import org.hibernate.boot.Metadata; -import org.hibernate.mapping.Column; -import org.hibernate.mapping.ForeignKey; -import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Property; -import org.hibernate.mapping.Selectable; -import org.hibernate.mapping.Table; -import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; -import org.hibernate.tools.test.util.HibernateUtil; -import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - - - -/** - * @author max - * @author koen - */ -public class TestCase { - - private Metadata metadata = null; - - @Before - public void setUp() { - JdbcUtil.createDatabase(this); - metadata = MetadataDescriptorFactory - .createJdbcDescriptor(null, null, true) - .createMetadata(); - } - - @After - public void tearDown() { - JdbcUtil.dropDatabase(this); - } - - @Test - public void testMultiColumnForeignKeys() throws SQLException { - - Table table = HibernateUtil.getTable(metadata, "COURSE"); - Assert.assertNotNull(table); - ForeignKey foreignKey = HibernateUtil.getForeignKey(table, "FK_COURSE__SCHEDULE"); - Assert.assertNotNull(foreignKey); - - Assert.assertEquals("Schedule", foreignKey.getReferencedEntityName() ); - Assert.assertEquals("COURSE", foreignKey.getTable().getName() ); - - Assert.assertEquals(1,foreignKey.getColumnSpan() ); - Assert.assertEquals(foreignKey.getColumn(0).getName(), "SCHEDULE_KEY"); - - Assert.assertEquals(table.getPrimaryKey().getColumn(0).getName(), "SCHEDULE_KEY"); - Assert.assertEquals(table.getPrimaryKey().getColumn(1).getName(), "REQUEST_KEY"); - - PersistentClass course = metadata.getEntityBinding("Course"); - - Assert.assertEquals(2,course.getIdentifier().getColumnSpan() ); - Iterator columnIterator = course.getIdentifier().getColumnIterator(); - Assert.assertEquals(((Column)(columnIterator.next())).getName(), "SCHEDULE_KEY"); - Assert.assertEquals(((Column)(columnIterator.next())).getName(), "REQUEST_KEY"); - - PersistentClass topic = metadata.getEntityBinding("CourseTopic"); - - Property property = topic.getProperty("course"); - columnIterator = property.getValue().getColumnIterator(); - Assert. assertEquals(((Column)(columnIterator.next())).getName(), "SCHEDULE_KEY"); - Assert.assertEquals(((Column)(columnIterator.next())).getName(), "REQUEST_KEY"); - - } - - -} diff --git a/test/oracle/src/test/java/org/hibernate/cfg/reveng/dialect/TestCase.java b/test/oracle/src/test/java/org/hibernate/cfg/reveng/dialect/TestCase.java new file mode 100644 index 0000000000..ed3cf4f6e8 --- /dev/null +++ b/test/oracle/src/test/java/org/hibernate/cfg/reveng/dialect/TestCase.java @@ -0,0 +1,106 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.cfg.reveng.dialect; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; + +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.Environment; +import org.hibernate.cfg.reveng.DefaultDatabaseCollector; +import org.hibernate.cfg.reveng.ReverseEngineeringRuntimeInfo; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.engine.jdbc.spi.JdbcServices; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.tools.test.util.JdbcUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class TestCase { + + private Properties properties = null; + private ServiceRegistry serviceRegistry; + + @BeforeEach + public void setUp() { + JdbcUtil.createDatabase(this); + properties = Environment.getProperties(); + StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(); + serviceRegistry = ssrb.build(); + } + + @AfterEach + public void tearDown() { + JdbcUtil.dropDatabase(this); + } + + @Test + public void testColumnTypeSizes() { + MetaDataDialect dialect = configureOracleMetaDataDialect(); + + assertSqlTypeLengths(dialect, "a_varchar2_char", "VARCHAR2", 10, 0); + assertSqlTypeLengths(dialect, "a_varchar2_byte", "VARCHAR2", 10, 0); + assertSqlTypeLengths(dialect, "a_varchar_char", "VARCHAR2", 10, 0); + assertSqlTypeLengths(dialect, "a_varchar_byte", "VARCHAR2", 10, 0); + assertSqlTypeLengths(dialect, "a_nvarchar", "NVARCHAR2", 10, 0); + assertSqlTypeLengths(dialect, "a_char_char", "CHAR", 10, 0); + assertSqlTypeLengths(dialect, "a_char_byte", "CHAR", 10, 0); + assertSqlTypeLengths(dialect, "a_nchar_char", "NCHAR", 10, 0); + assertSqlTypeLengths(dialect, "a_nchar_byte", "NCHAR", 10, 0); + assertSqlTypeLengths(dialect, "a_number_int", "NUMBER", 10, 0); + assertSqlTypeLengths(dialect, "a_number_dec", "NUMBER", 10, 2); + assertSqlTypeLengths(dialect, "a_float", "FLOAT", 10, 0); + } + + private MetaDataDialect configureOracleMetaDataDialect() { + MetaDataDialect dialect = new OracleMetaDataDialect(); + JdbcServices jdbcServices = serviceRegistry.getService(JdbcServices.class); + ConnectionProvider connectionProvider = serviceRegistry.getService(ConnectionProvider.class); + dialect.configure( + ReverseEngineeringRuntimeInfo.createInstance( + connectionProvider, + jdbcServices.getSqlExceptionHelper().getSqlExceptionConverter(), + new DefaultDatabaseCollector(dialect))); + return dialect; + } + + private void assertSqlTypeLengths(MetaDataDialect dialect, String columnName, String typeName, int columnSize, int decimalDigits) { + columnName = columnName.toUpperCase(); + String catalog = properties.getProperty(AvailableSettings.DEFAULT_CATALOG); + String schema = properties.getProperty(AvailableSettings.DEFAULT_SCHEMA); + Iterator> columns = dialect.getColumns(catalog, schema, "PERSON", columnName); + boolean found = false; + while (columns.hasNext()) { + Map column = columns.next(); + assertEquals(column.get("COLUMN_NAME"),columnName.toUpperCase()); + assertEquals(column.get("TYPE_NAME"), typeName); + assertEquals(column.get("COLUMN_SIZE"), columnSize); + assertEquals(column.get("DECIMAL_DIGITS"), decimalDigits); + found = true; + } + assertTrue(found, "Expected column '" + columnName + "'to exist."); + } +} diff --git a/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java new file mode 100644 index 0000000000..6ae43a3529 --- /dev/null +++ b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/TestCase.java @@ -0,0 +1,97 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.CompositeIdOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import java.sql.SQLException; +import java.util.Iterator; + +import org.hibernate.boot.Metadata; +import org.hibernate.mapping.Column; +import org.hibernate.mapping.ForeignKey; +import org.hibernate.mapping.PersistentClass; +import org.hibernate.mapping.Property; +import org.hibernate.mapping.Selectable; +import org.hibernate.mapping.Table; +import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; +import org.hibernate.tools.test.util.HibernateUtil; +import org.hibernate.tools.test.util.JdbcUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * @author max + * @author koen + */ +public class TestCase { + + private Metadata metadata = null; + + @BeforeEach + public void setUp() { + JdbcUtil.createDatabase(this); + metadata = MetadataDescriptorFactory + .createJdbcDescriptor(null, null, true) + .createMetadata(); + } + + @AfterEach + public void tearDown() { + JdbcUtil.dropDatabase(this); + } + + @Test + public void testMultiColumnForeignKeys() throws SQLException { + + Table table = HibernateUtil.getTable(metadata, "COURSE"); + assertNotNull(table); + ForeignKey foreignKey = HibernateUtil.getForeignKey(table, "FK_COURSE__SCHEDULE"); + assertNotNull(foreignKey); + + assertEquals("Schedule", foreignKey.getReferencedEntityName() ); + assertEquals("COURSE", foreignKey.getTable().getName() ); + + assertEquals(1,foreignKey.getColumnSpan() ); + assertEquals(foreignKey.getColumn(0).getName(), "SCHEDULE_KEY"); + + assertEquals(table.getPrimaryKey().getColumn(0).getName(), "SCHEDULE_KEY"); + assertEquals(table.getPrimaryKey().getColumn(1).getName(), "REQUEST_KEY"); + + PersistentClass course = metadata.getEntityBinding("Course"); + + assertEquals(2,course.getIdentifier().getColumnSpan() ); + Iterator columnIterator = course.getIdentifier().getColumnIterator(); + assertEquals(((Column)(columnIterator.next())).getName(), "SCHEDULE_KEY"); + assertEquals(((Column)(columnIterator.next())).getName(), "REQUEST_KEY"); + + PersistentClass topic = metadata.getEntityBinding("CourseTopic"); + + Property property = topic.getProperty("course"); + columnIterator = property.getValue().getColumnIterator(); + assertEquals(((Column)(columnIterator.next())).getName(), "SCHEDULE_KEY"); + assertEquals(((Column)(columnIterator.next())).getName(), "REQUEST_KEY"); + + } + + +} diff --git a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java similarity index 52% rename from test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java rename to test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java index cb7cad2dd6..c7b805bcb3 100644 --- a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java +++ b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Identity/TestCase.java @@ -1,9 +1,27 @@ /* - * Created on 2004-11-23 + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2004-2021 Red Hat, Inc. * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.jdbc2cfg.Identity; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -11,11 +29,9 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * @author max @@ -25,7 +41,7 @@ public class TestCase { private Metadata metadata = null; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -33,19 +49,19 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } // TODO HBX-1412: Enable the test below and make sure it passes. - @Ignore +// @Disabled @Test public void testIdentity() throws SQLException { PersistentClass classMapping = metadata.getEntityBinding("Autoinc"); - Assert.assertNotNull(classMapping); - Assert.assertEquals( + assertNotNull(classMapping); + assertEquals( "identity", ((SimpleValue)classMapping .getIdentifierProperty() @@ -53,7 +69,7 @@ public void testIdentity() throws SQLException { .getIdentifierGeneratorStrategy()); classMapping = metadata.getEntityBinding("Noautoinc"); - Assert.assertEquals( + assertEquals( "assigned", ((SimpleValue)classMapping .getIdentifierProperty() diff --git a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java similarity index 59% rename from test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java rename to test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java index cade7f0a1e..7e561c89c3 100644 --- a/test/oracle/src/main/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java +++ b/test/oracle/src/test/java/org/hibernate/tool/jdbc2cfg/Views/TestCase.java @@ -4,6 +4,11 @@ */ package org.hibernate.tool.jdbc2cfg.Views; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.sql.SQLException; import org.hibernate.boot.Metadata; @@ -12,10 +17,9 @@ import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; import org.hibernate.tools.test.util.HibernateUtil; import org.hibernate.tools.test.util.JdbcUtil; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; @@ -27,7 +31,7 @@ public class TestCase { private Metadata metadata; - @Before + @BeforeEach public void setUp() { JdbcUtil.createDatabase(this); metadata = MetadataDescriptorFactory @@ -35,7 +39,7 @@ public void setUp() { .createMetadata(); } - @After + @AfterEach public void tearDown() { JdbcUtil.dropDatabase(this); } @@ -44,19 +48,19 @@ public void tearDown() { public void testViewAndSynonyms() throws SQLException { PersistentClass classMapping = metadata.getEntityBinding("Basicview"); - Assert.assertNotNull(classMapping); + assertNotNull(classMapping); classMapping = metadata.getEntityBinding("Weirdname"); - Assert.assertTrue("If this is not-null synonyms apparently work!",classMapping==null); + assertTrue(classMapping==null, "If this is not-null synonyms apparently work!"); // get comments Table table = HibernateUtil.getTable(metadata, "BASIC"); - Assert.assertEquals("a basic comment", table.getComment()); - Assert.assertEquals("a solid key", table.getPrimaryKey().getColumn(0).getComment()); + assertEquals("a basic comment", table.getComment()); + assertEquals("a solid key", table.getPrimaryKey().getColumn(0).getComment()); table = HibernateUtil.getTable(metadata, "MULTIKEYED"); - Assert.assertNull(table.getComment()); - Assert.assertNull(table.getColumn(0).getComment()); + assertNull(table.getComment()); + assertNull(table.getColumn(0).getComment()); } diff --git a/test/oracle/src/test/java/org/hibernate/tool/test/db/oracle/TestSuite.java b/test/oracle/src/test/java/org/hibernate/tool/test/db/oracle/TestSuite.java index 68c945d1ac..981e42f16f 100644 --- a/test/oracle/src/test/java/org/hibernate/tool/test/db/oracle/TestSuite.java +++ b/test/oracle/src/test/java/org/hibernate/tool/test/db/oracle/TestSuite.java @@ -1,13 +1,32 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2021 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tool.test.db.oracle; -import org.hibernate.tools.test.util.DbSuite; -import org.junit.runner.RunWith; -import org.junit.runners.Suite.SuiteClasses; +import org.hibernate.tool.test.db.DbTestSuite; +import org.junit.jupiter.api.Nested; -@RunWith(DbSuite.class) -@SuiteClasses({ - org.hibernate.tool.jdbc2cfg.CompositeIdOrder.TestCase.class, - org.hibernate.tool.jdbc2cfg.Views.TestCase.class, - org.hibernate.tool.test.db.CommonTestSuite.class -}) -public class TestSuite {} +public class TestSuite { + + @Nested public class OracleTestSuite extends DbTestSuite {} + @Nested public class DialectTestCase extends org.hibernate.cfg.reveng.dialect.TestCase {} + @Nested public class CompositeOrderTestCase extends org.hibernate.tool.jdbc2cfg.CompositeIdOrder.TestCase {} + @Nested public class ViewsTestCase extends org.hibernate.tool.jdbc2cfg.Views.TestCase {} + +} diff --git a/test/oracle/src/test/resources/hibernate.properties b/test/oracle/src/test/resources/hibernate.properties index edbb7ac4c8..8c5eaae5d7 100644 --- a/test/oracle/src/test/resources/hibernate.properties +++ b/test/oracle/src/test/resources/hibernate.properties @@ -1,3 +1,23 @@ +# +# Hibernate Tools, Tooling for your Hibernate Projects +# +# Copyright 2017-2020 Red Hat, Inc. +# +# Licensed under the GNU Lesser General Public License (LGPL), +# version 2.1 or later (the "License"). +# You may not use this file except in compliance with the License. +# You may read the licence in the 'lgpl.txt' file in the root folder of +# project or obtain a copy at +# +# http://www.gnu.org/licenses/lgpl-2.1.html +# +# 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. +# + hibernate.dialect org.hibernate.dialect.Oracle12cDialect hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver hibernate.connection.username HTT diff --git a/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/create.sql b/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/create.sql new file mode 100644 index 0000000000..e04b390dc2 --- /dev/null +++ b/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/create.sql @@ -0,0 +1 @@ +CREATE TABLE person ( id NUMBER(2) PRIMARY KEY, a_varchar2_char VARCHAR2(10 CHAR), a_varchar2_byte VARCHAR2(10 BYTE), a_varchar_char VARCHAR(10 CHAR), a_varchar_byte VARCHAR(10 BYTE), a_nvarchar NVARCHAR2(10), a_char_char CHAR(10 CHAR), a_char_byte CHAR(10 BYTE), a_nchar_char NCHAR(10), a_nchar_byte NCHAR(10), a_number_int NUMBER(10), a_number_dec NUMBER(10, 2), a_float FLOAT(10)) \ No newline at end of file diff --git a/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/drop.sql b/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/drop.sql new file mode 100644 index 0000000000..716ca00b53 --- /dev/null +++ b/test/oracle/src/test/resources/org/hibernate/cfg/reveng/dialect/drop.sql @@ -0,0 +1 @@ +DROP TABLE PERSON \ No newline at end of file diff --git a/test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultDatabaseCollector/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/hbm2x/DefaultSchemaCatalog/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml b/test/oracle/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml similarity index 94% rename from test/oracle/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml rename to test/oracle/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml index bc82183d72..cf708c66bc 100644 --- a/test/oracle/src/main/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml +++ b/test/oracle/src/test/resources/org/hibernate/tool/hbmlint/SchemaAnalyzer/SchemaIssues.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/BasicMultiSchema/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/CompositeIdOrder/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Identity/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/PersistentClasses/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/TernarySchema/drop.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Views/create.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Views/create.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Views/create.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Views/create.sql diff --git a/test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Views/drop.sql b/test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Views/drop.sql similarity index 100% rename from test/oracle/src/main/resources/org/hibernate/tool/jdbc2cfg/Views/drop.sql rename to test/oracle/src/test/resources/org/hibernate/tool/jdbc2cfg/Views/drop.sql diff --git a/test/pom.xml b/test/pom.xml index d962dd5d06..f0db462d78 100644 --- a/test/pom.xml +++ b/test/pom.xml @@ -8,7 +8,7 @@ org.hibernate hibernate-tools-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-parent @@ -17,6 +17,11 @@ Hibernate Tools Integration Tests Parent Project + + true + true + + all @@ -24,11 +29,12 @@ utils nodb common - h2 - hsql - mssql - oracle - mysql + maven-plugin + h2 + hsql + mssql + oracle + mysql @@ -40,9 +46,42 @@ utils nodb common + maven-plugin h2 + + hsql + + utils + common + hsql + + + + mssql + + utils + common + mssql + + + + mysql + + utils + common + mysql + + + + oracle + + utils + common + oracle + + diff --git a/test/utils/pom.xml b/test/utils/pom.xml index b5d0526e35..7e47f321a0 100644 --- a/test/utils/pom.xml +++ b/test/utils/pom.xml @@ -7,7 +7,7 @@ org.hibernate hibernate-tools-tests-parent - 6.0.0-SNAPSHOT + 5.6.16-SNAPSHOT hibernate-tools-tests-utils @@ -17,23 +17,19 @@ Hibernate Tools Test Utilities Project - - junit - junit - compile - com.h2database h2 - - - com.microsoft.sqlserver - mssql-jdbc org.hibernate hibernate-tools + + org.junit.jupiter + junit-jupiter-engine + compile + diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/ConnectionLeakUtil.java b/test/utils/src/main/java/org/hibernate/tools/test/util/ConnectionLeakUtil.java new file mode 100644 index 0000000000..1172675830 --- /dev/null +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/ConnectionLeakUtil.java @@ -0,0 +1,74 @@ +package org.hibernate.tools.test.util; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.opentest4j.AssertionFailedError; + +public class ConnectionLeakUtil { + + public static ConnectionLeakUtil forH2() { + ConnectionLeakUtil result = new ConnectionLeakUtil(); + result.idleConnectionCounter = new H2IdleConnectionCounter(); + return result; + } + + private IdleConnectionCounter idleConnectionCounter = null; + + private int connectionCount = 0; + + public void initialize() { + connectionCount = idleConnectionCounter.countConnections(); + } + + public void assertNoLeaks() { + int leaked = getLeakedConnectionCount(); + if (leaked != 0) { + throw new AssertionFailedError(leaked + " connections are leaked."); + } + } + + private int getLeakedConnectionCount() { + int previousCount = connectionCount; + connectionCount = idleConnectionCounter.countConnections(); + return connectionCount - previousCount; + } + + private static interface IdleConnectionCounter { + int countConnections(); + } + + private static class H2IdleConnectionCounter implements IdleConnectionCounter { + private Connection newConnection() { + try { + return DriverManager.getConnection("jdbc:h2:mem:test", "sa", ""); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + public int countConnections() { + try { + int result = 0; + Connection connection = newConnection(); + Statement statement = connection.createStatement(); + ResultSet resultSet = statement.executeQuery( + "SELECT COUNT(*) " + + "FROM information_schema.sessions " + + "WHERE executing_statement IS NULL"); + while (resultSet.next()) { + result = resultSet.getInt(1); + } + statement.close(); + connection.close(); + return result; + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + } + +} diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/DbSuite.java b/test/utils/src/main/java/org/hibernate/tools/test/util/DbSuite.java deleted file mode 100644 index a14671a4bf..0000000000 --- a/test/utils/src/main/java/org/hibernate/tools/test/util/DbSuite.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.hibernate.tools.test.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.junit.runner.Runner; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.Suite; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.RunnerBuilder; - -public class DbSuite extends Suite { - - public static final String SQL_SCRIPT_ROOT = "org.hibernate.tools.test.db.sqlScriptRoot"; - - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.TYPE) - @Inherited - public @interface SqlScriptRoot { - public String value(); - } - - boolean ignore = false; - String sqlScriptRoot; - - public DbSuite(Class klass, RunnerBuilder builder) throws InitializationError { - super(klass, builder); - ignore = !JdbcUtil.isDatabaseOnline(); - setSqlScriptRoot(klass); - } - - @Override - protected void runChild(Runner runner, final RunNotifier notifier) { - if (!ignore) { - if (sqlScriptRoot != null) { - System.setProperty( - SQL_SCRIPT_ROOT, - sqlScriptRoot); - } - runner.run(notifier); - if (sqlScriptRoot != null) { - System.getProperties().remove( - SQL_SCRIPT_ROOT); - } - } else { - notifier.fireTestIgnored(getDescription()); - } - } - - private void setSqlScriptRoot(Class klass) { - SqlScriptRoot annotation = klass.getAnnotation(SqlScriptRoot.class); - if (annotation != null) { - sqlScriptRoot = annotation.value(); - } - } - -} diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/DummyDatabaseMetadata.java b/test/utils/src/main/java/org/hibernate/tools/test/util/DummyDatabaseMetadata.java new file mode 100644 index 0000000000..e8ddeb61eb --- /dev/null +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/DummyDatabaseMetadata.java @@ -0,0 +1,1116 @@ +package org.hibernate.tools.test.util; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.RowIdLifetime; +import java.sql.SQLException; + +public class DummyDatabaseMetadata implements DatabaseMetaData { + + @Override + public T unwrap(Class iface) throws SQLException { + return null; + } + + @Override + public boolean isWrapperFor(Class iface) throws SQLException { + return false; + } + + @Override + public boolean allProceduresAreCallable() throws SQLException { + return false; + } + + @Override + public boolean allTablesAreSelectable() throws SQLException { + return false; + } + + @Override + public String getURL() throws SQLException { + return null; + } + + @Override + public String getUserName() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isReadOnly() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean nullsAreSortedHigh() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean nullsAreSortedLow() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean nullsAreSortedAtStart() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean nullsAreSortedAtEnd() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getDatabaseProductName() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDatabaseProductVersion() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDriverName() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getDriverVersion() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getDriverMajorVersion() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getDriverMinorVersion() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean usesLocalFiles() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean usesLocalFilePerTable() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMixedCaseIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesUpperCaseIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesLowerCaseIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesMixedCaseIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getIdentifierQuoteString() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSQLKeywords() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getNumericFunctions() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getStringFunctions() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSystemFunctions() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getTimeDateFunctions() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getSearchStringEscape() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getExtraNameCharacters() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean supportsAlterTableWithAddColumn() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsAlterTableWithDropColumn() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsColumnAliasing() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean nullPlusNonNullIsNull() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsConvert() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsConvert(int fromType, int toType) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsTableCorrelationNames() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsDifferentTableCorrelationNames() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsExpressionsInOrderBy() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOrderByUnrelated() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsGroupBy() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsGroupByUnrelated() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsGroupByBeyondSelect() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsLikeEscapeClause() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMultipleResultSets() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMultipleTransactions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsNonNullableColumns() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMinimumSQLGrammar() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCoreSQLGrammar() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsExtendedSQLGrammar() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsANSI92EntryLevelSQL() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsANSI92IntermediateSQL() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsANSI92FullSQL() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsIntegrityEnhancementFacility() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOuterJoins() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsFullOuterJoins() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsLimitedOuterJoins() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getSchemaTerm() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getProcedureTerm() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getCatalogTerm() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isCatalogAtStart() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getCatalogSeparator() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean supportsSchemasInDataManipulation() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSchemasInProcedureCalls() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSchemasInTableDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSchemasInIndexDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCatalogsInDataManipulation() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCatalogsInProcedureCalls() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCatalogsInTableDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCatalogsInIndexDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsPositionedDelete() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsPositionedUpdate() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSelectForUpdate() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsStoredProcedures() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSubqueriesInComparisons() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSubqueriesInExists() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSubqueriesInIns() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsSubqueriesInQuantifieds() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsCorrelatedSubqueries() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsUnion() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsUnionAll() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOpenCursorsAcrossCommit() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOpenCursorsAcrossRollback() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOpenStatementsAcrossCommit() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsOpenStatementsAcrossRollback() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getMaxBinaryLiteralLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxCharLiteralLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnsInGroupBy() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnsInIndex() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnsInOrderBy() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnsInSelect() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxColumnsInTable() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxConnections() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxCursorNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxIndexLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxSchemaNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxProcedureNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxCatalogNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxRowSize() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getMaxStatementLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxStatements() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxTableNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxTablesInSelect() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getMaxUserNameLength() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getDefaultTransactionIsolation() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean supportsTransactions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsTransactionIsolationLevel(int level) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsDataManipulationTransactionsOnly() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean dataDefinitionCausesTransactionCommit() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean dataDefinitionIgnoredInTransactions() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, + String columnNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getSchemas() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getCatalogs() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getTableTypes() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, + String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getTypeInfo() throws SQLException { + return getDummyResultSet(); + } + + @Override + public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean supportsResultSetType(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean ownUpdatesAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean ownDeletesAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean ownInsertsAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean othersUpdatesAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean othersDeletesAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean othersInsertsAreVisible(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean updatesAreDetected(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean deletesAreDetected(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean insertsAreDetected(int type) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsBatchUpdates() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public Connection getConnection() throws SQLException { + return getDummyConnection(); + } + + @Override + public boolean supportsSavepoints() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsNamedParameters() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsMultipleOpenResults() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsGetGeneratedKeys() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, + String attributeNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean supportsResultSetHoldability(int holdability) throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getResultSetHoldability() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getDatabaseMajorVersion() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getDatabaseMinorVersion() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getJDBCMajorVersion() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getJDBCMinorVersion() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getSQLStateType() throws SQLException { + // TODO Auto-generated method stub + return 0; + } + + @Override + public boolean locatorsUpdateCopy() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean supportsStatementPooling() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public RowIdLifetime getRowIdLifetime() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean autoCommitFailureClosesAllResultSets() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + @Override + public ResultSet getClientInfoProperties() throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) + throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, + String columnNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, + String columnNamePattern) throws SQLException { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean generatedKeyAlwaysReturned() throws SQLException { + // TODO Auto-generated method stub + return false; + } + + private Connection DUMMY_CONNECTION = null; + private ResultSet DUMMY_RESULT_SET = null; + + private Connection getDummyConnection() { + if (DUMMY_CONNECTION == null) { + DUMMY_CONNECTION = (Connection)Proxy.newProxyInstance( + HibernateUtil.class.getClassLoader(), + new Class[] { Connection.class }, + new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (method.getName().equals("getMetaData")) { + return DummyDatabaseMetadata.this; + } + return null; + } + }); + } + return DUMMY_CONNECTION; + } + + private ResultSet getDummyResultSet() { + if (DUMMY_RESULT_SET == null) { + DUMMY_RESULT_SET = (ResultSet)Proxy.newProxyInstance( + HibernateUtil.class.getClassLoader(), + new Class[] { ResultSet.class }, + new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (method.getName().equals("next")) { + return false; + } + return null; + } + }); + } + return DUMMY_RESULT_SET; + } + +} diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/HibernateUtil.java b/test/utils/src/main/java/org/hibernate/tools/test/util/HibernateUtil.java index 4a35f908ad..ed2b9c1897 100644 --- a/test/utils/src/main/java/org/hibernate/tools/test/util/HibernateUtil.java +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/HibernateUtil.java @@ -17,6 +17,11 @@ public class HibernateUtil { public static class Dialect extends org.hibernate.dialect.Dialect {} + public static class ConnectionProvider + extends org.hibernate.tools.test.util.internal.ConnectionProvider { + private static final long serialVersionUID = 1L; + } + public static ForeignKey getForeignKey(Table table, String fkName) { ForeignKey result = null; Iterator iter = table.getForeignKeyIterator(); @@ -54,6 +59,7 @@ public static MetadataDescriptor initializeMetadataDescriptor( } Properties properties = new Properties(); properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, HibernateUtil.ConnectionProvider.class.getName()); return MetadataDescriptorFactory.createNativeDescriptor(null, hbmFiles, properties); } diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/JUnitUtil.java b/test/utils/src/main/java/org/hibernate/tools/test/util/JUnitUtil.java index 9dd13f5118..a3a63ad226 100644 --- a/test/utils/src/main/java/org/hibernate/tools/test/util/JUnitUtil.java +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/JUnitUtil.java @@ -1,10 +1,30 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.util.Iterator; -import org.junit.Assert; -import org.junit.ComparisonFailure; +import org.opentest4j.AssertionFailedError; public class JUnitUtil { @@ -18,18 +38,15 @@ public static void assertIteratorContainsExactly( actualAmountOfElements++; iterator.next(); } - if (actualAmountOfElements != expectedAmountOfElements) { - throw new ComparisonFailure( - reason, - Integer.toString(expectedAmountOfElements), - Integer.toString(actualAmountOfElements)); + if (expectedAmountOfElements != actualAmountOfElements) { + throw new AssertionFailedError(reason, expectedAmountOfElements, actualAmountOfElements); } } public static void assertIsNonEmptyFile(File file) { - Assert.assertTrue(file + " does not exist", file.exists() ); - Assert.assertTrue(file + " not a file", file.isFile() ); - Assert.assertTrue(file + " does not have any contents", file.length()>0); + assertTrue(file.exists(), file + " does not exist"); + assertTrue(file.isFile(), file + " not a file"); + assertTrue(file.length()>0, file + " does not have any contents"); } } diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/JdbcUtil.java b/test/utils/src/main/java/org/hibernate/tools/test/util/JdbcUtil.java index 68a920f462..283b280da9 100644 --- a/test/utils/src/main/java/org/hibernate/tools/test/util/JdbcUtil.java +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/JdbcUtil.java @@ -112,8 +112,7 @@ public static void dropDatabase(Object test) { private static String[] getSqls(Object test, String scriptName) { String[] result = new String[] {}; - String location = ResourceUtil.getResourcesLocation(test) + scriptName; - InputStream inputStream = test.getClass().getResourceAsStream(location); + InputStream inputStream = ResourceUtil.resolveResourceLocation(test.getClass(), scriptName); if (inputStream != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/ResourceUtil.java b/test/utils/src/main/java/org/hibernate/tools/test/util/ResourceUtil.java index 8feb6d8768..6e5ff068e8 100644 --- a/test/utils/src/main/java/org/hibernate/tools/test/util/ResourceUtil.java +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/ResourceUtil.java @@ -1,3 +1,22 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; import java.io.File; @@ -7,20 +26,10 @@ public class ResourceUtil { - public static String getResourcesLocation(Object test) { - return '/' + test.getClass().getPackage().getName().replace('.', '/') + '/'; - } - public static void createResources(Object test, String[] resources, File resourcesDir) { try { - String defaultResourceLocation = getResourcesLocation(test); for (String resource : resources) { - String resourceLocation = - (resource.startsWith("/")) - ? resource : defaultResourceLocation + resource; - InputStream inputStream = test - .getClass() - .getResourceAsStream(resourceLocation); + InputStream inputStream = resolveResourceLocation(test.getClass(), resource); File resourceFile = new File(resourcesDir, resource); File parent = resourceFile.getParentFile(); if (!parent.exists()) { @@ -33,4 +42,26 @@ public static void createResources(Object test, String[] resources, File resourc } } + public static InputStream resolveResourceLocation(Class testClass, String resourceName) { + InputStream result = null; + if (resourceName.startsWith("/")) { + result = testClass.getResourceAsStream(resourceName); + } else { + result = resolveRelativeResourceLocation(testClass, resourceName); + } + return result; + } + + private static String getRelativeResourcesRoot(Class testClass) { + return '/' + testClass.getPackage().getName().replace('.', '/') + '/'; + } + + private static InputStream resolveRelativeResourceLocation(Class testClass, String resourceName) { + InputStream result = testClass.getResourceAsStream(getRelativeResourcesRoot(testClass) + resourceName); + if (result == null && testClass.getSuperclass() != Object.class) { + result = resolveRelativeResourceLocation(testClass.getSuperclass(), resourceName); + } + return result; + } + } diff --git a/test/utils/src/main/java/org/hibernate/tools/test/util/internal/ConnectionProvider.java b/test/utils/src/main/java/org/hibernate/tools/test/util/internal/ConnectionProvider.java new file mode 100644 index 0000000000..40ce5c809d --- /dev/null +++ b/test/utils/src/main/java/org/hibernate/tools/test/util/internal/ConnectionProvider.java @@ -0,0 +1,271 @@ +package org.hibernate.tools.test.util.internal; + +import java.sql.Array; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.NClob; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.RowIdLifetime; +import java.sql.SQLClientInfoException; +import java.sql.SQLException; +import java.sql.SQLWarning; +import java.sql.SQLXML; +import java.sql.Savepoint; +import java.sql.Statement; +import java.sql.Struct; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.Executor; + +import org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl; + +public class ConnectionProvider extends UserSuppliedConnectionProviderImpl { + + private static final long serialVersionUID = 1L; + + private static Connection CONNECTION = new Connection(); + private static DatabaseMetaData DATABASE_META_DATA = new DatabaseMetaData(); + + @Override public java.sql.Connection getConnection() throws SQLException { return CONNECTION; } + + @Override public void closeConnection(java.sql.Connection conn) throws SQLException {} + + private static class Connection implements java.sql.Connection { + @Override public T unwrap(Class iface) throws SQLException { return null; } + @Override public boolean isWrapperFor(Class iface) throws SQLException { return false; } + @Override public Statement createStatement() throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return null; } + @Override public CallableStatement prepareCall(String sql) throws SQLException { return null; } + @Override public String nativeSQL(String sql) throws SQLException { return null; } + @Override public void setAutoCommit(boolean autoCommit) throws SQLException {} + @Override public boolean getAutoCommit() throws SQLException { return false; } + @Override public void commit() throws SQLException {} + @Override public void rollback() throws SQLException {} + @Override public void close() throws SQLException {} + @Override public boolean isClosed() throws SQLException { return false; } + @Override public DatabaseMetaData getMetaData() throws SQLException { return DATABASE_META_DATA; } + @Override public void setReadOnly(boolean readOnly) throws SQLException {} + @Override public boolean isReadOnly() throws SQLException { return false; } + @Override public void setCatalog(String catalog) throws SQLException {} + @Override public String getCatalog() throws SQLException { return null; } + @Override public void setTransactionIsolation(int level) throws SQLException {} + @Override public int getTransactionIsolation() throws SQLException { return 0; } + @Override public SQLWarning getWarnings() throws SQLException { return null; } + @Override public void clearWarnings() throws SQLException {} + @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } + @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } + @Override public Map> getTypeMap() throws SQLException { return null; } + @Override public void setTypeMap(Map> map) throws SQLException {} + @Override public void setHoldability(int holdability) throws SQLException {} + @Override public int getHoldability() throws SQLException { return 0; } + @Override public Savepoint setSavepoint() throws SQLException { return null; } + @Override public Savepoint setSavepoint(String name) throws SQLException { return null; } + @Override public void rollback(Savepoint savepoint) throws SQLException {} + @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException {} + @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } + @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return null; } + @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return null; } + @Override public Clob createClob() throws SQLException { return null; } + @Override public Blob createBlob() throws SQLException { return null; } + @Override public NClob createNClob() throws SQLException { return null; } + @Override public SQLXML createSQLXML() throws SQLException { return null; } + @Override public boolean isValid(int timeout) throws SQLException { return false;} + @Override public void setClientInfo(String name, String value) throws SQLClientInfoException {} + @Override public void setClientInfo(Properties properties) throws SQLClientInfoException {} + @Override public String getClientInfo(String name) throws SQLException { return null; } + @Override public Properties getClientInfo() throws SQLException { return null; } + @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return null; } + @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return null; } + @Override public void setSchema(String schema) throws SQLException {} + @Override public String getSchema() throws SQLException { return null; } + @Override public void abort(Executor executor) throws SQLException {} + @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {} + @Override public int getNetworkTimeout() throws SQLException { return 0; } + } + + private static class DatabaseMetaData implements java.sql.DatabaseMetaData { + @Override public T unwrap(Class iface) throws SQLException { return null; } + @Override public boolean isWrapperFor(Class iface) throws SQLException { return false; } + @Override public boolean allProceduresAreCallable() throws SQLException { return false; } + @Override public boolean allTablesAreSelectable() throws SQLException { return false; } + @Override public String getURL() throws SQLException { return null; } + @Override public String getUserName() throws SQLException { return null; } + @Override public boolean isReadOnly() throws SQLException { return false; } + @Override public boolean nullsAreSortedHigh() throws SQLException { return false; } + @Override public boolean nullsAreSortedLow() throws SQLException { return false; } + @Override public boolean nullsAreSortedAtStart() throws SQLException { return false; } + @Override public boolean nullsAreSortedAtEnd() throws SQLException { return false; } + @Override public String getDatabaseProductName() throws SQLException { return null; } + @Override public String getDatabaseProductVersion() throws SQLException { return null; } + @Override public String getDriverName() throws SQLException { return null; } + @Override public String getDriverVersion() throws SQLException { return null; } + @Override public int getDriverMajorVersion() { return 0; } + @Override public int getDriverMinorVersion() { return 0; } + @Override public boolean usesLocalFiles() throws SQLException { return false; } + @Override public boolean usesLocalFilePerTable() throws SQLException { return false; } + @Override public boolean supportsMixedCaseIdentifiers() throws SQLException { return false; } + @Override public boolean storesUpperCaseIdentifiers() throws SQLException { return false; } + @Override public boolean storesLowerCaseIdentifiers() throws SQLException { return false; } + @Override public boolean storesMixedCaseIdentifiers() throws SQLException { return false; } + @Override public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { return false; } + @Override public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { return false; } + @Override public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { return false; } + @Override public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { return false; } + @Override public String getIdentifierQuoteString() throws SQLException { return null; } + @Override public String getSQLKeywords() throws SQLException { return null; } + @Override public String getNumericFunctions() throws SQLException { return null; } + @Override public String getStringFunctions() throws SQLException { return null; } + @Override public String getSystemFunctions() throws SQLException { return null; } + @Override public String getTimeDateFunctions() throws SQLException { return null; } + @Override public String getSearchStringEscape() throws SQLException { return null; } + @Override public String getExtraNameCharacters() throws SQLException { return null; } + @Override public boolean supportsAlterTableWithAddColumn() throws SQLException { return false; } + @Override public boolean supportsAlterTableWithDropColumn() throws SQLException { return false; } + @Override public boolean supportsColumnAliasing() throws SQLException { return false; } + @Override public boolean nullPlusNonNullIsNull() throws SQLException { return false; } + @Override public boolean supportsConvert() throws SQLException { return false; } + @Override public boolean supportsConvert(int fromType, int toType) throws SQLException { return false; } + @Override public boolean supportsTableCorrelationNames() throws SQLException { return false; } + @Override public boolean supportsDifferentTableCorrelationNames() throws SQLException { return false; } + @Override public boolean supportsExpressionsInOrderBy() throws SQLException { return false; } + @Override public boolean supportsOrderByUnrelated() throws SQLException { return false; } + @Override public boolean supportsGroupBy() throws SQLException { return false; } + @Override public boolean supportsGroupByUnrelated() throws SQLException { return false; } + @Override public boolean supportsGroupByBeyondSelect() throws SQLException { return false; } + @Override public boolean supportsLikeEscapeClause() throws SQLException { return false; } + @Override public boolean supportsMultipleResultSets() throws SQLException { return false; } + @Override public boolean supportsMultipleTransactions() throws SQLException { return false; } + @Override public boolean supportsNonNullableColumns() throws SQLException { return false; } + @Override public boolean supportsMinimumSQLGrammar() throws SQLException { return false; } + @Override public boolean supportsCoreSQLGrammar() throws SQLException { return false; } + @Override public boolean supportsExtendedSQLGrammar() throws SQLException { return false; } + @Override public boolean supportsANSI92EntryLevelSQL() throws SQLException { return false; } + @Override public boolean supportsANSI92IntermediateSQL() throws SQLException { return false; } + @Override public boolean supportsANSI92FullSQL() throws SQLException { return false; } + @Override public boolean supportsIntegrityEnhancementFacility() throws SQLException { return false; } + @Override public boolean supportsOuterJoins() throws SQLException { return false; } + @Override public boolean supportsFullOuterJoins() throws SQLException { return false; } + @Override public boolean supportsLimitedOuterJoins() throws SQLException { return false; } + @Override public String getSchemaTerm() throws SQLException { return null; } + @Override public String getProcedureTerm() throws SQLException { return null; } + @Override public String getCatalogTerm() throws SQLException { return null; } + @Override public boolean isCatalogAtStart() throws SQLException { return false; } + @Override public String getCatalogSeparator() throws SQLException { return null; } + @Override public boolean supportsSchemasInDataManipulation() throws SQLException { return false; } + @Override public boolean supportsSchemasInProcedureCalls() throws SQLException { return false; } + @Override public boolean supportsSchemasInTableDefinitions() throws SQLException { return false; } + @Override public boolean supportsSchemasInIndexDefinitions() throws SQLException { return false; } + @Override public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { return false; } + @Override public boolean supportsCatalogsInDataManipulation() throws SQLException { return false; } + @Override public boolean supportsCatalogsInProcedureCalls() throws SQLException { return false; } + @Override public boolean supportsCatalogsInTableDefinitions() throws SQLException { return false; } + @Override public boolean supportsCatalogsInIndexDefinitions() throws SQLException { return false; } + @Override public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { return false; } + @Override public boolean supportsPositionedDelete() throws SQLException { return false; } + @Override public boolean supportsPositionedUpdate() throws SQLException { return false; } + @Override public boolean supportsSelectForUpdate() throws SQLException { return false; } + @Override public boolean supportsStoredProcedures() throws SQLException { return false; } + @Override public boolean supportsSubqueriesInComparisons() throws SQLException { return false; } + @Override public boolean supportsSubqueriesInExists() throws SQLException { return false; } + @Override public boolean supportsSubqueriesInIns() throws SQLException { return false; } + @Override public boolean supportsSubqueriesInQuantifieds() throws SQLException { return false; } + @Override public boolean supportsCorrelatedSubqueries() throws SQLException { return false; } + @Override public boolean supportsUnion() throws SQLException { return false; } + @Override public boolean supportsUnionAll() throws SQLException { return false; } + @Override public boolean supportsOpenCursorsAcrossCommit() throws SQLException { return false; } + @Override public boolean supportsOpenCursorsAcrossRollback() throws SQLException { return false; } + @Override public boolean supportsOpenStatementsAcrossCommit() throws SQLException { return false; } + @Override public boolean supportsOpenStatementsAcrossRollback() throws SQLException { return false; } + @Override public int getMaxBinaryLiteralLength() throws SQLException { return 0; } + @Override public int getMaxCharLiteralLength() throws SQLException { return 0; } + @Override public int getMaxColumnNameLength() throws SQLException { return 0; } + @Override public int getMaxColumnsInGroupBy() throws SQLException { return 0; } + @Override public int getMaxColumnsInIndex() throws SQLException { return 0; } + @Override public int getMaxColumnsInOrderBy() throws SQLException { return 0; } + @Override public int getMaxColumnsInSelect() throws SQLException { return 0; } + @Override public int getMaxColumnsInTable() throws SQLException { return 0; } + @Override public int getMaxConnections() throws SQLException { return 0; } + @Override public int getMaxCursorNameLength() throws SQLException { return 0; } + @Override public int getMaxIndexLength() throws SQLException { return 0; } + @Override public int getMaxSchemaNameLength() throws SQLException { return 0; } + @Override public int getMaxProcedureNameLength() throws SQLException { return 0; } + @Override public int getMaxCatalogNameLength() throws SQLException { return 0; } + @Override public int getMaxRowSize() throws SQLException { return 0; } + @Override public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { return false; } + @Override public int getMaxStatementLength() throws SQLException { return 0; } + @Override public int getMaxStatements() throws SQLException { return 0; } + @Override public int getMaxTableNameLength() throws SQLException { return 0; } + @Override public int getMaxTablesInSelect() throws SQLException { return 0; } + @Override public int getMaxUserNameLength() throws SQLException { return 0; } + @Override public int getDefaultTransactionIsolation() throws SQLException { return 0; } + @Override public boolean supportsTransactions() throws SQLException { return false; } + @Override public boolean supportsTransactionIsolationLevel(int level) throws SQLException { return false; } + @Override public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { return false; } + @Override public boolean supportsDataManipulationTransactionsOnly() throws SQLException { return false; } + @Override public boolean dataDefinitionCausesTransactionCommit() throws SQLException { return false; } + @Override public boolean dataDefinitionIgnoredInTransactions() throws SQLException { return false; } + @Override public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { return null; } + @Override public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { return null; } + @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { return null; } + @Override public ResultSet getSchemas() throws SQLException { return null; } + @Override public ResultSet getCatalogs() throws SQLException { return null; } + @Override public ResultSet getTableTypes() throws SQLException { return null; } + @Override public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return null; } + @Override public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { return null; } + @Override public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { return null; } + @Override public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { return null; } + @Override public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { return null; } + @Override public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { return null; } + @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { return null; } + @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { return null; } + @Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { return null; } + @Override public ResultSet getTypeInfo() throws SQLException { return null; } + @Override public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { return null; } + @Override public boolean supportsResultSetType(int type) throws SQLException { return false; } + @Override public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { return false; } + @Override public boolean ownUpdatesAreVisible(int type) throws SQLException { return false; } + @Override public boolean ownDeletesAreVisible(int type) throws SQLException { return false; } + @Override public boolean ownInsertsAreVisible(int type) throws SQLException { return false; } + @Override public boolean othersUpdatesAreVisible(int type) throws SQLException { return false; } + @Override public boolean othersDeletesAreVisible(int type) throws SQLException { return false; } + @Override public boolean othersInsertsAreVisible(int type) throws SQLException { return false; } + @Override public boolean updatesAreDetected(int type) throws SQLException { return false; } + @Override public boolean deletesAreDetected(int type) throws SQLException { return false; } + @Override public boolean insertsAreDetected(int type) throws SQLException { return false; } + @Override public boolean supportsBatchUpdates() throws SQLException { return false; } + @Override public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { return null; } + @Override public Connection getConnection() throws SQLException { return CONNECTION; } + @Override public boolean supportsSavepoints() throws SQLException { return false; } + @Override public boolean supportsNamedParameters() throws SQLException { return false; } + @Override public boolean supportsMultipleOpenResults() throws SQLException { return false; } + @Override public boolean supportsGetGeneratedKeys() throws SQLException { return false; } + @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { return null; } + @Override public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException {return null;} + @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { return null; } + @Override public boolean supportsResultSetHoldability(int holdability) throws SQLException { return false; } + @Override public int getResultSetHoldability() throws SQLException { return 0; } + @Override public int getDatabaseMajorVersion() throws SQLException { return 0; } + @Override public int getDatabaseMinorVersion() throws SQLException { return 0; } + @Override public int getJDBCMajorVersion() throws SQLException { return 0; } + @Override public int getJDBCMinorVersion() throws SQLException { return 0; } + @Override public int getSQLStateType() throws SQLException { return 0; } + @Override public boolean locatorsUpdateCopy() throws SQLException { return false; } + @Override public boolean supportsStatementPooling() throws SQLException { return false; } + @Override public RowIdLifetime getRowIdLifetime() throws SQLException { return null; } + @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { return null; } + @Override public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { return false; } + @Override public boolean autoCommitFailureClosesAllResultSets() throws SQLException { return false; } + @Override public ResultSet getClientInfoProperties() throws SQLException { return null; } + @Override public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { return null; } + @Override public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { return null; } + @Override public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { return null; } + @Override public boolean generatedKeyAlwaysReturned() throws SQLException { return false; } + } + +} diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/AntUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/AntUtilTest.java index 9bd9ead03a..c5cf8a6cbe 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/AntUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/AntUtilTest.java @@ -1,15 +1,36 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.File; import java.nio.file.Files; import org.apache.tools.ant.Target; import org.apache.tools.ant.taskdefs.Echo; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class AntUtilTest { @@ -18,21 +39,21 @@ public class AntUtilTest { " \n" + " \n"; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + @Test public void testCreateProject() throws Exception { - File buildFile = new File(temporaryFolder.getRoot(), "build.xml"); + File buildFile = new File(outputFolder, "build.xml"); Files.copy(new ByteArrayInputStream(BUILD_XML.getBytes()), buildFile.toPath()); AntUtil.Project project = AntUtil.createProject(buildFile); - Assert.assertEquals("AntUtilTest", project.getName()); + assertEquals("AntUtilTest", project.getName()); } @Test public void testGetLog() { AntUtil.Project project = new AntUtil.Project(); - Assert.assertNull(project.logBuffer); + assertNull(project.logBuffer); Target target = new Target(); target.setName("foobar"); Echo echo = new Echo(); @@ -41,7 +62,7 @@ public void testGetLog() { target.addTask(echo); project.addTarget(target); project.executeTarget("foobar"); - Assert.assertTrue(AntUtil.getLog(project).contains("Executing foobar")); + assertTrue(AntUtil.getLog(project).contains("Executing foobar")); } } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/ConnectionLeakUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/ConnectionLeakUtilTest.java new file mode 100644 index 0000000000..da6c09daec --- /dev/null +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/ConnectionLeakUtilTest.java @@ -0,0 +1,58 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2018-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ConnectionLeakUtilTest { + + private ConnectionLeakUtil connectionLeakUtil = null; + + @BeforeEach + public void before() { + connectionLeakUtil = ConnectionLeakUtil.forH2(); + connectionLeakUtil.initialize(); + } + + @Test + public void testLeaks() throws Exception { + try { + DriverManager.getConnection("jdbc:h2:mem:test", "sa", ""); + connectionLeakUtil.assertNoLeaks(); + throw new RuntimeException("should not happen"); + } catch (AssertionError e) { + assertEquals("1 connections are leaked.", e.getMessage()); + } + } + + @Test + public void testNoLeaks() throws Exception { + Connection connection = DriverManager.getConnection("jdbc:h2:mem:test", "sa", ""); + connection.close(); + connectionLeakUtil.assertNoLeaks(); + } + +} diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/DbSuiteTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/DbSuiteTest.java deleted file mode 100644 index 11e6986817..0000000000 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/DbSuiteTest.java +++ /dev/null @@ -1,171 +0,0 @@ -package org.hibernate.tools.test.util; - -import java.io.File; -import java.io.FileWriter; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Properties; - -import org.hibernate.tools.test.util.DbSuite.SqlScriptRoot; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.Description; -import org.junit.runner.RunWith; -import org.junit.runner.Runner; -import org.junit.runner.notification.RunListener; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.Suite.SuiteClasses; -import org.junit.runners.model.RunnerBuilder; - - -public class DbSuiteTest { - - private class DummyRunner extends Runner { - @Override - public Description getDescription() { - return Description.EMPTY; - } - @Override - public void run(RunNotifier notifier) { - sqlScriptRoot = System.getProperty(DbSuite.SQL_SCRIPT_ROOT); - notifier.fireTestStarted(getDescription());; - } - } - - private class DummyListener extends RunListener { - boolean isStarted = false; - boolean isIgnored = false; - public void testStarted(Description description) throws Exception { - isStarted = true; - } - public void testIgnored(Description description) throws Exception { - isIgnored = true; - } - } - - public class DummyTest { - @Test - public void testDummy() { - Assert.assertTrue(true); - } - } - - @RunWith(DbSuite.class) - @SuiteClasses(DummyTest.class) - public class FirstSuite {} - - @RunWith(DbSuite.class) - @SuiteClasses(DummyTest.class) - @SqlScriptRoot("foo.bar") - public class SecondSuite {} - - private class TestRunnerBuilder extends RunnerBuilder { - @Override - public Runner runnerForClass(Class testClass) throws Throwable { - return null; - } - } - - private DbSuite dbSuite; - private String sqlScriptRoot = null; - - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - - @Before - public void setUp() throws Exception { - createHibernateProperties("sa", "", "jdbc:h2:mem:test"); - setUpClassLoader(); - } - - @After - public void tearDown() throws Exception { - restoreClassLoader(); - } - - @Test - public void testDbSuiteConstruction() throws Exception { - dbSuite = new DbSuite(FirstSuite.class, new TestRunnerBuilder()); - Assert.assertNull(dbSuite.sqlScriptRoot); - Assert.assertFalse(dbSuite.ignore); - dbSuite = new DbSuite(SecondSuite.class, new TestRunnerBuilder()); - Assert.assertEquals("foo.bar", dbSuite.sqlScriptRoot); - Assert.assertFalse(dbSuite.ignore); - new File(temporaryFolder.getRoot(), "hibernate.properties").delete(); - createHibernateProperties("foo", "bar", "jdbc:sqlserver://org.foo.bar:1433"); - dbSuite = new DbSuite(FirstSuite.class, new TestRunnerBuilder()); - Assert.assertNull(dbSuite.sqlScriptRoot); - Assert.assertTrue(dbSuite.ignore); - dbSuite = new DbSuite(SecondSuite.class, new TestRunnerBuilder()); - Assert.assertEquals("foo.bar", dbSuite.sqlScriptRoot); - Assert.assertTrue(dbSuite.ignore); - } - - @Test - public void testRunChild() throws Exception { - dbSuite = new DbSuite(FirstSuite.class, new TestRunnerBuilder()); - Runner runner = new DummyRunner(); - RunNotifier notifier = new RunNotifier(); - DummyListener listener = new DummyListener(); - notifier.addListener(listener); - dbSuite.ignore = true; - listener.isStarted = false; - listener.isIgnored = false; - dbSuite.runChild(runner, notifier); - Assert.assertFalse(listener.isStarted); - Assert.assertTrue(listener.isIgnored); - dbSuite.ignore = false; - dbSuite.sqlScriptRoot = null; - listener.isStarted = false; - listener.isIgnored = false; - dbSuite.runChild(runner, notifier); - Assert.assertTrue(listener.isStarted); - Assert.assertFalse(listener.isIgnored); - Assert.assertNull(sqlScriptRoot); - dbSuite.ignore = false; - dbSuite.sqlScriptRoot = "foo.bar"; - listener.isStarted = false; - listener.isIgnored = false; - dbSuite.runChild(runner, notifier); - Assert.assertTrue(listener.isStarted); - Assert.assertFalse(listener.isIgnored); - Assert.assertEquals("foo.bar", sqlScriptRoot); - } - - private void createHibernateProperties( - String user, - String password, - String url) - throws Exception { - Properties properties = new Properties(); - properties.put("hibernate.connection.username", user); - properties.put("hibernate.connection.password", password); - properties.put("hibernate.connection.url", url); - File outputFolder = temporaryFolder.getRoot(); - File propertiesFile = new File(outputFolder, "hibernate.properties"); - FileWriter writer = new FileWriter(propertiesFile); - properties.store(writer, null); - writer.close(); - } - - private void setUpClassLoader() throws Exception { - ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader( - new URLClassLoader( - new URL[] { temporaryFolder.getRoot().toURI().toURL() }, - currentClassLoader)); - } - - private void restoreClassLoader() { - URLClassLoader currentClassLoader = - (URLClassLoader)Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(currentClassLoader.getParent()); - } - - - -} diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/FileUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/FileUtilTest.java index e10e3b6f19..86bd1605cf 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/FileUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/FileUtilTest.java @@ -1,35 +1,56 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class FileUtilTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); @Test public void testFindFirstString() throws Exception { String resource = "/org/hibernate/tools/test/util/FileUtilTest.resource"; File file = new File(getClass().getResource(resource).toURI()); - Assert.assertEquals("or would it be a bar test?", FileUtil.findFirstString("bar", file)); - Assert.assertNull(FileUtil.findFirstString("foobar", file)); - Assert.assertEquals("This is a foo test", FileUtil.findFirstString("test", file)); - Assert.assertEquals("And a third line...", FileUtil.findFirstString("third", file)); + assertEquals("or would it be a bar test?", FileUtil.findFirstString("bar", file)); + assertNull(FileUtil.findFirstString("foobar", file)); + assertEquals("This is a foo test", FileUtil.findFirstString("test", file)); + assertEquals("And a third line...", FileUtil.findFirstString("third", file)); } @Test public void testGenerateNoopComparator() throws Exception { - FileUtil.generateNoopComparator(temporaryFolder.getRoot()); - File pkg = new File(temporaryFolder.getRoot(), "comparator"); - Assert.assertTrue(pkg.isDirectory() && pkg.exists()); + FileUtil.generateNoopComparator(outputFolder); + File pkg = new File(outputFolder, "comparator"); + assertTrue(pkg.isDirectory() && pkg.exists()); File comp = new File(pkg, "NoopComparator.java"); - Assert.assertTrue(comp.isFile() && comp.exists()); - Assert.assertEquals( + assertTrue(comp.isFile() && comp.exists()); + assertEquals( "public class NoopComparator implements Comparator {", FileUtil.findFirstString("NoopComparator", comp)); } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/HibernateUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/HibernateUtilTest.java index b4d6459ea5..3292845735 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/HibernateUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/HibernateUtilTest.java @@ -1,5 +1,29 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.io.File; import java.util.Collections; import java.util.Properties; @@ -11,29 +35,33 @@ import org.hibernate.mapping.Table; import org.hibernate.tool.api.metadata.MetadataDescriptor; import org.hibernate.tool.api.metadata.MetadataDescriptorFactory; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.hibernate.tools.test.util.internal.ConnectionProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class HibernateUtilTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - + @TempDir + public File outputFolder = new File("output"); + @Test public void testGetForeignKey() { Table table = new Table(); - Assert.assertNull(HibernateUtil.getForeignKey(table, "foo")); - Assert.assertNull(HibernateUtil.getForeignKey(table, "bar")); - table.createForeignKey("foo", Collections.emptyList(), null, null); - Assert.assertNotNull(HibernateUtil.getForeignKey(table, "foo")); - Assert.assertNull(HibernateUtil.getForeignKey(table, "bar")); + assertNull(HibernateUtil.getForeignKey(table, "foo")); + assertNull(HibernateUtil.getForeignKey(table, "bar")); + table.createForeignKey("foo", Collections.emptyList(), "Bar", null); + assertNotNull(HibernateUtil.getForeignKey(table, "foo")); + assertNull(HibernateUtil.getForeignKey(table, "bar")); } @Test public void testDialectInstantiation() { - Assert.assertNotNull(new HibernateUtil.Dialect()); + assertNotNull(new HibernateUtil.Dialect()); + } + + @Test + public void testConnectionProviderInstantiation() { + assertNotNull(new HibernateUtil.ConnectionProvider()); } @Test @@ -42,26 +70,27 @@ public void testInitializeConfiguration() { .initializeMetadataDescriptor( this, new String[] { "HelloWorld.hbm.xml" }, - temporaryFolder.getRoot()) + outputFolder) .createMetadata(); - Assert.assertSame( + assertSame( HibernateUtil.Dialect.class, metadata.getDatabase().getDialect().getClass()); - Assert.assertNotNull(metadata.getEntityBinding("HelloWorld")); + assertNotNull(metadata.getEntityBinding("HelloWorld")); } @Test public void testAddAnnotatedClass() { Properties properties = new Properties(); - properties.setProperty(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.DIALECT, HibernateUtil.Dialect.class.getName()); + properties.put(AvailableSettings.CONNECTION_PROVIDER, ConnectionProvider.class.getName()); MetadataDescriptor metadataDescriptor = MetadataDescriptorFactory .createNativeDescriptor(null, null, properties); - Assert.assertNull(metadataDescriptor + assertNull(metadataDescriptor .createMetadata() .getEntityBinding( "org.hibernate.tools.test.util.HibernateUtilTest$Dummy")); HibernateUtil.addAnnotatedClass(metadataDescriptor, Dummy.class); - Assert.assertNotNull(metadataDescriptor + assertNotNull(metadataDescriptor .createMetadata() .getEntityBinding( "org.hibernate.tools.test.util.HibernateUtilTest$Dummy")); diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/JUnitUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/JUnitUtilTest.java index 74da50ec16..acb8b20800 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/JUnitUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/JUnitUtilTest.java @@ -1,11 +1,32 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.util.ArrayList; -import org.junit.Assert; -import org.junit.ComparisonFailure; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.opentest4j.AssertionFailedError; public class JUnitUtilTest { @@ -16,21 +37,21 @@ public void testAssertIteratorContainsExactly() { list.add("bar"); try { JUnitUtil.assertIteratorContainsExactly("less", list.iterator(), 1); - Assert.fail(); - } catch (ComparisonFailure e) { - Assert.assertTrue(e.getMessage().contains("less")); + fail(); + } catch (AssertionFailedError e) { + assertTrue(e.getMessage().contains("less")); } try { JUnitUtil.assertIteratorContainsExactly("more", list.iterator(), 3); - Assert.fail(); - } catch (ComparisonFailure e) { - Assert.assertTrue(e.getMessage().contains("more")); + fail(); + } catch (AssertionFailedError e) { + assertTrue(e.getMessage().contains("more")); } try { JUnitUtil.assertIteratorContainsExactly("exact", list.iterator(), 2); - Assert.assertTrue(true); - } catch (ComparisonFailure e) { - Assert.fail(); + assertTrue(true); + } catch (AssertionFailedError e) { + fail(); } } @@ -41,14 +62,14 @@ public void testAssertIsNonEmptyFile() throws Exception { try { JUnitUtil.assertIsNonEmptyFile(exists); } catch (Exception e) { - Assert.fail(); + fail(); } File doesNotExist = new File(exists.getAbsolutePath() + '_'); try { JUnitUtil.assertIsNonEmptyFile(doesNotExist); - Assert.fail(); + fail(); } catch (AssertionError e) { - Assert.assertTrue(e.getMessage().contains("does not exist")); + assertTrue(e.getMessage().contains("does not exist")); } } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/JavaUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/JavaUtilTest.java index 828302fc09..b07c1974f5 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/JavaUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/JavaUtilTest.java @@ -1,12 +1,32 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.FileWriter; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class JavaUtilTest { @@ -22,13 +42,12 @@ public class JavaUtilTest { " public Foo foo; "+ "} "; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); @Test public void testCompile() throws Exception { - File testFolder = temporaryFolder.getRoot(); - File packageFolder = new File(testFolder, "org/hibernate/tool/test"); + File packageFolder = new File(outputFolder, "org/hibernate/tool/test"); packageFolder.mkdirs(); File fooFile = new File(packageFolder, "Foo.java"); FileWriter fileWriter = new FileWriter(fooFile); @@ -38,11 +57,11 @@ public void testCompile() throws Exception { fileWriter = new FileWriter(barFile); fileWriter.write(BAR_STRING); fileWriter.close(); - Assert.assertFalse(new File(packageFolder, "Foo.class").exists()); - Assert.assertFalse(new File(packageFolder, "Bar.class").exists()); - JavaUtil.compile(testFolder); - Assert.assertTrue(new File(packageFolder, "Foo.class").exists()); - Assert.assertTrue(new File(packageFolder, "Bar.class").exists()); + assertFalse(new File(packageFolder, "Foo.class").exists()); + assertFalse(new File(packageFolder, "Bar.class").exists()); + JavaUtil.compile(outputFolder); + assertTrue(new File(packageFolder, "Foo.class").exists()); + assertTrue(new File(packageFolder, "Bar.class").exists()); } } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/JdbcUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/JdbcUtilTest.java index 997a9c7d19..4acf7162ee 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/JdbcUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/JdbcUtilTest.java @@ -1,5 +1,30 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; import java.io.FileWriter; import java.lang.reflect.InvocationHandler; @@ -13,26 +38,24 @@ import java.sql.ResultSet; import java.util.Properties; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class JdbcUtilTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); - @Before + @BeforeEach public void setUp() throws Exception { clearConnectionTable(); createHibernateProperties("sa", "", "jdbc:h2:mem:test"); setUpClassLoader(); } - @After + @AfterEach public void tearDown() throws Exception { clearConnectionTable(); restoreClassLoader(); @@ -41,17 +64,17 @@ public void tearDown() throws Exception { @Test public void testGetConnectionProperties() throws Exception { Properties properties = JdbcUtil.getConnectionProperties(); - Assert.assertEquals("jdbc:h2:mem:test", properties.get("url")); - Assert.assertEquals("sa", properties.get("user")); - Assert.assertEquals("", properties.get("password")); + assertEquals("jdbc:h2:mem:test", properties.get("url")); + assertEquals("sa", properties.get("user")); + assertEquals("", properties.get("password")); } @Test public void testEstablishJdbcConnection() throws Exception { - Assert.assertNull(JdbcUtil.CONNECTION_TABLE.get(this)); + assertNull(JdbcUtil.CONNECTION_TABLE.get(this)); JdbcUtil.establishJdbcConnection(this); Connection connection = JdbcUtil.CONNECTION_TABLE.get(this); - Assert.assertFalse(connection.isClosed()); + assertFalse(connection.isClosed()); } @Test @@ -59,11 +82,11 @@ public void testReleaseJdbcConnection() throws Exception { Connection connection = DriverManager.getConnection("jdbc:h2:mem:test;USER=sa"); JdbcUtil.CONNECTION_TABLE.put(this, connection); - Assert.assertNotNull(JdbcUtil.CONNECTION_TABLE.get(this)); - Assert.assertFalse(connection.isClosed()); + assertNotNull(JdbcUtil.CONNECTION_TABLE.get(this)); + assertFalse(connection.isClosed()); JdbcUtil.releaseJdbcConnection(this); - Assert.assertNull(JdbcUtil.CONNECTION_TABLE.get(this)); - Assert.assertTrue(connection.isClosed()); + assertNull(JdbcUtil.CONNECTION_TABLE.get(this)); + assertTrue(connection.isClosed()); } @Test @@ -74,7 +97,7 @@ public void testExecuteDDL() throws Exception { ResultSet resultSet = connection .getMetaData() .getTables(null, null, "FOO", null); - Assert.assertFalse(resultSet.next()); + assertFalse(resultSet.next()); String[] sqls = new String[] { "CREATE TABLE FOO (BAR INT)" }; @@ -82,7 +105,7 @@ public void testExecuteDDL() throws Exception { resultSet = connection .getMetaData() .getTables(null, null, "FOO", null); - Assert.assertTrue(resultSet.next()); + assertTrue(resultSet.next()); } @Test @@ -96,19 +119,19 @@ public void testToIdentifier() throws Exception { connectionInvocationHandler ); JdbcUtil.CONNECTION_TABLE.put(this, connection); metaDataInvocationHandler.whichCase = "MIXED"; - Assert.assertEquals("Foo", JdbcUtil.toIdentifier(this, "Foo")); + assertEquals("Foo", JdbcUtil.toIdentifier(this, "Foo")); metaDataInvocationHandler.whichCase = "UPPER"; - Assert.assertEquals("FOO", JdbcUtil.toIdentifier(this, "Foo")); + assertEquals("FOO", JdbcUtil.toIdentifier(this, "Foo")); metaDataInvocationHandler.whichCase = "LOWER"; - Assert.assertEquals("foo", JdbcUtil.toIdentifier(this, "Foo")); + assertEquals("foo", JdbcUtil.toIdentifier(this, "Foo")); } @Test public void testIsDatabaseOnline() throws Exception { - Assert.assertTrue(JdbcUtil.isDatabaseOnline()); - new File(temporaryFolder.getRoot(), "hibernate.properties").delete(); + assertTrue(JdbcUtil.isDatabaseOnline()); + new File(outputFolder, "hibernate.properties").delete(); createHibernateProperties("foo", "bar", "jdbc:sqlserver://org.foo.bar:1433"); - Assert.assertFalse(JdbcUtil.isDatabaseOnline()); + assertFalse(JdbcUtil.isDatabaseOnline()); } private void clearConnectionTable() throws Exception { @@ -127,7 +150,6 @@ private void createHibernateProperties( properties.put("hibernate.connection.username", user); properties.put("hibernate.connection.password", password); properties.put("hibernate.connection.url", url); - File outputFolder = temporaryFolder.getRoot(); File propertiesFile = new File(outputFolder, "hibernate.properties"); FileWriter writer = new FileWriter(propertiesFile); properties.store(writer, null); @@ -138,7 +160,7 @@ private void setUpClassLoader() throws Exception { ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( new URLClassLoader( - new URL[] { temporaryFolder.getRoot().toURI().toURL() }, + new URL[] { outputFolder.toURI().toURL() }, currentClassLoader)); } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/ResourceUtilTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/ResourceUtilTest.java index 9c2c50ff47..5a72c059f3 100644 --- a/test/utils/src/test/java/org/hibernate/tools/test/util/ResourceUtilTest.java +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/ResourceUtilTest.java @@ -1,33 +1,59 @@ +/* + * Hibernate Tools, Tooling for your Hibernate Projects + * + * Copyright 2017-2020 Red Hat, Inc. + * + * Licensed under the GNU Lesser General Public License (LGPL), + * version 2.1 or later (the "License"). + * You may not use this file except in compliance with the License. + * You may read the licence in the 'lgpl.txt' file in the root folder of + * project or obtain a copy at + * + * http://www.gnu.org/licenses/lgpl-2.1.html + * + * 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.tools.test.util; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.File; +import java.io.InputStream; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class ResourceUtilTest { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @TempDir + public File outputFolder = new File("output"); @Test - public void testGetResourcesLocation() { - Assert.assertEquals( - "/org/hibernate/tools/test/util/", - ResourceUtil.getResourcesLocation(this)); + public void testResolveResourceLocation() { + InputStream is = ResourceUtil.resolveResourceLocation(getClass(), "/foo"); + assertNull(is); + is = ResourceUtil.resolveResourceLocation(getClass(), "/ResourceUtilTest.resource"); + assertNotNull(is); + is = ResourceUtil.resolveResourceLocation(getClass(), "HelloWorld.foo.bar"); + assertNull(is); + is = ResourceUtil.resolveResourceLocation(getClass(), "HelloWorld.hbm.xml"); } @Test public void testCreateResources() { String[] resources = new String[] { "HelloWorld.hbm.xml" }; - File outputFolder = temporaryFolder.getRoot(); File helloWorldFile = new File(outputFolder, "HelloWorld.hbm.xml"); - Assert.assertFalse(helloWorldFile.exists()); + assertFalse(helloWorldFile.exists()); ResourceUtil.createResources(this, resources, outputFolder); - Assert.assertTrue(helloWorldFile.exists()); - Assert.assertTrue(FileUtil + assertTrue(helloWorldFile.exists()); + assertTrue(FileUtil .findFirstString("class", helloWorldFile) .contains("HelloWorld")); } diff --git a/test/utils/src/test/java/org/hibernate/tools/test/util/internal/ConnectionProviderTest.java b/test/utils/src/test/java/org/hibernate/tools/test/util/internal/ConnectionProviderTest.java new file mode 100644 index 0000000000..337157884a --- /dev/null +++ b/test/utils/src/test/java/org/hibernate/tools/test/util/internal/ConnectionProviderTest.java @@ -0,0 +1,31 @@ +package org.hibernate.tools.test.util.internal; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.junit.jupiter.api.Test; + +public class ConnectionProviderTest { + + private ConnectionProvider connectionProvider = new org.hibernate.tools.test.util.internal.ConnectionProvider(); + + @Test + public void testGetConnection() { + try { + assertNotNull(connectionProvider.getConnection()); + } catch (Exception e) { + fail(); + } + } + + @Test + public void testCloseConnection() { + try { + connectionProvider.closeConnection(null); + } catch (Exception e) { + fail(); + } + } + +} diff --git a/test/utils/src/test/resources/ResourceUtilTest.resource b/test/utils/src/test/resources/ResourceUtilTest.resource new file mode 100644 index 0000000000..e69de29bb2 diff --git a/test/utils/src/test/resources/org/hibernate/tools/test/util/HelloWorld.hbm.xml b/test/utils/src/test/resources/org/hibernate/tools/test/util/HelloWorld.hbm.xml index 82989a5032..9588363b32 100644 --- a/test/utils/src/test/resources/org/hibernate/tools/test/util/HelloWorld.hbm.xml +++ b/test/utils/src/test/resources/org/hibernate/tools/test/util/HelloWorld.hbm.xml @@ -1,7 +1,7 @@ + "https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> diff --git a/test/utils/src/test/resources/org/hibernate/tools/test/util/JUnitUtilTest.resource b/test/utils/src/test/resources/org/hibernate/tools/test/util/JUnitUtilTest.resource deleted file mode 100644 index 52f9fc2b35..0000000000 --- a/test/utils/src/test/resources/org/hibernate/tools/test/util/JUnitUtilTest.resource +++ /dev/null @@ -1 +0,0 @@ -the file is not empty \ No newline at end of file diff --git a/test/utils/src/test/resources/org/hibernate/tools/test/util/hibernate.properties b/test/utils/src/test/resources/org/hibernate/tools/test/util/hibernate.properties deleted file mode 100644 index da21574937..0000000000 --- a/test/utils/src/test/resources/org/hibernate/tools/test/util/hibernate.properties +++ /dev/null @@ -1 +0,0 @@ -hibernate.dialect org.hibernate.tools.test.util.HibernateUtil$Dialect \ No newline at end of file