diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index 68e24de4..b903da55 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -3,27 +3,31 @@
name: Java CI
-on: [push, pull_request,workflow_dispatch]
+on: [push, pull_request, workflow_dispatch]
jobs:
build:
runs-on: ubuntu-latest
+ if: "!contains(github.event.head_commit.message, '__CI__')"
env:
- luceeVersion: light-6.0.0.316-SNAPSHOT
+ luceeVersion: 6.0.0.316-SNAPSHOT
steps:
- uses: actions/checkout@v3
+
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
java-version: '11'
- distribution: 'adopt'
+ distribution: 'temurin'
+
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2
key: lucee-script-runner-maven-cache
+
- name: Cache Lucee files
uses: actions/cache@v3
with:
@@ -31,32 +35,125 @@ jobs:
key: lucee-downloads-${{ env.luceeVersion }}
restore-keys: |
lucee-downloads
+
- name: Build with Ant
run: ant -noinput -verbose -buildfile build.xml
+
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: hibernate-lex
path: dist/*.lex
+
- name: Checkout Lucee
uses: actions/checkout@v3
with:
repository: lucee/lucee
path: lucee
- - name: Run Lucee Test Suite (testFilter="orm")
+
+ - name: Run Lucee Test Suite (testLabels="orm")
uses: lucee/script-runner@main
with:
webroot: ${{ github.workspace }}/lucee/test
execute: /bootstrap-tests.cfm
- luceeVersion: ${{ env.luceeVersion }}
+ luceeVersion: light-${{ env.luceeVersion }}
extensionDir: ${{ github.workspace }}/dist
env:
testLabels: orm
testAdditional: ${{ github.workspace }}/tests
+
- name: Publish Test Results
uses: EnricoMi/publish-unit-test-result-action@v1
if: always()
with:
- files: ${{ github.workspace }}/lucee/test/reports/junit-test-results.xml
+ files: ${{ github.workspace }}/lucee/test/reports/junit-test-results-${{env.luceeVersion}}.xml
check_name: "Test Results"
+ maven_build:
+ runs-on: ubuntu-latest
+ if: "!contains(github.event.head_commit.message, '__CI__')"
+ strategy:
+ fail-fast: false
+ matrix:
+ lucee_version: ["5.3.10.97"]
+ java_version: [ "8", "11", "17" ]
+
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up JDK
+ uses: actions/setup-java@v3
+ with:
+ java-version: '${{matrix.java_version}}'
+ distribution: 'temurin'
+
+ - name: Build with Maven
+ run: mvn --batch-mode -f pom.xml -Dlucee.version=${{matrix.lucee_version}} -Djdk.version=${{matrix.java_version}} compile
+
+ javadocs:
+ runs-on: ubuntu-latest
+ if: "!contains(github.event.head_commit.message, '__CI__')"
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Set up JDK 8
+ uses: actions/setup-java@v3
+ with:
+ java-version: '8'
+ distribution: 'temurin'
+
+ - name: Cache Maven packages
+ uses: actions/cache@v3
+ with:
+ path: ~/.m2
+ key: maven-cache
+
+ - name: Generate Javadocs
+ run: mvn --batch-mode -f pom.xml javadoc:javadoc
+
+ - name: Get Project Version for Javadocs Versioning
+ id: current_version
+ # For Maven builds (future)
+ # run: echo "VERSION=`mvn help:evaluate -Dexpression=project.version -q -DforceStdout`" >> $GITHUB_ENV
+ # For Ant builds (still the default)
+ run: echo "VERSION=`ant -silent -quiet version`" >> $GITHUB_ENV
+
+ - name: Upload API Docs to S3
+ uses: jakejarvis/s3-sync-action@master
+ with:
+ args: --acl public-read
+ env:
+ AWS_S3_BUCKET: ${{ secrets.AWS_APIDOCS_BUCKET }}
+ AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_ACCESS_SECRET }}
+ SOURCE_DIR: "docs"
+ DEST_DIR: "lucee/hibernate-extension/${{ env.VERSION }}/"
+
+ format:
+ runs-on: ubuntu-latest
+ if: "!contains(github.event.head_commit.message, '__CI__')"
+ steps:
+ - uses: actions/checkout@v3
+ with:
+ token: ${{secrets.GH_TOKEN}}
+
+ - name: Set up JDK 11
+ uses: actions/setup-java@v3
+ with:
+ java-version: '11'
+ distribution: 'temurin'
+
+ - name: Cache Maven packages
+ uses: actions/cache@v3
+ with:
+ path: ~/.m2
+ key: maven-cache
+
+ - name: Format Java source code
+ run: mvn --batch-mode -f pom.xml formatter:format
+
+ - name: Commit formatting changes
+ uses: stefanzweifel/git-auto-commit-action@v4
+ with:
+ file_pattern: "docs"
+ commit_message: "🤖 CI: Auto-format Java source __CI__"
diff --git a/.gitignore b/.gitignore
index 695e4b88..7ed7aa96 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,24 @@
-/dist
-temp
-**/.DS_Store
+# Editor and OS artifacts
+.vscode
+.DS_Store
**/.svn/
/*.project
va specific
+
+# build files/dist
+/bin
+/build
+/dist
+/temp
*.class
-target
-target/*
+/target
*.lock
*.DS_Store
-/cache
\ No newline at end of file
+/cache
+/docs
+
+# Test artifacts
+WEB-INF/
+
+# Lucee source for CFML tests
+/lucee
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..30fb67ea
--- /dev/null
+++ b/README.md
@@ -0,0 +1,78 @@
+# Lucee Hibernate Extension (ORM)
+
+[![Java CI](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml/badge.svg?branch=5.4)](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml) 5.4
+
+[![Java CI](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml/badge.svg?branch=3.5.5)](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml) 3.5.5
+
+[![Java CI](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml/badge.svg)](https://github.com/lucee/extension-hibernate/actions/workflows/main.yml) Master
+
+* A [Hibernate ORM](https://hibernate.org/orm/) wrapper for the [Lucee CFML language](https://www.lucee.org/)
+
+* Issues: https://luceeserver.atlassian.net/issues/?jql=labels%20%3D%20%22orm%22
+* Documentation: https://docs.lucee.org/categories/orm.html
+
+## Contributing
+
+You will need to install the following for extension development:
+
+* Java 1.8+ (JRE and JDK)
+* [ant](https://www.osradar.com/install-apache-ant-ubuntu-20-04/) (for building the extension `.lex` file)
+* [maven](https://linuxize.com/post/how-to-install-apache-maven-on-ubuntu-20-04/) (for other automated tooling)
+* [Docker](https://docs.docker.com/engine/install/) and [Docker Compose](https://docs.docker.com/compose/install/) (for managing test database servers)
+
+### Getting Started
+
+1. Install the repo - `git clone git@github.com:lucee/extension-hibernate.git`
+2. Make changes..
+3. [Build extension via `ant dist`](#building)
+4. Test via `./test.sh` (See [#Testing](#testing) for more info)
+
+**Before you send a PR:**
+
+1. Don't forget to run tests!
+ 1. (if you can't get tests to pass, ask for help!)
+2. Format java source code: `mvn formatter:format`
+
+## Building
+
+Using ant builds (for now):
+
+* `ant clean` - clean build directories
+* `ant compile` - compile code
+* `ant dist` - Package the extension into a Lucee-installable `.lex` extension file
+
+Using the Maven builds:
+
+* `mvn test` run java-based (junit) tests
+* `mvn javadoc:javadoc` generate java docs
+* `mvn formatter:format` [format java source](https://code.revelc.net/formatter-maven-plugin/usage.html)
+* `mvn verify` Run OWASP dependency checker to look for vulnerabilities
+
+## Testing
+
+See Lucee documentation on [testing-a-lucee-extension-locally](https://docs.lucee.org/guides/working-with-source/building-and-testing-extensions.html#testing-a-lucee-extension-locally).
+
+To run CFML tests against the extension:
+
+1. Check out [lucee/Lucee](https://github.com/lucee/lucee) to the parent directory - `git clone git@github.com:lucee/Lucee.git ../lucee`
+2. Check out [lucee/script-runner](https://github.com/lucee/script-runner) to the parent directory - `git clone git@github.com:lucee/Lucee.git ../script-runner`.
+
+Next, start the test databases using the Docker-compose setup:
+
+```bash
+cd tests && docker-compose up
+```
+
+This will start Postgres, MySQL, and MSSQL containers using the credentials specified in `tests/.env`.
+
+Finally, you can run tests from the extension root:
+
+```bash
+./test.sh
+```
+
+To build a .lex and test it immediately, chain `ant dist` and `./test.sh`:
+
+```bash
+ant dist && ./test.sh
+```
\ No newline at end of file
diff --git a/build.xml b/build.xml
index 0d04fb43..069f8268 100644
--- a/build.xml
+++ b/build.xml
@@ -13,7 +13,10 @@
-
+
+
+
+
@@ -38,6 +41,10 @@
+
+
+ ${bundleversion}${build.number}${versionAppendix}
+
@@ -78,10 +85,19 @@ lucee-core-version: "${luceeCoreVersion}"
+
+
+
+
+
-
+
+
+
+
+
- 4.0.0
-
- org.lucee
- extension.hibernate
- 5.0.0.99-SNAPSHOT
- jar
-
- Extension Hibernate
- Lucee Extension for Hibernate ORM Engine.
- http://maven.lucee.org/extension/hibernate
-
-
-
- hibernate.extension
+
+ 4.0.0
+
+ org.lucee
+ hibernate.extension
+
+ 5.4.29.75-BETA
+ bundle
+
+ Ortus Hibernate Extension
+ Lucee Extension for Hibernate ORM Engine.
+ http://maven.lucee.org/extension/hibernate
+
+
+ Hibernate ORM Engine
+ hibernate-extensionFAD1E8CB-4F45-4184-86359145767C29DE
- Hibernate ORM (Hibernate in short) is an object-relational mapping library for the Java language,
- providing a framework for mapping an object-oriented domain model to a traditional relational database.
- Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related
- database accesses with high-level object handling functions.
+ Hibernate ORM (Hibernate in short) is an object-relational mapping library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.org.lucee.extension.orm.hibernate.HibernateORMEngine
-
-
-
-
- The GNU Lesser General Public License, Version 2.1
- http://www.gnu.org/licenses/lgpl-2.1.txt
- repo
-
-
-
-
-
- micstriit
- Michael Offner
- michael@lucee.org
- Lucee Association Switzerland
- http://lucee.org
-
- Project-Administrator
- Developer
-
- +1
-
-
-
-
+
+
+ 5.3.10.97
+ 5.4.29.Final
+
+
+ 1.8
+ ${jdk.version}
+ ${jdk.version}
+ UTF-8
+
+
+
+
+ The GNU Lesser General Public License, Version 2.1
+ http://www.gnu.org/licenses/lgpl-2.1.txt
+ repo
+
+
+
+
+
+ micstriit
+ Michael Offner
+ michael@lucee.org
+ Lucee Association Switzerland
+ http://lucee.org
+
+ Project-Administrator
+ Developer
+
+ +1
+
+
+
+
-
+
+ org.codehaus.mojo
+ build-helper-maven-plugin
+ 3.2.0
+
+
+ add-source
+ generate-sources
+
+ add-source
+
+
+
+
+
+
+
+
+
+
-
-
- org.apache.maven.plugins
- maven-source-plugin
-
-
- attach-sources
-
- jar
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
-
-
- attach-javadocs
-
- jar
-
-
-
-
-
-
-
-
-
+ org.apache.maven.plugins
- maven-jar-plugin
- 2.6
- true
-
+ maven-javadoc-plugin
+ 3.4.1
+
+
+ attach-javadocs
+
+ jar
+
+
+
-
- .*
-
-
- src/main/java/META-INF/MANIFEST.MF
-
- ${main.class}
-
-
-
-
-
+ ${project.basedir}
+ docs
+ -Xdoclint:none
+ false
+
+
+
org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 1.7
-
-
-
-
-
-
-
-
-
-
+ maven-compiler-plugin
+ 3.3
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 5.1.8
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ org.lucee.extension.orm.hibernate
+
+ org.lucee.extension.orm.hibernate,org.lucee.extension.orm.hibernate.jdbc
+
+ net.sf.ehcache.hibernate
+ org.lucee.hibernate;bundle-version=5.4.29.1,org.lucee.antlr;bundle-version=2.7.6,org.lucee.dom4j;bundle-version=1.6.1,org.lucee.javassist;bundle-version=3.9.0.GA,org.lucee.jta;bundle-version=1.1.0,slf4j.api;bundle-version=1.7.36,org.apache.commons.collections;bundle-version=3.2.1,org.lucee.xml.apis;bundle-version=1.4.1,com.fasterxml.classmate;bundle-version=1.5.1,net.bytebuddy.byte-buddy;bundle-version=1.10.21,org.lucee.hibernate-annotations;bundle-version=5.1.2.Final,javax.persistence-api;bundle-version=2.2,org.lucee.hibernate-ehcache;bundle-version=5.4.29.Final,org.lucee.ehcache;bundle-version=2.10.6,jakarta.xml.bind-api;bundle-version=2.3.3,org.glassfish.jaxb.runtime;bundle-version=2.3.4
+
+
+ <_noimportjava>true
+
+
+
+
+
+
+ com.github.ekryd.echo-maven-plugin
+ echo-maven-plugin
+ 1.3.2
+ false
+
+
+ copy-starter-manifest
+ package
+
+ echo
+
+
+ /${project.basedir}/source/java/src/META-INF/EXTENSION.MF
+
+ target/META-INF/MANIFEST.MF
+
+
+
+ append-manifest-entries
+ package
+
+ echo
+
+
+
+name: ${name}
+id: ${id}
+description: ${description}
+version: ${project.version}
+orm: [{'class':'${class}','name':'${project.artifactId}','version':'${project.version}'}]
+lucee-core-version: ${lucee.version}
+
+
+ target/META-INF/MANIFEST.MF
+
+ true
+
+
+
+
-
-
-
- junit
- junit
- 4.12
-
+
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+
+
+
+
+ source/lex.xml
+
+
+
+
+
+
+
+ com.coderplus.maven.plugins
+ copy-rename-maven-plugin
+ 1.0.1
+
+
+ copy-file
+ package
+
+ rename
+
+
+ ${project.build.directory}/${project.build.finalName}-lex.zip
+ ${project.build.directory}/${project.build.finalName}.lex
+
+
+
+
+
+
+
+
+ org.owasp
+ dependency-check-maven
+ 7.3.2
+
+
+
+ check
+
+
+
+
+
+ net.revelc.code.formatter
+ formatter-maven-plugin
+ 2.21.0
+
+
+ ${project.basedir}/source/java/src/
+ ${project.basedir}/src/test/java
+
+
+
+
-
- org.lucee
- lucee
-
-
- org.lucee
- lucee
- 3.1.0
-
+
-
-
- compile
- org.apache.felix
- org.apache.felix.framework
- 4.2.1
-
-
- javax.servlet
- javax.servlet-api
- 3.1.0
-
-
- javax.servlet.jsp
- jsp-api
- 2.2
-
-
- javax.el
- javax.el-api
- 3.0.0
-
-
- org.apache.ant
- ant
- 1.9.5
-
-
-
- org.apache.tika
- tika-core
- 1.10
-
-
-
-
-
- org.apache.sanselan
- sanselan
- 0.97-incubator
-
-
-
-
-
- org.apache.commons
- codec
- 1.6.0
-
-
-
-
-
-
-
-
-
- org.apache.commons
- commons-collections4
- 4.0
-
-
-
-
-
-
-
- org.apache.commons
- commons-compress
- 1.9
-
-
-
-
- commons-discovery
- commons-discovery
- 0.5
-
-
-
-
- org.apache.commons
- commons-email
- 1.2
-
-
-
-
- org.apache.commons
- fileupload
- 1.2.1
-
-
-
-
- org.lucee
- commons-httpclient
- 3.1
-
-
-
-
- commons-io
- commons-io
- 2.4
-
-
-
-
- commons-lang
- commons-lang
- 2.6
-
-
-
-
-
-
-
- org.apache.commons.logging
- adapters
- 1.1.1
-
-
-
-
- org.apache.commons.logging
- api
- jar
- 1.1.1
-
-
-
- org.apache.commons
- logging
- jar
- 1.1.1
-
+
+
+
+ org.junit
+ junit-bom
+ 5.9.2
+ pom
+ import
+
+
+
-
-
- commons-net
- commons-net
- 3.3
-
-
-
+
- org.apache
- oro
- jar
- 2.0.8
+ org.junit.jupiter
+ junit-jupiter
+ 5.9.2
+ test
-
-
- log4j
- log4j
- 1.2.17
-
-
-
-
- apache.poi.ooxml
- schemas
- jar
- 3.8.0
-
-
-
- org.apache.poi
- ooxml
- jar
- 3.8.0
-
-
-
- apache.poi.tm
- extractors
- jar
- 3.8.0
-
-
-
- org.apache
- poi
- jar
- 3.8.0
-
-
-
- apache.ws.axis
- ant
- jar
- 1.4.0
-
-
-
- apache.ws
- axis
- jar
- 1.4.0.L004
-
-
-
- apache.xml
- xalan
- jar
- 2.7.1
-
-
-
- apache.xml
- xerces
- jar
- 2.11.0
-
-
-
- backport.util
- concurrent
- jar
- 2.2.0
-
-
-
- bcprov
- jdk14
- jar
- 1.36.0
-
-
-
-
- edu.oswego.cs.gee
- concurrent
- jar
- 1.3.3
-
-
-
-
- net.sf.ehcache
- ehcache
- 2.10.0
-
-
-
-
-
- ESAPI
- ESAPI
- jar
- 2.1.0
-
-
-
-
- flex.messaging
- common
- jar
- 3.3.0.22497
-
-
-
- flex.messaging
- core
- jar
- 3.3.0.22497
-
-
-
- flex.messaging
- opt
- jar
- 3.3.0.22497
-
-
-
- flex.messaging
- proxy
- jar
- 3.3.0.22497
-
-
-
- flex.messaging
- remoting
- jar
- 3.3.0.22497
-
-
-
- fusiondebug.api
- server
- jar
- 1.0.20
-
-
-
- apache.http.components
- client
- jar
- 4.5.0.0001L
-
-
-
- apache.http.components
- core
- jar
- 4.4.1
-
-
-
- apache.http.components
- mime
- jar
- 4.5.0
-
-
-
- hsqldb
- hsqldb
- jar
- 1.8.0
-
-
-
- icepdf
- core
- jar
- 3.1.0.3
-
-
- jacob
- jacob
- jar
- 1.16.1
+ org.mockito
+ mockito-inline
+ 4.0.0
+ test
-
- javaparser
- javaparser
- jar
- 1.0.8
-
-
-
- javasysmon
- javasysmon
- jar
- 0.3.3
+ org.mockito
+ mockito-junit-jupiter
+ 4.0.0
+ test
-
-
- org.samba
- jcifs
- jar
- 1.3.17
-
-
-
- jcommon
- jcommon
- jar
- 1.0.10
-
-
-
- jencrypt
- jencrypt
- jar
- 1.4.2.04
-
-
-
- jffmpeg
- jffmpeg
- jar
- 1.4.2.09
-
-
-
- jfreechart
- patch
- jar
- 1.0.12
-
-
-
- jfreechart
- jfreechart
- jar
- 1.0.12
-
-
-
+
- org.joda
- time
- jar
- 2.1.0
-
-
-
- jpedal
- gpl
- jar
- 3.51.12
+ org.lucee
+ lucee
+ ${lucee.version}
+
+ provided
-
-
- lowagie
- itext
- jar
- 2.1.2.1
-
-
-
- metadata
- extractor
- jar
- 2.6.4
+ org.lucee
+ txw2
+ 2011.8.9
-
-
- org.ow2.asm
- asm-all
- 4.2
-
-
-
+
- ojdbc14
- ojdbc14
- jar
- 0.0.0
+ org.hibernate
+ hibernate-core
+ ${hibernate.version}
-
+
- openamf
- astranslator
- jar
- 1.5.8
-
-
-
- openamf
- openamf
- jar
- 1.5.8
-
-
-
- org.apache.pdfbox
- pdfbox
- 1.8.9
-
-
-
-
-
- org.apache.pdfbox
- fontbox
- 1.8.9
-
-
-
-
- org.apache.pdfbox
- jempbox
- 1.8.9
-
-
-
-
- PDFRenderer
- PDFRenderer
- jar
- 1.0.5
-
-
-
- resolver
- resolver
- jar
- 1.2.0
-
-
-
- serializer
- serializer
- jar
- 2.7.1
-
+ org.hibernate
+ hibernate-ehcache
+ ${hibernate.version}
-
-
- org.slf4j
- slf4j-api
- 1.7.12
-
-
-
-
- org.slf4j
- slf4j-nop
- 1.7.12
-
-
-
-
- ss
- css2
- jar
- 0.9.4
-
-
-
- stax
- api
- jar
- 1.0.1
+
+
+
+ org.glassfish.jaxb
+ txw2
+
+
-
-
- sun
- activation
- jar
- 1.1.0
-
-
-
- sun.jai
- codec
- jar
- 1.1.2
-
-
-
- sun.jai
- core
- jar
- 1.2.1
-
-
-
- sun.jndi
- ldap
- jar
- 1.2.4
-
-
-
- sun.jndi
- ldapbp
- jar
- 1.2.4
-
-
-
- sun.jndi
- ldapsec
- jar
- 1.2.4
-
-
-
- sun.jndi
- providerutil
- jar
- 1.2.4
-
-
-
- sun
- mail
- jar
- 1.3.3.01
-
-
-
- sun.security
- jaas
- jar
- 1.2.4
-
-
-
- sun.xml
- jaxrpc
- jar
- 1.2.1
-
-
-
- sun.xml
- wsdl4j
- jar
- 1.5.1
-
-
-
- sun.xml
- saaj
- jar
- 1.2.1
-
-
-
- tagsoup
- tagsoup
- jar
- 1.2.1
-
-
+
w3cdomjar1.1.0
-
-
- xdb
- xdb
- jar
- 1.0.0
-
-
-
- xml
- apis
- jar
- 1.3.2
-
-
-
- xmlbeans
- xmlbeans
- jar
- 2.3.0.r540734
-
-
+
+
- xmlparserv2
- xmlparserv2
- jar
- 1.2.2
+ com.sun.xml.bind
+ jaxb-osgi
+ 2.3.7
+
+
repohttps://raw.githubusercontent.com/lucee/mvn/master/releases
-
- snapi
- https://oss.sonatype.org/content/repositories/snapshots
-
+
-
- https://github.com/lucee/Lucee
- scm:git:git://github.com/lucee/Lucee.git
- scm:git:git@github.com:lucee/Lucee.git
- ${project.version}
-
-
-
-
- ossrh
- https://oss.sonatype.org/service/local/staging/deploy/maven2/
-
-
- ossrh
- https://oss.sonatype.org/content/repositories/snapshots
-
-
+
+ https://github.com/michaelborn/extension-hibernate
+ scm:git:git://github.com/michaelborn/extension-hibernate.git
+ scm:git:git@github.com:michaelborn/extension-hibernate.git
+ ${project.version}
+
+
+
+
+ ossrh
+ https://oss.sonatype.org/service/local/staging/deploy/maven2/
+
+
+ ossrh
+ https://oss.sonatype.org/content/repositories/snapshots
+
+
\ No newline at end of file
diff --git a/source/fld/ormFunctions.fld b/source/fld/ormFunctions.fld
new file mode 100644
index 00000000..2b7e6d36
--- /dev/null
+++ b/source/fld/ormFunctions.fld
@@ -0,0 +1,476 @@
+
+
+
+
+ 1.00
+ Hibernate-extension
+ https://github.com/lucee/extension-hibernate
+ Hibernate
+
+ Functions to interact with Hibernate
+
+
+
+
+ EntityDelete
+ org.lucee.extension.orm.functions.EntityDelete
+ Deletes the record from the database for the specified entity.
+EntityDelete(entity)
+
+ name
+ object
+ Yes
+ Name of the entity being deleted.
+
+
+ void
+
+
+
+
+
+ entityLoad
+ org.lucee.extension.orm.functions.EntityLoad
+ Loads and returns an array of entities of the specified entityName.
+EntityLoad (entityName, filterCriteria [,unique]
+EntityLoad(entityName, filterCriteria, sortOrder [, options])
+
+ name
+ string
+ Yes
+ Name of the entity to be loaded.
+
+
+ idOrFilter
+ id,filter
+ any
+ no
+ The primary key value of the entity that must be loaded or Key-value pair (Struct) of property names and values.
+ If there are more than one key-value pair, then the AND operator is used.If specified, loads and returns an array of entities of the specified entity name that matches the filterCriteria.
+
+
+ uniqueOrOrder
+ unique,order
+ any
+ no
+ when the second argument is an id then this argument defines the boolean "unique" otherwise it defines the order.
+
+- unique:
+If unique is set to true, then the entity is returned.
+If you are sure that only one record exists that matches this filterCriteria, then you can specify unique=true, so that a single entity is returned instead of an array.
+If you set unique=true and multiple records are returned, then an exception occurs.
+
+- order:
+String used to specify the sortOrder of the entities that are returned.If specified, loads and returns an array of entities that satisfy the filterCriteria sorted as specified by the sortOrder.
+
+
+
+
+ options
+ any
+ no
+
+The following options to customize the output (only used when second argument is "id"):
+- ignoreCase: Ignores the case of sort order when set to true. Use only if you specify the sortOrder parameter.
+- offset: Specifies the position from which to retrieve the objects.
+- maxResults: Specifies the maximum number of objects to be retrieved.
+- cacheable: Whether the result has to be cached in the secondary cache. Default is false.
+- cacheName: Name of the cache in secondary cache.
+- timeout: Specifies the timeout value (in seconds) for the query.
+
+
+
+ any
+
+
+
+
+
+ EntityLoadByPK
+ org.lucee.extension.orm.functions.EntityLoadByPK
+ Loads and returns an array of objects for given primary key.
+
+ name
+ string
+ Yes
+ Name of the entity to be loaded.
+
+
+ id
+ any
+ yes
+ The primary key value of the entity that must be loaded
+
+
+ unique
+ boolean
+ no
+ If unique is set to true, then the entity is returned.
+If you are sure that only one record exists that matches this filtercriteria, then you can specify unique=true, so that a single entity is returned instead of an array.
+If you set unique=true and multiple records are returned, then an exception occurs.
+
+
+ any
+
+
+
+
+
+ EntityLoadByExample
+ org.lucee.extension.orm.functions.EntityLoadByExample
+ Loads and returns an array of objects that match the sample entity.
+entityLoadByExample(sampleEntity,[unique])
+
+ sampleEntity
+ object
+ yes
+ Name of the sample entity that is used to match and filter similar entities to load.
+
+
+ unique
+ boolean
+ no
+ If unique is set to true, then the entity is returned.
+If you are sure that only one record exists that matches this filtercriteria, then you can specify unique=true, so that a single entity is returned instead of an array.
+If you set unique=true and multiple records are returned, then an exception occurs.
+
+
+ any
+
+
+
+
+
+ EntityMerge
+ org.lucee.extension.orm.functions.EntityMerge
+ Attaches given entity to current ORM session
+
+ entity
+ any
+ yes
+ The entity that must be attached to the ORM session.
+
+
+ any
+
+
+
+
+
+ EntityNew
+ org.lucee.extension.orm.functions.EntityNew
+ Creates a new instance of the persistent CFC with the entity name that you provide.
+
+ entityName
+ string
+ yes
+ Name of the instance being created.
+
+
+ properties
+ struct
+ no
+ a struct containing data to populate the entity properties.
+
+
+ any
+
+
+
+
+
+ EntityNameArray
+ org.lucee.extension.orm.functions.EntityNameArray
+ return all loaded entities as array
+
+ array
+
+
+
+
+
+ EntityNameList
+ org.lucee.extension.orm.functions.EntityNameList
+ return all loaded entities as string list
+
+ delimiter
+ string
+ no
+ delimiter used for the list
+
+
+ string
+
+
+
+
+
+ EntityReload
+ org.lucee.extension.orm.functions.EntityReload
+ Reloads data for an entity that is already loaded.
+
+ entity
+ object
+ yes
+ name of the entity
+
+
+ void
+
+
+
+
+
+ EntitySave
+ org.lucee.extension.orm.functions.EntitySave
+ Saves or updates data of the entity and all related entities to the database.
+EntitySave(entity, [forceInsert])
+
+ entity
+ object
+ yes
+ Name of the entity that must be saved in the database.
+
+
+ forceInsert
+ boolean
+ no
+ If true, then Lucee always tries to insert the entity as a new record.
+
+
+ void
+
+
+
+
+
+ EntityToQuery
+ org.lucee.extension.orm.functions.EntityToQuery
+ Converts the input entity object or the input array of entity objects to a query object.
+
+ entity
+ object
+ yes
+ entity or array of entities
+
+
+ name
+ string
+ no
+ name of the entities
+
+
+ query
+
+
+
+
+
+
+ ORMExecuteQuery
+ org.lucee.extension.orm.functions.ORMExecuteQuery
+ Runs the HQL on the default data source specified for the application.
+
+ hql
+ string
+ yes
+
+
+
+ paramsOrUnique
+ params
+ any
+ no
+
+
+
+ uniqueOrQueryOptions
+ unique
+ any
+ no
+
+
+
+ queryOptions
+ any
+ no
+
+
+
+ any
+
+
+
+
+ ORMClearSession
+ org.lucee.extension.orm.functions.ORMClearSession
+ Removes all the entities that are loaded or created in the session. This clears the first level cache and removes the objects that are not yet saved to the database.
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ void
+
+
+
+
+ ORMCloseSession
+ org.lucee.extension.orm.functions.ORMCloseSession
+ Closes the current ORM session.
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ void
+
+
+
+
+ ORMCloseAllSessions
+ org.lucee.extension.orm.functions.ORMCloseAllSessions
+ Closes all ORM session.
+
+ void
+
+
+
+
+ ORMEvictCollection
+ org.lucee.extension.orm.functions.ORMEvictCollection
+ This will remove all the entries with the specified relation/collection name in the specified component.
+ormEvictCollection(componentName,relationName,[id])
+
+
+ entityName
+ String
+ yes
+
+
+
+ collectionName
+ String
+ yes
+
+
+
+ primaryKey
+ String
+ no
+
+
+
+
+ void
+
+
+
+
+ ORMEvictEntity
+ org.lucee.extension.orm.functions.ORMEvictEntity
+ This will remove all the entries for the specified component name from the entity cache.
+ormEvictEntity(componentName,[id])
+
+
+ entityName
+ String
+ yes
+
+
+
+ primaryKey
+ String
+ no
+
+
+
+
+ void
+
+
+
+
+ ORMEvictQueries
+ org.lucee.extension.orm.functions.ORMEvictQueries
+ This will remove all the queries from the named query cache.
+If name is not specified, all queries from default cache will be removed.
+ormEvictQueries([cacheName])
+
+ cacheName
+ cache,region
+ String
+ no
+
+
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ void
+
+
+
+
+ ORMFlush
+ org.lucee.extension.orm.functions.ORMFlush
+ Flushes the current ORM session. ORMFlush flushes all the pending CRUD operations in that request. Any changes made in the objects, in the current ORM session, are saved to the database.
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ void
+
+
+
+
+ ORMGetSession
+ org.lucee.extension.orm.functions.ORMGetSession
+ Returns the current ORM session
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ object
+
+
+
+
+ ORMGetSessionFactory
+ org.lucee.extension.orm.functions.ORMGetSessionFactory
+ Returns ORM session factory instance
+
+ datasource
+ string
+ no
+ datasource used for the session, if nor defined the datasource defined in application.cfc/cfapplication is used.
+
+
+ object
+
+
+
+
+ ORMReload
+ org.lucee.extension.orm.functions.ORMReload
+ Returns ORM session factory instance
+
+ void
+
+
+
+
\ No newline at end of file
diff --git a/source/java/.project b/source/java/.project
index 1d65b9dd..0e3a1937 100644
--- a/source/java/.project
+++ b/source/java/.project
@@ -14,4 +14,15 @@
org.eclipse.jdt.core.javanature
+
+
+ 1674334952723
+
+ 30
+
+ org.eclipse.core.resources.regexFilterMatcher
+ node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__
+
+
+
diff --git a/source/java/src/META-INF/EXTENSION.MF b/source/java/src/META-INF/EXTENSION.MF
new file mode 100644
index 00000000..9d885be5
--- /dev/null
+++ b/source/java/src/META-INF/EXTENSION.MF
@@ -0,0 +1 @@
+Manifest-Version: 1.0
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityDelete.java b/source/java/src/org/lucee/extension/orm/functions/EntityDelete.java
new file mode 100755
index 00000000..b15cc765
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityDelete.java
@@ -0,0 +1,48 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * Delete an entity or array of entities with this CFML built-in function.
+ */
+public class EntityDelete extends BIF {
+ public static String call(PageContext pc, Object obj) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ session.delete(pc, obj);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 1) return call(pc, args[0]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityDelete", 1, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityLoad.java b/source/java/src/org/lucee/extension/orm/functions/EntityLoad.java
new file mode 100755
index 00000000..f43eb1a7
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityLoad.java
@@ -0,0 +1,106 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.type.Struct;
+
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to load an ORM entity or entities by ID or criteria
+ */
+public class EntityLoad extends BIF {
+
+ public static Object call(PageContext pc, String name) throws PageException {
+
+ ORMSession session = ORMUtil.getSession(pc);
+ return session.loadAsArray(pc, name, CommonUtil.createStruct());
+ }
+
+ public static Object call(PageContext pc, String name, Object idOrFilter) throws PageException {
+ return call(pc, name, idOrFilter, Boolean.FALSE);
+ }
+
+ public static Object call(PageContext pc, String name, Object idOrFilter, Object uniqueOrOptions)
+ throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+
+ // id
+ if (CommonUtil.isSimpleValue(idOrFilter)) {
+ // id,unique
+ if (CommonUtil.isCastableToBoolean(uniqueOrOptions)) {
+ // id,unique=true
+ if (CommonUtil.toBooleanValue(uniqueOrOptions))
+ return session.load(pc, name, CommonUtil.toString(idOrFilter));
+ // id,unique=false
+ return session.loadAsArray(pc, name, CommonUtil.toString(idOrFilter));
+ } else if (CommonUtil.isString(uniqueOrOptions)) {
+ return session.loadAsArray(pc, name, CommonUtil.toString(idOrFilter),
+ CommonUtil.toString(uniqueOrOptions));
+ }
+
+ // id,options
+ return session.loadAsArray(pc, name, CommonUtil.toString(idOrFilter));
+ }
+
+ // filter,[unique|sortorder]
+ if (CommonUtil.isSimpleValue(uniqueOrOptions)) {
+ // filter,unique
+ if (CommonUtil.isBoolean(uniqueOrOptions)) {
+ if (CommonUtil.toBooleanValue(uniqueOrOptions))
+ return session.load(pc, name, CommonUtil.toStruct(idOrFilter));
+ return session.loadAsArray(pc, name, CommonUtil.toStruct(idOrFilter));
+ }
+ // filter,sortorder
+ return session.loadAsArray(pc, name, CommonUtil.toStruct(idOrFilter), (Struct) null,
+ CommonUtil.toString(uniqueOrOptions));
+ }
+ // filter,options
+ return session.loadAsArray(pc, name, CommonUtil.toStruct(idOrFilter), CommonUtil.toStruct(uniqueOrOptions));
+ }
+
+ public static Object call(PageContext pc, String name, Object filter, Object order, Object options)
+ throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ return session.loadAsArray(pc, name, CommonUtil.toStruct(filter), CommonUtil.toStruct(options),
+ CommonUtil.toString(order));
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+ if (args.length == 2) return call(pc, cast.toString(args[0]), args[1]);
+ if (args.length == 3) return call(pc, cast.toString(args[0]), args[1], args[2]);
+ if (args.length == 4) return call(pc, cast.toString(args[0]), args[1], args[2], args[3]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityLoad", 1, 4, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityLoadByExample.java b/source/java/src/org/lucee/extension/orm/functions/EntityLoadByExample.java
new file mode 100755
index 00000000..06d51b6a
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityLoadByExample.java
@@ -0,0 +1,56 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * Built-in CFML method to load entity which matches the sample entity.
+ */
+public class EntityLoadByExample extends BIF {
+ public static Object call(PageContext pc, Object sampleEntity) throws PageException {
+ return call(pc, sampleEntity, false);
+ }
+
+ public static Object call(PageContext pc, Object sampleEntity, boolean unique) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ if (unique)
+ return session.loadByExample(pc, sampleEntity);
+ return session.loadByExampleAsArray(pc, sampleEntity);
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 2) return call(pc, args[0], cast.toBoolean(args[1]));
+ if (args.length == 1) return call(pc, args[0]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityLoadByExample", 2, 3, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityLoadByPK.java b/source/java/src/org/lucee/extension/orm/functions/EntityLoadByPK.java
new file mode 100755
index 00000000..d76a34fd
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityLoadByPK.java
@@ -0,0 +1,38 @@
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * Built-in CFML method to load entity by primary key.
+ */
+public class EntityLoadByPK extends BIF {
+ public static Object call(PageContext pc, String name, Object oID) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ String id;
+ if (CommonUtil.isBinary(oID))
+ id = CommonUtil.toBase64(oID);
+ else
+ id = CommonUtil.toString(oID);
+ return session.load(pc, name, id);
+ // FUTURE call instead load(..,..,OBJECT);
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 2) return call(pc, cast.toString(args[0]), args[1]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityLoadByPK", 2, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityMerge.java b/source/java/src/org/lucee/extension/orm/functions/EntityMerge.java
new file mode 100755
index 00000000..6053b423
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityMerge.java
@@ -0,0 +1,48 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * Merge a detached or transient entity into the Hibernate session.
+ */
+public class EntityMerge extends BIF {
+
+ public static Object call(PageContext pc, Object obj) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ return session.merge(pc, obj);
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 1) return call(pc, args[0]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityMerge", 1, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityNameArray.java b/source/java/src/org/lucee/extension/orm/functions/EntityNameArray.java
new file mode 100755
index 00000000..a39fa277
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityNameArray.java
@@ -0,0 +1,49 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.type.Array;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+/**
+ * CFML built-in function to retrieve an array of all ORM entity names.
+ */
+public class EntityNameArray extends BIF {
+
+ public static Array call(PageContext pc) throws PageException {
+ return CommonUtil.toArray(
+ ORMUtil.getSession(pc).getEntityNames()
+ );
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 0) return call(pc);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "entityNameArray", 0, 0, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityNameList.java b/source/java/src/org/lucee/extension/orm/functions/EntityNameList.java
new file mode 100755
index 00000000..9d82d8ae
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityNameList.java
@@ -0,0 +1,55 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to retrieve a list of all ORM entity names.
+ */
+public class EntityNameList extends BIF {
+
+ public static String call(PageContext pc) throws PageException {
+ return call(pc, ",");
+ }
+
+ public static String call(PageContext pc, String delimiter) throws PageException {
+ ORMSession sess = ORMUtil.getSession(pc);
+ return String.join(delimiter, sess.getEntityNames());
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 0) return call(pc);
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityNameList", 0, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityNew.java b/source/java/src/org/lucee/extension/orm/functions/EntityNew.java
new file mode 100755
index 00000000..b03d6dd0
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityNew.java
@@ -0,0 +1,95 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import java.util.Iterator;
+import java.util.Map.Entry;
+
+import lucee.runtime.Component;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.type.Collection.Key;
+import lucee.runtime.type.Struct;
+import lucee.runtime.type.UDF;
+
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to create a new instance of a Hibernate session entity.
+ */
+public class EntityNew extends BIF {
+
+ public static Object call(PageContext pc, String name) throws PageException {
+ return call(pc, name, null);
+ }
+
+ public static Object call(PageContext pc, String name, Struct properties) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ if (properties == null)
+ return session.create(pc, name);
+
+ Component entity = session.create(pc, name);
+ setPropeties(pc, entity, properties, false);
+ return entity;
+
+ }
+
+ public static void setPropeties(PageContext pc, Component c, Struct properties, boolean ignoreNotExisting)
+ throws PageException {
+ if (properties == null)
+ return;
+
+ // argumentCollection
+ if (properties.size() == 1 && properties.containsKey(CommonUtil.createKey("argumentCollection"))
+ && !c.containsKey(CommonUtil.createKey("setArgumentCollection"))) {
+ properties = CommonUtil.toStruct(properties.get(CommonUtil.createKey("argumentCollection")));
+ }
+
+ Iterator> it = properties.entryIterator();
+ Entry e;
+ while (it.hasNext()) {
+ e = it.next();
+ Key funcName = CommonUtil.createKey("set" + e.getKey().getString());
+ if (ignoreNotExisting) {
+ if (c.get(funcName, null) instanceof UDF)
+ c.call(pc, funcName, new Object[] { e.getValue() });
+ } else {
+ c.call(pc, funcName, new Object[] { e.getValue() });
+ }
+ }
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+ if (args.length == 2) return call(pc, cast.toString(args[0]), cast.toStruct(args[1]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityNew", 1, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityReload.java b/source/java/src/org/lucee/extension/orm/functions/EntityReload.java
new file mode 100755
index 00000000..7cafa2ae
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityReload.java
@@ -0,0 +1,50 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to reload an ORM entity.
+ */
+public class EntityReload extends BIF {
+
+ public static String call(PageContext pc, Object obj) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ session.reload(pc, obj);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 1) return call(pc, args[0]);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityReload", 1, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntitySave.java b/source/java/src/org/lucee/extension/orm/functions/EntitySave.java
new file mode 100755
index 00000000..72a53dc4
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntitySave.java
@@ -0,0 +1,56 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to persist an entity to the database.
+ */
+public class EntitySave extends BIF {
+
+ public static String call(PageContext pc, Object obj) throws PageException {
+ return call(pc, obj, false);
+ }
+
+ public static String call(PageContext pc, Object obj, boolean forceInsert) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ session.save(pc, obj, forceInsert);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, args[0]);
+ if (args.length == 2) return call(pc, args[0], cast.toBoolean(args[1]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntitySave", 1, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/EntityToQuery.java b/source/java/src/org/lucee/extension/orm/functions/EntityToQuery.java
new file mode 100755
index 00000000..a73ee138
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/EntityToQuery.java
@@ -0,0 +1,57 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.type.Query;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to convert an entity to a query object.
+ */
+public class EntityToQuery extends BIF {
+
+ public static Query call(PageContext pc, Object obj) throws PageException {
+ return call(pc, obj, null);
+ }
+
+ public static Query call(PageContext pc, Object obj, String name) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ return session.toQuery(pc, obj, name);
+
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, args[0]);
+ if (args.length == 2) return call(pc, args[0], cast.toString(args[1]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "EntityToQuery", 1, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMClearSession.java b/source/java/src/org/lucee/extension/orm/functions/ORMClearSession.java
new file mode 100755
index 00000000..021c443e
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMClearSession.java
@@ -0,0 +1,58 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to clear the ORM session.
+ */
+public class ORMClearSession extends BIF {
+
+ public static String call(PageContext pc) throws PageException {
+ return call(pc, null);
+ }
+
+ public static String call(PageContext pc, String datasource) throws PageException {
+ if (Util.isEmpty(datasource, true))
+ ORMUtil.getSession(pc).clear(pc);
+ else
+ ORMUtil.getSession(pc).clear(pc, datasource.trim());
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 0) return call(pc);
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMClearSession", 0, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMCloseAllSessions.java b/source/java/src/org/lucee/extension/orm/functions/ORMCloseAllSessions.java
new file mode 100644
index 00000000..eb403166
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMCloseAllSessions.java
@@ -0,0 +1,46 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to close all open ORM sessions.
+ */
+public class ORMCloseAllSessions extends BIF {
+ public static String call(PageContext pc) throws PageException {
+ ORMUtil.getSession(pc).closeAll(pc);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 0) return call(pc);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMCloseAllSessions", 0, 0, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMCloseSession.java b/source/java/src/org/lucee/extension/orm/functions/ORMCloseSession.java
new file mode 100755
index 00000000..2a8cde66
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMCloseSession.java
@@ -0,0 +1,58 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to close the ORM session for the named datasource.
+ */
+public class ORMCloseSession extends BIF {
+
+ public static String call(PageContext pc) throws PageException {
+ return call(pc, null);
+ }
+
+ public static String call(PageContext pc, String datasource) throws PageException {
+ if (Util.isEmpty(datasource, true))
+ ORMUtil.getSession(pc).close(pc);
+ else
+ ORMUtil.getSession(pc).close(pc, datasource.trim());
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 0) return call(pc);
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMCloseSession", 0, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMEvictCollection.java b/source/java/src/org/lucee/extension/orm/functions/ORMEvictCollection.java
new file mode 100755
index 00000000..cf1434e7
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMEvictCollection.java
@@ -0,0 +1,60 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to evict a collection for the given entity/collection name.
+ */
+public class ORMEvictCollection extends BIF {
+ public static String call(PageContext pc, String entityName, String collectionName) throws PageException {
+ return call(pc, entityName, collectionName, null);
+ }
+
+ public static String call(PageContext pc, String entityName, String collectionName, String primaryKey)
+ throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ if (Util.isEmpty(primaryKey))
+ session.evictCollection(pc, entityName, collectionName);
+ else
+ session.evictCollection(pc, entityName, collectionName, primaryKey);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 2) return call(pc, cast.toString(args[0]), cast.toString(args[1]));
+ if (args.length == 3) return call(pc, cast.toString(args[0]), cast.toString(args[1]), cast.toString(args[2]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMEvictCollection", 2, 3, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMEvictEntity.java b/source/java/src/org/lucee/extension/orm/functions/ORMEvictEntity.java
new file mode 100755
index 00000000..baa88e6a
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMEvictEntity.java
@@ -0,0 +1,59 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to evict an entity from the current ORM session.
+ */
+public class ORMEvictEntity extends BIF {
+ public static String call(PageContext pc, String entityName) throws PageException {
+ return call(pc, entityName, null);
+ }
+
+ public static String call(PageContext pc, String entityName, String primaryKey) throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ if (Util.isEmpty(primaryKey))
+ session.evictEntity(pc, entityName);
+ else
+ session.evictEntity(pc, entityName, primaryKey);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+ if (args.length == 2) return call(pc, cast.toString(args[0]), cast.toString(args[1]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMEvictEntity", 1, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMEvictQueries.java b/source/java/src/org/lucee/extension/orm/functions/ORMEvictQueries.java
new file mode 100755
index 00000000..6c7dbcc8
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMEvictQueries.java
@@ -0,0 +1,58 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to evict queries from the named query cache.
+ */
+public class ORMEvictQueries extends BIF {
+ public static String call(PageContext pc) throws PageException {
+ return call(pc, null, null);
+ }
+
+ public static String call(PageContext pc, String cacheName) throws PageException {
+ return call(pc, cacheName, null);
+ }
+
+ public static String call(PageContext pc, String cacheName, String datasource) throws PageException {
+ ORMUtil.getSession(pc).evictQueries(pc, cacheName, datasource);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 0) return call(pc);
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+ if (args.length == 2) return call(pc, cast.toString(args[0]), cast.toString(args[1]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMEvictQueries", 0, 2, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMExecuteQuery.java b/source/java/src/org/lucee/extension/orm/functions/ORMExecuteQuery.java
new file mode 100755
index 00000000..53d7083e
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMExecuteQuery.java
@@ -0,0 +1,121 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ExceptionUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import java.util.List;
+import java.util.Map;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.type.Array;
+import lucee.runtime.type.Struct;
+
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to execute an HQL query through Hibernate ORM.
+ */
+public class ORMExecuteQuery extends BIF {
+
+ public static Object call(PageContext pc, String hql) throws PageException {
+ return _call(pc, hql, null, false, null);
+ }
+
+ public static Object call(PageContext pc, String hql, Object paramsOrUnique) throws PageException {
+ if (CommonUtil.isCastableToBoolean(paramsOrUnique)) {
+ return _call(pc, hql, null, CommonUtil.toBooleanValue(paramsOrUnique), null);
+ }
+ return _call(pc, hql, paramsOrUnique, false, null);
+ }
+
+ public static Object call(PageContext pc, String hql, Object paramsOrUnique, Object uniqueOrQueryOptions)
+ throws PageException {
+ if (CommonUtil.isCastableToBoolean(paramsOrUnique)) {
+ return _call(pc, hql, null, CommonUtil.toBooleanValue(paramsOrUnique),
+ CommonUtil.toStruct(uniqueOrQueryOptions));
+ }
+ if (CommonUtil.isCastableToBoolean(uniqueOrQueryOptions)) {
+ return _call(pc, hql, paramsOrUnique, CommonUtil.toBooleanValue(uniqueOrQueryOptions), null);
+ }
+ return _call(pc, hql, paramsOrUnique, false, CommonUtil.toStruct(uniqueOrQueryOptions));
+ }
+
+ public static Object call(PageContext pc, String hql, Object params, boolean isUnique, Struct queryOptions)
+ throws PageException {
+ return _call(pc, hql, params, isUnique, queryOptions);
+ }
+
+ private static Object _call(PageContext pc, String hql, Object params, boolean unique, Struct queryOptions)
+ throws PageException {
+ ORMSession session = ORMUtil.getSession(pc);
+ String dsn = null;
+ if (queryOptions != null)
+ dsn = CommonUtil.toString(queryOptions.get(CommonUtil.createKey("datasource"), null), null);
+ if (Util.isEmpty(dsn, true))
+ dsn = ORMUtil.getDefaultDataSource(pc).getName();
+
+ if (params == null)
+ return toCFML(session.executeQuery(pc, dsn, hql, CommonUtil.createArray(), unique, queryOptions));
+ else if (CommonUtil.isStruct(params))
+ return toCFML(session.executeQuery(pc, dsn, hql, CommonUtil.toStruct(params), unique, queryOptions));
+ else if (CommonUtil.isArray(params))
+ return toCFML(session.executeQuery(pc, dsn, hql, CommonUtil.toArray(params), unique, queryOptions));
+ else if (CommonUtil.isCastableToStruct(params))
+ return toCFML(session.executeQuery(pc, dsn, hql, CommonUtil.toStruct(params), unique, queryOptions));
+ else if (CommonUtil.isCastableToArray(params))
+ return toCFML(session.executeQuery(pc, dsn, hql, CommonUtil.toArray(params), unique, queryOptions));
+ else
+ throw ExceptionUtil.createException("ORMExecuteQuery : cannot convert the params to an array or a struct");
+
+ }
+
+ private static Object toCFML(Object obj) throws PageException {
+ if (obj instanceof List> && !(obj instanceof Array))
+ return CommonUtil.toArray(obj);
+ if (obj instanceof Map, ?> && !(obj instanceof Struct))
+ return CommonUtil.toStruct(obj);
+ return obj;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+ if (args.length == 2) return call(pc, cast.toString(args[0]), args[1]);
+ if (args.length == 3) return call(pc, cast.toString(args[0]), args[1], args[2]);
+ if (args.length == 4) {
+ Struct queryOptions = null;
+ if (args[1] != null){ queryOptions = cast.toStruct(args[1]); }
+ return call(pc, cast.toString(args[0]), args[1], cast.toBoolean(args[1],false), queryOptions);
+ }
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMExecuteQuery", 1, 4, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMFlush.java b/source/java/src/org/lucee/extension/orm/functions/ORMFlush.java
new file mode 100755
index 00000000..d83e9915
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMFlush.java
@@ -0,0 +1,57 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.loader.util.Util;
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.util.Cast;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to flush the current session.
+ */
+public class ORMFlush extends BIF {
+ public static String call(PageContext pc) throws PageException {
+ return call(pc, null);
+ }
+
+ public static String call(PageContext pc, String datasource) throws PageException {
+ if (Util.isEmpty(datasource, true))
+ ORMUtil.getSession(pc).flush(pc);
+ else
+ ORMUtil.getSession(pc).flush(pc, datasource.trim());
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+ Cast cast = engine.getCastUtil();
+
+ if (args.length == 0) return call(pc);
+ if (args.length == 1) return call(pc, cast.toString(args[0]));
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMFlush", 0, 1, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMGetSession.java b/source/java/src/org/lucee/extension/orm/functions/ORMGetSession.java
new file mode 100755
index 00000000..1fc4ad0a
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMGetSession.java
@@ -0,0 +1,47 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.ext.function.BIF;
+
+public class ORMGetSession extends BIF {
+
+ private static final long serialVersionUID = 349899413869883140L;
+
+ public static Object call(PageContext pc) throws PageException {
+ return call(pc, null);
+ }
+
+ public static Object call(PageContext pc, String datasource) throws PageException {
+ String dsn = ORMUtil.getDataSource(pc, datasource).getName();
+ return ORMUtil.getSession(pc).getRawSession(dsn);
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ if (args.length == 0)
+ return call(pc);
+ return call(pc, CommonUtil.toString(args[0]));
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMGetSessionFactory.java b/source/java/src/org/lucee/extension/orm/functions/ORMGetSessionFactory.java
new file mode 100755
index 00000000..b1ae405e
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMGetSessionFactory.java
@@ -0,0 +1,47 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.ext.function.BIF;
+
+public class ORMGetSessionFactory extends BIF {
+
+ private static final long serialVersionUID = -8739815940242857106L;
+
+ public static Object call(PageContext pc) throws PageException {
+ return call(pc, null);
+ }
+
+ public static Object call(PageContext pc, String datasource) throws PageException {
+ String dsn = ORMUtil.getDataSource(pc, datasource).getName();
+ return ORMUtil.getSession(pc).getRawSessionFactory(dsn);
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ if (args.length == 0)
+ return call(pc);
+ return call(pc, CommonUtil.toString(args[0]));
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/functions/ORMReload.java b/source/java/src/org/lucee/extension/orm/functions/ORMReload.java
new file mode 100755
index 00000000..65389b56
--- /dev/null
+++ b/source/java/src/org/lucee/extension/orm/functions/ORMReload.java
@@ -0,0 +1,59 @@
+/**
+ *
+ * Copyright (c) 2015, Lucee Association Switzerland. All rights reserved.
+ *
+ * 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, see .
+ *
+ **/
+package org.lucee.extension.orm.functions;
+
+import org.lucee.extension.orm.hibernate.util.ORMUtil;
+
+import lucee.runtime.PageContext;
+import lucee.runtime.exp.PageException;
+import lucee.runtime.orm.ORMConfiguration;
+import lucee.runtime.orm.ORMSession;
+import lucee.runtime.ext.function.BIF;
+import lucee.loader.engine.CFMLEngineFactory;
+import lucee.loader.engine.CFMLEngine;
+
+/**
+ * CFML built-in function to flush the current session.
+ */
+public class ORMReload extends BIF {
+ public static String call(PageContext pc) throws PageException {
+
+ // flush and close session
+ ORMSession session = ORMUtil.getSession(pc, false);
+ if (session != null) {// MUST do the same with all sesson using the same engine
+ ORMConfiguration config = session.getEngine().getConfiguration(pc);
+ if (config.autoManageSession()) {
+ session.flushAll(pc);
+ session.closeAll(pc);
+ }
+ }
+ pc.getApplicationContext().reinitORM(pc);
+ ORMUtil.resetEngine(pc, true);
+ return null;
+ }
+
+ @Override
+ public Object invoke(PageContext pc, Object[] args) throws PageException {
+ CFMLEngine engine = CFMLEngineFactory.getInstance();
+
+ if (args.length == 0) return call(pc);
+
+ throw engine.getExceptionUtil().createFunctionException(pc, "ORMReload", 0, 0, args.length);
+ }
+}
\ No newline at end of file
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/ColumnInfo.java b/source/java/src/org/lucee/extension/orm/hibernate/ColumnInfo.java
index bd9adc14..49558e02 100755
--- a/source/java/src/org/lucee/extension/orm/hibernate/ColumnInfo.java
+++ b/source/java/src/org/lucee/extension/orm/hibernate/ColumnInfo.java
@@ -2,93 +2,99 @@
public class ColumnInfo {
- private String name;
- private int type;
- private String typeName;
- private int size;
- private boolean nullable;
+ private String name;
+ private int type;
+ private String typeName;
+ private int size;
+ private boolean nullable;
- public ColumnInfo(String name, int type, String typeName, int size, boolean nullable) {
+ public ColumnInfo(String name, int type, String typeName, int size, boolean nullable) {
- this.name = name;
- this.type = type;
- this.typeName = typeName;
- this.size = size;
- this.nullable = nullable;
- }
+ this.name = name;
+ this.type = type;
+ this.typeName = typeName;
+ this.size = size;
+ this.nullable = nullable;
+ }
- /**
- * @return the name
- */
- public String getName() {
- return name;
- }
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
- /**
- * @param name the name to set
- */
- public void setName(String name) {
- this.name = name;
- }
+ /**
+ * @param name
+ * the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
- /**
- * @return the type
- */
- public int getType() {
- return type;
- }
+ /**
+ * @return the type
+ */
+ public int getType() {
+ return type;
+ }
- /**
- * @param type the type to set
- */
- public void setType(int type) {
- this.type = type;
- }
+ /**
+ * @param type
+ * the type to set
+ */
+ public void setType(int type) {
+ this.type = type;
+ }
- /**
- * @return the typeName
- */
- public String getTypeName() {
- return typeName;
- }
+ /**
+ * @return the typeName
+ */
+ public String getTypeName() {
+ return typeName;
+ }
- /**
- * @param typeName the typeName to set
- */
- public void setTypeName(String typeName) {
- this.typeName = typeName;
- }
+ /**
+ * @param typeName
+ * the typeName to set
+ */
+ public void setTypeName(String typeName) {
+ this.typeName = typeName;
+ }
- /**
- * @return the size
- */
- public int getSize() {
- return size;
- }
+ /**
+ * @return the size
+ */
+ public int getSize() {
+ return size;
+ }
- /**
- * @param size the size to set
- */
- public void setSize(int size) {
- this.size = size;
- }
+ /**
+ * @param size
+ * the size to set
+ */
+ public void setSize(int size) {
+ this.size = size;
+ }
- /**
- * @return the nullable
- */
- public boolean isNullable() {
- return nullable;
- }
+ /**
+ * @return the nullable
+ */
+ public boolean isNullable() {
+ return nullable;
+ }
- /**
- * @param nullable the nullable to set
- */
- public void setNullable(boolean nullable) {
- this.nullable = nullable;
- }
+ /**
+ * @param nullable
+ * the nullable to set
+ */
+ public void setNullable(boolean nullable) {
+ this.nullable = nullable;
+ }
- @Override
- public String toString() {
- return "name:" + name + ";type:" + type + ";typeName:" + typeName + ";size:" + size + ";nullable:" + nullable + ";";
- }
+ @Override
+ public String toString() {
+ return "name:" + name + ";type:" + type + ";typeName:" + typeName + ";size:" + size + ";nullable:" + nullable
+ + ";";
+ }
}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/CommonUtil.java b/source/java/src/org/lucee/extension/orm/hibernate/CommonUtil.java
deleted file mode 100644
index 0f5016c7..00000000
--- a/source/java/src/org/lucee/extension/orm/hibernate/CommonUtil.java
+++ /dev/null
@@ -1,961 +0,0 @@
-package org.lucee.extension.orm.hibernate;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.Serializable;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.nio.charset.Charset;
-import java.sql.ResultSet;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.TimeZone;
-
-import org.hibernate.JDBCException;
-import org.hibernate.exception.ConstraintViolationException;
-import org.lucee.extension.orm.hibernate.util.XMLUtil;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import lucee.commons.io.res.Resource;
-import lucee.commons.lang.types.RefBoolean;
-import lucee.loader.engine.CFMLEngineFactory;
-import lucee.loader.util.Util;
-import lucee.runtime.Component;
-import lucee.runtime.Mapping;
-import lucee.runtime.PageContext;
-import lucee.runtime.component.Property;
-import lucee.runtime.config.Config;
-import lucee.runtime.db.DataSource;
-import lucee.runtime.db.DatasourceConnection;
-import lucee.runtime.db.SQL;
-import lucee.runtime.db.SQLItem;
-import lucee.runtime.exp.PageException;
-import lucee.runtime.type.Array;
-import lucee.runtime.type.Collection;
-import lucee.runtime.type.Collection.Key;
-import lucee.runtime.type.Query;
-import lucee.runtime.type.Struct;
-import lucee.runtime.type.dt.DateTime;
-import lucee.runtime.type.scope.Argument;
-import lucee.runtime.util.Cast;
-import lucee.runtime.util.Creation;
-import lucee.runtime.util.DBUtil;
-import lucee.runtime.util.Decision;
-import lucee.runtime.util.ORMUtil;
-import lucee.runtime.util.Operation;
-
-public class CommonUtil {
-
- public static final Key ENTITY_NAME = CommonUtil.createKey("entityname");
- public static final Key FIELDTYPE = CommonUtil.createKey("fieldtype");
- public static final Key POST_INSERT = CommonUtil.createKey("postInsert");
- public static final Key POST_UPDATE = CommonUtil.createKey("postUpdate");
- public static final Key PRE_DELETE = CommonUtil.createKey("preDelete");
- public static final Key POST_DELETE = CommonUtil.createKey("postDelete");
- public static final Key PRE_LOAD = CommonUtil.createKey("preLoad");
- public static final Key POST_LOAD = CommonUtil.createKey("postLoad");
- public static final Key PRE_UPDATE = CommonUtil.createKey("preUpdate");
- public static final Key PRE_INSERT = CommonUtil.createKey("preInsert");
- public static final Key ON_FLUSH = CommonUtil.createKey("onFlush");
- public static final Key ON_AUTO_FLUSH = CommonUtil.createKey("onAutoFlush");
- public static final Key ON_CLEAR = CommonUtil.createKey("onClear");
- public static final Key ON_DELETE = CommonUtil.createKey("onDelete");
- public static final Key ON_DIRTY_CHECK = CommonUtil.createKey("onDirtyCheck");
- public static final Key ON_EVICT = CommonUtil.createKey("onEvict");
-
- public static final Key INIT = CommonUtil.createKey("init");
- private static final short INSPECT_UNDEFINED = (short) 4; /* ConfigImpl.INSPECT_UNDEFINED */
- private static final Class>[] ZEROC = new Class>[] {};
- private static final Object[] ZEROO = new Object[] {};
- private static final Class>[] GET_DSCONN = new Class[] { PageContext.class, DataSource.class, String.class, String.class, boolean.class };
- private static final Class>[] REL_DSCONN = new Class[] { PageContext.class, DatasourceConnection.class, boolean.class };
- // private static final Class>[] GET_CONN = new Class[] { PageContext.class, DataSource.class,
- // String.class, String.class };
- // private static final Class>[] REL_CONN = new Class[] { PageContext.class,
- // DatasourceConnection.class };
- // releaseConnection(pageContext, dc);
- private static Charset _charset;
-
- public static Charset _UTF8;
- // public static Charset ISO88591;
- public static Charset _UTF16BE;
- public static Charset _UTF16LE;
-
- public static Charset getCharset() {
- if (_charset == null) {
- String strCharset = System.getProperty("file.encoding");
- if (strCharset == null || strCharset.equalsIgnoreCase("MacRoman")) strCharset = "cp1252";
-
- if (strCharset.equalsIgnoreCase("utf-8")) _charset = UTF8();
- else _charset = toCharset(strCharset);
- }
- return _charset;
- }
-
- public static Charset UTF8() {
- if (_UTF8 == null) _UTF8 = toCharset("UTF-8");
- return _UTF8;
- }
-
- private static Charset UTF16LE() {
- if (_UTF16LE == null) _UTF16LE = toCharset("UTF-16LE");
- return _UTF16LE;
- }
-
- private static Charset UTF16BE() {
- if (_UTF16BE == null) _UTF16BE = toCharset("UTF-16BE");
- return _UTF16BE;
- }
-
- private static Charset toCharset(String charset) {
- try {
- return CFMLEngineFactory.getInstance().getCastUtil().toCharset(charset);
- }
- catch (PageException pe) {
- throw CFMLEngineFactory.getInstance().getExceptionUtil().createPageRuntimeException(pe);
- }
- }
-
- private static Cast caster;
- private static Decision decision;
- private static Creation creator;
- private static Operation op;
- private static lucee.runtime.util.XMLUtil xml;
- private static lucee.runtime.util.ListUtil list;
- private static DBUtil db;
- private static ORMUtil orm;
- // private static Method mGetDataSourceManager;
- // private static Method mGetConnection;
- // private static Method mReleaseConnection;
-
- private static Method mGetDatasourceConnection;
- private static Method mReleaseDatasourceConnection;
-
- public static Object castTo(PageContext pc, Class trgClass, Object obj) throws PageException {
- return caster().castTo(pc, trgClass, obj);
- }
-
- public static Array toArray(Object obj) throws PageException {
- return caster().toArray(obj);
- }
-
- public static Array toArray(Object obj, Array defaultValue) {
- return caster().toArray(obj, defaultValue);
- }
-
- public static Boolean toBoolean(String str) throws PageException {
- return caster().toBoolean(str);
- }
-
- public static Boolean toBoolean(String str, Boolean defaultValue) {
- return caster().toBoolean(str, defaultValue);
- }
-
- public static Boolean toBoolean(Object obj) throws PageException {
- return caster().toBoolean(obj);
- }
-
- public static Boolean toBoolean(Object obj, Boolean defaultValue) {
- return caster().toBoolean(obj, defaultValue);
- }
-
- public static Boolean toBooleanValue(String str) throws PageException {
- return caster().toBooleanValue(str);
- }
-
- public static Boolean toBooleanValue(String str, Boolean defaultValue) {
- return caster().toBooleanValue(str, defaultValue);
- }
-
- public static boolean toBooleanValue(Object obj) throws PageException {
- return caster().toBooleanValue(obj);
- }
-
- public static boolean toBooleanValue(Object obj, boolean defaultValue) {
- return caster().toBooleanValue(obj, defaultValue);
- }
-
- public static Component toComponent(Object obj) throws PageException {
- return caster().toComponent(obj);
- }
-
- public static Component toComponent(Object obj, Component defaultValue) {
- return caster().toComponent(obj, defaultValue);
- }
-
- public static Object toList(String[] arr, String delimiter) {
- return list().toList(arr, delimiter);
- }
-
- public static String toString(Object obj, String defaultValue) {
- return caster().toString(obj, defaultValue);
- }
-
- public static String toString(Object obj) throws PageException {
- return caster().toString(obj);
- }
-
- public static String toString(boolean b) {
- return caster().toString(b);
- }
-
- public static String toString(double d) {
- return caster().toString(d);
- }
-
- public static String toString(int i) {
- return caster().toString(i);
- }
-
- public static String toString(long l) {
- return caster().toString(l);
- }
-
- /**
- * reads String data from File
- *
- * @param file
- * @param charset
- * @return readed string
- * @throws IOException
- */
- public static String toString(Resource file, Charset charset) throws IOException {
- Reader r = null;
- try {
- r = getReader(file, charset);
- String str = toString(r);
- return str;
- }
- finally {
- closeEL(r);
- }
- }
-
- public static String toString(Reader reader) throws IOException {
- StringWriter sw = new StringWriter(512);
- copy(toBufferedReader(reader), sw);
- sw.close();
- return sw.toString();
- }
-
- public static BufferedReader toBufferedReader(Reader r) {
- if (r instanceof BufferedReader) return (BufferedReader) r;
- return new BufferedReader(r);
- }
-
- private static final void copy(Reader r, Writer w) throws IOException {
- copy(r, w, 0xffff);
- }
-
- private static final void copy(Reader r, Writer w, int blockSize) throws IOException {
- char[] buffer = new char[blockSize];
- int len;
-
- while ((len = r.read(buffer)) != -1)
- w.write(buffer, 0, len);
- }
-
- public static Reader getReader(Resource res, Charset charset) throws IOException {
- InputStream is = null;
- try {
- is = res.getInputStream();
- boolean markSupported = is.markSupported();
- if (markSupported) is.mark(4);
- int first = is.read();
- int second = is.read();
- // FE FF UTF-16, big-endian
- if (first == 0xFE && second == 0xFF) {
- return _getReader(is, UTF16BE());
- }
- // FF FE UTF-16, little-endian
- if (first == 0xFF && second == 0xFE) {
- return _getReader(is, UTF16LE());
- }
-
- int third = is.read();
- // EF BB BF UTF-8
- if (first == 0xEF && second == 0xBB && third == 0xBF) {
- // is.reset();
- return _getReader(is, UTF8());
- }
-
- if (markSupported) {
- is.reset();
- return _getReader(is, charset);
- }
- }
- catch (IOException ioe) {
- closeEL(is);
- throw ioe;
- }
-
- // when mark not supported return new reader
- closeEL(is);
- is = null;
- try {
- is = res.getInputStream();
- }
- catch (IOException ioe) {
- closeEL(is);
- throw ioe;
- }
- return _getReader(is, charset);
- }
-
- private static Reader _getReader(InputStream is, Charset cs) {
- if (cs == null) cs = getCharset();
- return new BufferedReader(new InputStreamReader(is, cs));
- }
-
- public static String[] toStringArray(String list, String delimiter) {
- return list().toStringArray(list().toArray(list, delimiter), ""); // TODO better
- }
-
- public static Float toFloat(Object obj) throws PageException {
- return caster().toFloat(obj);
- }
-
- public static Float toFloat(Object obj, Float defaultValue) {
- return caster().toFloat(obj, defaultValue);
- }
-
- public static float toFloatValue(Object obj) throws PageException {
- return caster().toFloatValue(obj);
- }
-
- public static float toFloatValue(Object obj, float defaultValue) {
- return caster().toFloatValue(obj, defaultValue);
- }
-
- public static Double toDouble(Object obj) throws PageException {
- return caster().toDouble(obj);
- }
-
- public static Double toDouble(Object obj, Double defaultValue) {
- return caster().toDouble(obj, defaultValue);
- }
-
- public static double toDoubleValue(Object obj) throws PageException {
- return caster().toDoubleValue(obj);
- }
-
- public static double toDoubleValue(Object obj, double defaultValue) {
- return caster().toDoubleValue(obj, defaultValue);
- }
-
- public static BigDecimal toBigDecimal(Object obj) throws PageException {
- return caster().toBigDecimal(obj);
- }
-
- public static BigDecimal toBigDecimal(Object obj, BigDecimal defaultValue) {
- return caster().toBigDecimal(obj, defaultValue);
- }
-
- public static Short toShort(Object obj) throws PageException {
- return caster().toShort(obj);
- }
-
- public static Short toShort(Object obj, Short defaultValue) {
- return caster().toShort(obj, defaultValue);
- }
-
- public static double toShortValue(Object obj) throws PageException {
- return caster().toShortValue(obj);
- }
-
- public static double toShortValue(Object obj, short defaultValue) {
- return caster().toShortValue(obj, defaultValue);
- }
-
- public static Integer toInteger(Object obj) throws PageException {
- return caster().toInteger(obj);
- }
-
- public static Integer toInteger(Object obj, Integer defaultValue) {
- return caster().toInteger(obj, defaultValue);
- }
-
- public static Long toLong(Object obj) throws PageException {
- return caster().toLong(obj);
- }
-
- public static Long toLong(Object obj, Long defaultValue) {
- return caster().toLong(obj, defaultValue);
- }
-
- public static long toLongValue(Object obj) throws PageException {
- return caster().toLongValue(obj);
- }
-
- public static long toLongValue(Object obj, long defaultValue) {
- return caster().toLongValue(obj, defaultValue);
- }
-
- public static byte[] toBinary(Object obj) throws PageException {
- return caster().toBinary(obj);
- }
-
- public static byte[] toBinary(Object obj, byte[] defaultValue) {
- return caster().toBinary(obj, defaultValue);
- }
-
- public static int toIntValue(Object obj) throws PageException {
- return caster().toIntValue(obj);
- }
-
- public static int toIntValue(Object obj, int defaultValue) {
- return caster().toIntValue(obj, defaultValue);
- }
-
- public static Array toArray(Argument arg) {
- Array trg = createArray();
- int[] keys = arg.intKeys();
- for (int i = 0; i < keys.length; i++) {
- trg.setEL(keys[i], arg.get(keys[i], null));
- }
- return trg;
- }
-
- public static PageException toPageException(Throwable t) {
- PageException pe = caster().toPageException(t);
- if (t instanceof org.hibernate.HibernateException) {
- org.hibernate.HibernateException he = (org.hibernate.HibernateException) t;
- Throwable cause = he.getCause();
- if (cause != null) {
- pe = caster().toPageException(cause);
- ExceptionUtil.setAdditional(pe, CommonUtil.createKey("hibernate exception"), t);
- }
- }
- if (t instanceof JDBCException) {
- JDBCException je = (JDBCException) t;
- ExceptionUtil.setAdditional(pe, CommonUtil.createKey("sql"), je.getSQL());
- }
- if (t instanceof ConstraintViolationException) {
- ConstraintViolationException cve = (ConstraintViolationException) t;
- if (!Util.isEmpty(cve.getConstraintName())) {
- ExceptionUtil.setAdditional(pe, CommonUtil.createKey("constraint name"), cve.getConstraintName());
- }
- }
- return pe;
- }
-
- public static Serializable toSerializable(Object obj) throws PageException {
- return caster().toSerializable(obj);
- }
-
- public static Serializable toSerializable(Object obj, Serializable defaultValue) {
- return caster().toSerializable(obj, defaultValue);
- }
-
- public static Struct toStruct(Object obj) throws PageException {
- return caster().toStruct(obj);
- }
-
- public static Struct toStruct(Object obj, Struct defaultValue) {
- return caster().toStruct(obj, defaultValue);
- }
-
- public static SQLItem toSQLItem(Object value, int type) {
- return db().toSQLItem(value, type);
- }
-
- public static SQL toSQL(String sql, SQLItem[] items) {
- return db().toSQL(sql, items);
- }
-
- public static Object toSqlType(SQLItem item) throws PageException {
- return db().toSqlType(item);
- }
-
- public static Object[] toNativeArray(Object obj) throws PageException {
- return caster().toNativeArray(obj);
- }
-
- public static Key toKey(String str) {
- return caster().toKey(str);
- }
-
- public static String toTypeName(Object obj) {
- return caster().toTypeName(obj);
- }
-
- public static Node toXML(Object obj) throws PageException {
- return XMLUtil.toNode(obj);
- }
- /*
- * public static Node toXML(Object obj, Node defaultValue) { return
- * caster().toXML(obj,defaultValue); }
- */
-
- public static Document toDocument(Resource res, Charset cs) throws PageException {
- return XMLUtil.parse(XMLUtil.toInputSource(res, cs), null, false);
- }
-
- public static boolean isArray(Object obj) {
- return decision().isArray(obj);
- }
-
- public static boolean isStruct(Object obj) {
- return decision().isStruct(obj);
- }
-
- public static boolean isAnyType(String type) {
- return decision().isAnyType(type);
- }
-
- public static Array createArray() {
- return creator().createArray();
- }
-
- public static DateTime createDateTime(long time) {
- return creator().createDateTime(time);
- }
-
- public static Property createProperty(String name, String type) {
- return creator().createProperty(name, type);
- }
-
- public static Struct createStruct() {
- return creator().createStruct();
- }
-
- public static Collection.Key createKey(String key) {
- return creator().createKey(key);
- }
-
- public static Query createQuery(Collection.Key[] columns, int rows, String name) throws PageException {
- return creator().createQuery(columns, rows, name);
- }
-
- public static Query createQuery(Collection.Key[] columns, String[] types, int rows, String name) throws PageException {
- return creator().createQuery(columns, types, rows, name);
- }
-
- public static Query createQuery(Array names, Array types, int rows, String name) throws PageException {
- Collection.Key[] knames = new Collection.Key[names.size()];
- String[] ktypes = new String[types.size()];
- for (int i = names.size() - 1; i >= 0; i--) {
- knames[i] = caster().toKey(names.getE(i + 1));
- ktypes[i] = caster().toString(types.getE(i + 1));
- }
- return creator().createQuery(knames, ktypes, rows, name);
- }
-
- public static RefBoolean createRefBoolean() {
- return new RefBooleanImpl();
- }
-
- public static Key[] keys(Collection coll) {
- if (coll == null) return new Key[0];
- Iterator it = coll.keyIterator();
- List rtn = new ArrayList();
- if (it != null) while (it.hasNext()) {
- rtn.add(it.next());
- }
- return rtn.toArray(new Key[rtn.size()]);
- }
-
- private static Creation creator() {
- if (creator == null) creator = CFMLEngineFactory.getInstance().getCreationUtil();
- return creator;
- }
-
- private static Decision decision() {
- if (decision == null) decision = CFMLEngineFactory.getInstance().getDecisionUtil();
- return decision;
- }
-
- private static Cast caster() {
- if (caster == null) caster = CFMLEngineFactory.getInstance().getCastUtil();
- return caster;
- }
-
- private static Operation op() {
- if (op == null) op = CFMLEngineFactory.getInstance().getOperatonUtil();
- return op;
- }
-
- private static lucee.runtime.util.ListUtil list() {
- if (list == null) list = CFMLEngineFactory.getInstance().getListUtil();
- return list;
- }
-
- private static ORMUtil orm() {
- if (orm == null) orm = CFMLEngineFactory.getInstance().getORMUtil();
- return orm;
- }
-
- private static DBUtil db() {
- if (db == null) db = CFMLEngineFactory.getInstance().getDBUtil();
- return db;
- }
-
- /**
- * represents a SQL Statement with his defined arguments for a prepared statement
- */
- static class SQLImpl implements SQL {
-
- private String strSQL;
-
- /**
- * Constructor only with SQL String
- *
- * @param strSQL SQL String
- */
- public SQLImpl(String strSQL) {
- this.strSQL = strSQL;
- }
-
- public void addItems(SQLItem item) {
-
- }
-
- @Override
- public SQLItem[] getItems() {
- return new SQLItem[0];
- }
-
- @Override
- public int getPosition() {
- return 0;
- }
-
- @Override
- public void setPosition(int position) {
- }
-
- @Override
- public String getSQLString() {
- return strSQL;
- }
-
- @Override
- public void setSQLString(String strSQL) {
- this.strSQL = strSQL;
- }
-
- @Override
- public String toString() {
- return strSQL;
- }
-
- @Override
- public String toHashString() {
- return strSQL;
- }
- }
-
- /**
- * Integer Type that can be modified
- */
- public static final class RefBooleanImpl implements RefBoolean {// MUST add interface Castable
-
- private boolean value;
-
- public RefBooleanImpl() {
- }
-
- /**
- * @param value
- */
- public RefBooleanImpl(boolean value) {
- this.value = value;
- }
-
- /**
- * @param value
- */
- @Override
- public void setValue(boolean value) {
- this.value = value;
- }
-
- /**
- * @return returns value as Boolean Object
- */
- @Override
- public Boolean toBoolean() {
- return value ? Boolean.TRUE : Boolean.FALSE;
- }
-
- /**
- * @return returns value as boolean value
- */
- @Override
- public boolean toBooleanValue() {
- return value;
- }
-
- @Override
- public String toString() {
- return value ? "true" : "false";
- }
- }
-
- public static DataSource getDataSource(PageContext pc, String dsn, DataSource defaultValue) {
- if (Util.isEmpty(dsn, true) || dsn.equals("__default__")) return orm().getDefaultDataSource(pc, defaultValue);
- return pc.getDataSource(dsn.trim(), defaultValue);
- }
-
- public static DataSource getDataSource(PageContext pc, String name) throws PageException {
- if (Util.isEmpty(name, true)) return orm().getDefaultDataSource(pc);
- return pc.getDataSource(name);
- }
-
- /*
- * private static Object getDatasourceManager(PageContext pc) throws PageException { try { if
- * (mGetDataSourceManager == null || pc.getClass() != mGetDataSourceManager.getDeclaringClass())
- * mGetDataSourceManager = pc.getClass().getMethod("getDataSourceManager", ZEROC); return
- * mGetDataSourceManager.invoke(pc, ZEROO); } catch (Exception e) { throw
- * CFMLEngineFactory.getInstance().getCastUtil().toPageException(e); } }
- */
-
- public static DatasourceConnection getDatasourceConnection(PageContext pc, DataSource ds, String user, String pass, boolean transactionSensitive) throws PageException {
- if (transactionSensitive) {
- return pc.getDataSourceManager().getConnection(pc, ds, user, pass);
-
- }
-
- DBUtil dbutil = db();
- try {
- if (mGetDatasourceConnection == null || dbutil.getClass() != mGetDatasourceConnection.getDeclaringClass()) {
- mGetDatasourceConnection = dbutil.getClass().getMethod("getDatasourceConnection", GET_DSCONN);
- }
- return (DatasourceConnection) mGetDatasourceConnection.invoke(dbutil, new Object[] { pc, ds, user, pass, false });
- }
- catch (Exception e) {
- throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e);
- }
- /*
- * Object manager = getDatasourceManager(pc); try { if (mGetConnection == null || manager.getClass()
- * != mGetConnection.getDeclaringClass()) { mGetConnection =
- * manager.getClass().getMethod("getConnection", GET_CONN); } return (DatasourceConnection)
- * mGetConnection.invoke(manager, new Object[] { pc, ds, user, pass }); } catch (Exception e) {
- * throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e); }
- */
- }
-
- public static void releaseDatasourceConnection(PageContext pc, DatasourceConnection dc, boolean transactionSensitive) throws PageException {
- // print.ds("rel:" + transactionSensitive);
- if (transactionSensitive) {
- pc.getDataSourceManager().releaseConnection(pc, dc);
- return;
- }
-
- DBUtil dbutil = db();
- try {
- if (mReleaseDatasourceConnection == null || dbutil.getClass() != mReleaseDatasourceConnection.getDeclaringClass()) {
- mReleaseDatasourceConnection = dbutil.getClass().getMethod("releaseDatasourceConnection", REL_DSCONN);
- }
- mReleaseDatasourceConnection.invoke(dbutil, new Object[] { pc, dc, false });
- }
- catch (Exception e) {
- throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(e);
- }
-
- /*
- * Object manager = getDatasourceManager(pc); try { if (mReleaseConnection == null ||
- * manager.getClass() != mReleaseConnection.getDeclaringClass()) { mReleaseConnection =
- * manager.getClass().getMethod("releaseConnection", REL_CONN); } mReleaseConnection.invoke(manager,
- * new Object[] { pc, dc }); } catch (Exception e) { throw
- * CFMLEngineFactory.getInstance().getCastUtil().toPageException(e); }
- */
- }
-
- public static Mapping createMapping(Config config, String virtual, String physical) {
- return creator().createMapping(config, virtual, physical, null, INSPECT_UNDEFINED, true, false, false, false, true, true, null, -1, -1);
- }
-
- public static String last(String list, String delimiter) {
- return list().last(list, delimiter, true);
- }
-
- public static int listFindNoCaseIgnoreEmpty(String list, String value, char delimiter) {
- return list().findNoCaseIgnoreEmpty(list, value, delimiter);
- }
-
- public static String[] trimItems(String[] arr) {
- for (int i = 0; i < arr.length; i++) {
- arr[i] = arr[i].trim();
- }
- return arr;
- }
-
- public static Document getDocument(Node node) {
- return XMLUtil.getDocument(node);
- }
-
- public static Document newDocument() throws PageException {
- return XMLUtil.newDocument();
- }
-
- public static void setFirst(Node parent, Node node) {
- XMLUtil.setFirst(parent, node);
- }
-
- public static Property[] getProperties(Component c, boolean onlyPeristent, boolean includeBaseProperties, boolean preferBaseProperties, boolean inheritedMappedSuperClassOnly) {
- return c.getProperties(onlyPeristent, includeBaseProperties, preferBaseProperties, inheritedMappedSuperClassOnly);
- }
-
- public static void write(Resource res, String string, Charset cs, boolean append) throws IOException {
- if (cs == null) cs = getCharset();
-
- Writer writer = null;
- try {
- writer = getWriter(res, cs, append);
- writer.write(string);
- }
- finally {
- closeEL(writer);
- }
- }
-
- public static Writer getWriter(Resource res, Charset charset, boolean append) throws IOException {
- OutputStream os = null;
- try {
- os = res.getOutputStream(append);
- }
- catch (IOException ioe) {
- closeEL(os);
- throw ioe;
- }
- return getWriter(os, charset);
- }
-
- public static Writer getWriter(OutputStream os, Charset cs) {
- if (cs == null) cs = getCharset();
- return new BufferedWriter(new OutputStreamWriter(os, getCharset()));
- }
-
- public static BufferedReader toBufferedReader(Resource res, Charset charset) throws IOException {
- return toBufferedReader(getReader(res, (Charset) null));
- }
-
- public static boolean equalsComplexEL(Object left, Object right) {
- return op().equalsComplexEL(left, right, false, true);
- }
-
- public static PageContext pc() {
- return CFMLEngineFactory.getInstance().getThreadPageContext();
- }
-
- public static Config config() {
- return pc().getConfig();
- }
-
- public static void closeEL(OutputStream os) {
- if (os != null) {
- try {
- os.close();
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
- }
-
- public static void closeEL(Writer w) {
- if (w != null) {
- try {
- w.close();
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
- }
-
- public static void closeEL(ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
- }
-
- public static void closeEL(InputStream is) {
- try {
- if (is != null) is.close();
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
-
- public static void closeEL(Reader r) {
- try {
- if (r != null) r.close();
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
-
- public static boolean isRelated(Property property) {
- return orm().isRelated(property);
- }
-
- public static Object convertToSimpleMap(String paramsStr) {
- return orm().convertToSimpleMap(paramsStr);
- }
-
- public static String getDataSourceName(PageContext pc, Component cfc) throws PageException {
- return orm().getDataSourceName(pc, cfc);
- }
-
- public static DataSource getDataSource(PageContext pc, Component cfc) throws PageException {
- return orm().getDataSource(pc, cfc);
- }
-
- public static boolean equals(Component l, Component r) {
- // TODO Auto-generated method stub
- return orm().equals(l, r);
- }
-
- public static DataSource getDefaultDataSource(PageContext pc) throws PageException {
- return orm().getDefaultDataSource(pc);
- }
-
- public static Object getPropertyValue(Component cfc, String name, Object defaultValue) {
- return orm().getPropertyValue(cfc, name, defaultValue);
- }
-
- public static String toString(Node node, boolean omitXMLDecl, boolean indent, String publicId, String systemId, String encoding) throws PageException {
- return XMLUtil.toString(node, omitXMLDecl, indent, publicId, systemId, encoding);
- }
-
- public static Locale toLocale(String strLocale) throws PageException {
- return caster().toLocale(strLocale);
- }
-
- public static TimeZone toTimeZone(Object value, Object obj) throws PageException {
- return caster().toTimeZone(obj);
- }
-
- public static Character toCharacter(Object value) throws PageException {
- return caster().toCharacter(value);
- }
-
- public static DateTime toDate(Object value, TimeZone timeZone) throws PageException {
- return caster().toDate(value, timeZone);
- }
-
- public static Calendar toCalendar(DateTime date, TimeZone timeZone, Locale locale) {
- return caster().toCalendar(date.getTime(), timeZone, locale);
- }
-}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/Dialect.java b/source/java/src/org/lucee/extension/orm/hibernate/Dialect.java
index 97b736b6..dc7bf948 100755
--- a/source/java/src/org/lucee/extension/orm/hibernate/Dialect.java
+++ b/source/java/src/org/lucee/extension/orm/hibernate/Dialect.java
@@ -6,169 +6,194 @@
import java.util.Iterator;
import org.apache.felix.framework.BundleWiringImpl.BundleClassLoader;
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
import org.osgi.framework.Bundle;
-import lucee.loader.engine.CFMLEngineFactory;
import lucee.loader.util.Util;
import lucee.runtime.db.DataSource;
import lucee.runtime.type.Struct;
-import lucee.runtime.util.ListUtil;
+/**
+ * Hibernate Dialect manager
+ */
public class Dialect {
- private static Struct dialects = CommonUtil.createStruct();
+ private static Struct dialects = CommonUtil.createStruct();
- static {
+ static {
- try {
- BundleClassLoader bcl = (BundleClassLoader) org.hibernate.dialect.SybaseDialect.class.getClassLoader();
- Bundle b = bcl.getBundle();
+ try {
+ BundleClassLoader bcl = (BundleClassLoader) org.hibernate.dialect.SybaseDialect.class.getClassLoader();
+ Bundle b = bcl.getBundle();
- // List all XML files in the OSGI-INF directory and below
- ListUtil util = CFMLEngineFactory.getInstance().getListUtil();
- Enumeration e = b.findEntries("org/hibernate/dialect", "*.class", true);
- String path;
- while (e.hasMoreElements()) {
- try {
- path = e.nextElement().getPath();
- if (path.startsWith("/")) path = path.substring(1);
- else if (path.startsWith("\\")) path = path.substring(1);
- if (path.endsWith(".class")) path = path.substring(0, path.length() - 6);
- path = path.replace('/', '.');
- path = path.replace('\\', '.');
- String name;
- Class> clazz = bcl.loadClass(path);
- if (org.hibernate.dialect.Dialect.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
- dialects.setEL(CommonUtil.createKey(path), path);
- dialects.setEL(CommonUtil.createKey(CommonUtil.last(path, ".")), path);
- name = CommonUtil.last(path, ".");
- dialects.setEL(CommonUtil.createKey(name), path);
- if (name.endsWith("Dialect")) {
- name = name.substring(0, name.length() - 7);
- dialects.setEL(CommonUtil.createKey(name), path);
- }
+ // List all XML files in the OSGI-INF directory and below
+ Enumeration e = b.findEntries("org/hibernate/dialect", "*.class", true);
+ String path;
+ while (e.hasMoreElements()) {
+ try {
+ path = e.nextElement().getPath();
+ if (path.startsWith("/"))
+ path = path.substring(1);
+ else if (path.startsWith("\\"))
+ path = path.substring(1);
+ if (path.endsWith(".class"))
+ path = path.substring(0, path.length() - 6);
+ path = path.replace('/', '.');
+ path = path.replace('\\', '.');
+ String name;
+ Class> clazz = bcl.loadClass(path);
+ if (org.hibernate.dialect.Dialect.class.isAssignableFrom(clazz)
+ && !Modifier.isAbstract(clazz.getModifiers())) {
+ dialects.setEL(CommonUtil.createKey(path), path);
+ dialects.setEL(CommonUtil.createKey(CommonUtil.last(path, ".")), path);
+ name = CommonUtil.last(path, ".");
+ dialects.setEL(CommonUtil.createKey(name), path);
+ if (name.endsWith("Dialect")) {
+ name = name.substring(0, name.length() - 7);
+ dialects.setEL(CommonUtil.createKey(name), path);
+ }
- // print.e("dialects.setEL(\"" + name + "\",\"" + path + "\");");
- }
- }
- catch (Exception exx) {
- exx.printStackTrace();
- }
- }
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- dialects.setEL("CUBRID", "org.hibernate.dialect.CUBRIDDialect");
- dialects.setEL("Cache71", "org.hibernate.dialect.Cache71Dialect");
- dialects.setEL("CockroachDB192", "org.hibernate.dialect.CockroachDB192Dialect");
- dialects.setEL("CockroachDB201", "org.hibernate.dialect.CockroachDB201Dialect");
- dialects.setEL("DB2390", "org.hibernate.dialect.DB2390Dialect");
- dialects.setEL("DB2390V8", "org.hibernate.dialect.DB2390V8Dialect");
- dialects.setEL("DB2400", "org.hibernate.dialect.DB2400Dialect");
- dialects.setEL("DB2400V7R3", "org.hibernate.dialect.DB2400V7R3Dialect");
- dialects.setEL("DB297", "org.hibernate.dialect.DB297Dialect");
- dialects.setEL("DB2", "org.hibernate.dialect.DB2Dialect");
- dialects.setEL("DataDirectOracle9", "org.hibernate.dialect.DataDirectOracle9Dialect");
- dialects.setEL("Derby", "org.hibernate.dialect.DerbyDialect");
- dialects.setEL("DerbyTenFive", "org.hibernate.dialect.DerbyTenFiveDialect");
- dialects.setEL("DerbyTenSeven", "org.hibernate.dialect.DerbyTenSevenDialect");
- dialects.setEL("DerbyTenSix", "org.hibernate.dialect.DerbyTenSixDialect");
- dialects.setEL("Firebird", "org.hibernate.dialect.FirebirdDialect");
- dialects.setEL("FrontBase", "org.hibernate.dialect.FrontBaseDialect");
- dialects.setEL("H2", "org.hibernate.dialect.H2Dialect");
- dialects.setEL("HANACloudColumnStore", "org.hibernate.dialect.HANACloudColumnStoreDialect");
- dialects.setEL("HANAColumnStore", "org.hibernate.dialect.HANAColumnStoreDialect");
- dialects.setEL("HANARowStore", "org.hibernate.dialect.HANARowStoreDialect");
- dialects.setEL("HSQL", "org.hibernate.dialect.HSQLDialect");
- dialects.setEL("Informix10", "org.hibernate.dialect.Informix10Dialect");
- dialects.setEL("Informix", "org.hibernate.dialect.InformixDialect");
- dialects.setEL("Ingres10", "org.hibernate.dialect.Ingres10Dialect");
- dialects.setEL("Ingres9", "org.hibernate.dialect.Ingres9Dialect");
- dialects.setEL("Ingres", "org.hibernate.dialect.IngresDialect");
- dialects.setEL("Interbase", "org.hibernate.dialect.InterbaseDialect");
- dialects.setEL("JDataStore", "org.hibernate.dialect.JDataStoreDialect");
- dialects.setEL("MariaDB102", "org.hibernate.dialect.MariaDB102Dialect");
- dialects.setEL("MariaDB103", "org.hibernate.dialect.MariaDB103Dialect");
- dialects.setEL("MariaDB10", "org.hibernate.dialect.MariaDB10Dialect");
- dialects.setEL("MariaDB53", "org.hibernate.dialect.MariaDB53Dialect");
- dialects.setEL("MariaDB", "org.hibernate.dialect.MariaDBDialect");
- dialects.setEL("Mckoi", "org.hibernate.dialect.MckoiDialect");
- dialects.setEL("MimerSQL", "org.hibernate.dialect.MimerSQLDialect");
- dialects.setEL("MySQL55", "org.hibernate.dialect.MySQL55Dialect");
- dialects.setEL("MySQL57", "org.hibernate.dialect.MySQL57Dialect");
- dialects.setEL("MySQL57InnoDB", "org.hibernate.dialect.MySQL57InnoDBDialect");
- dialects.setEL("MySQL5", "org.hibernate.dialect.MySQL5Dialect");
- dialects.setEL("MySQL5InnoDB", "org.hibernate.dialect.MySQL5InnoDBDialect");
- dialects.setEL("MySQL8", "org.hibernate.dialect.MySQL8Dialect");
- dialects.setEL("MySQL", "org.hibernate.dialect.MySQL8Dialect");
- dialects.setEL("MySQLInnoDB", "org.hibernate.dialect.MySQLInnoDBDialect");
- dialects.setEL("MySQLMyISAM", "org.hibernate.dialect.MySQLMyISAMDialect");
- dialects.setEL("Oracle10g", "org.hibernate.dialect.Oracle10gDialect");
- dialects.setEL("Oracle12c", "org.hibernate.dialect.Oracle12cDialect");
- dialects.setEL("Oracle8i", "org.hibernate.dialect.Oracle8iDialect");
- dialects.setEL("Oracle9", "org.hibernate.dialect.Oracle9Dialect");
- dialects.setEL("Oracle9i", "org.hibernate.dialect.Oracle9iDialect");
- dialects.setEL("Oracle", "org.hibernate.dialect.OracleDialect");
- dialects.setEL("Pointbase", "org.hibernate.dialect.PointbaseDialect");
- dialects.setEL("PostgreSQL10", "org.hibernate.dialect.PostgreSQL10Dialect");
- dialects.setEL("PostgreSQL81", "org.hibernate.dialect.PostgreSQL81Dialect");
- dialects.setEL("PostgreSQL82", "org.hibernate.dialect.PostgreSQL82Dialect");
- dialects.setEL("PostgreSQL91", "org.hibernate.dialect.PostgreSQL91Dialect");
- dialects.setEL("PostgreSQL92", "org.hibernate.dialect.PostgreSQL92Dialect");
- dialects.setEL("PostgreSQL93", "org.hibernate.dialect.PostgreSQL93Dialect");
- dialects.setEL("PostgreSQL94", "org.hibernate.dialect.PostgreSQL94Dialect");
- dialects.setEL("PostgreSQL95", "org.hibernate.dialect.PostgreSQL95Dialect");
- dialects.setEL("PostgreSQL9", "org.hibernate.dialect.PostgreSQL9Dialect");
- dialects.setEL("PostgreSQL", "org.hibernate.dialect.PostgreSQLDialect");
- dialects.setEL("PostgresPlus", "org.hibernate.dialect.PostgresPlusDialect");
- dialects.setEL("Progress", "org.hibernate.dialect.ProgressDialect");
- dialects.setEL("RDMSOS2200", "org.hibernate.dialect.RDMSOS2200Dialect");
- dialects.setEL("SAPDB", "org.hibernate.dialect.SAPDBDialect");
- dialects.setEL("SQLServer2005", "org.hibernate.dialect.SQLServer2005Dialect");
- dialects.setEL("SQLServer2008", "org.hibernate.dialect.SQLServer2008Dialect");
- dialects.setEL("SQLServer2012", "org.hibernate.dialect.SQLServer2012Dialect");
- dialects.setEL("SQLServer", "org.hibernate.dialect.SQLServerDialect");
- dialects.setEL("Sybase11", "org.hibernate.dialect.Sybase11Dialect");
- dialects.setEL("SybaseASE157", "org.hibernate.dialect.SybaseASE157Dialect");
- dialects.setEL("SybaseASE15", "org.hibernate.dialect.SybaseASE15Dialect");
- dialects.setEL("SybaseAnywhere", "org.hibernate.dialect.SybaseAnywhereDialect");
- dialects.setEL("Sybase", "org.hibernate.dialect.SybaseDialect");
- dialects.setEL("Teradata14", "org.hibernate.dialect.Teradata14Dialect");
- dialects.setEL("Teradata", "org.hibernate.dialect.TeradataDialect");
- dialects.setEL("TimesTen", "org.hibernate.dialect.TimesTenDialect");
+ // print.e("dialects.setEL(\"" + name + "\",\"" + path + "\");");
+ }
+ } catch (Exception exx) {
+ exx.printStackTrace();
+ }
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
- }
+ dialects.setEL(CommonUtil.createKey("CUBRID"), "org.hibernate.dialect.CUBRIDDialect");
+ dialects.setEL(CommonUtil.createKey("Cache71"), "org.hibernate.dialect.Cache71Dialect");
+ dialects.setEL(CommonUtil.createKey("CockroachDB192"), "org.hibernate.dialect.CockroachDB192Dialect");
+ dialects.setEL(CommonUtil.createKey("CockroachDB201"), "org.hibernate.dialect.CockroachDB201Dialect");
+ dialects.setEL(CommonUtil.createKey("DB2390"), "org.hibernate.dialect.DB2390Dialect");
+ dialects.setEL(CommonUtil.createKey("DB2390V8"), "org.hibernate.dialect.DB2390V8Dialect");
+ dialects.setEL(CommonUtil.createKey("DB2400"), "org.hibernate.dialect.DB2400Dialect");
+ dialects.setEL(CommonUtil.createKey("DB2400V7R3"), "org.hibernate.dialect.DB2400V7R3Dialect");
+ dialects.setEL(CommonUtil.createKey("DB297"), "org.hibernate.dialect.DB297Dialect");
+ dialects.setEL(CommonUtil.createKey("DB2"), "org.hibernate.dialect.DB2Dialect");
+ dialects.setEL(CommonUtil.createKey("DataDirectOracle9"), "org.hibernate.dialect.DataDirectOracle9Dialect");
+ dialects.setEL(CommonUtil.createKey("Derby"), "org.hibernate.dialect.DerbyDialect");
+ dialects.setEL(CommonUtil.createKey("DerbyTenFive"), "org.hibernate.dialect.DerbyTenFiveDialect");
+ dialects.setEL(CommonUtil.createKey("DerbyTenSeven"), "org.hibernate.dialect.DerbyTenSevenDialect");
+ dialects.setEL(CommonUtil.createKey("DerbyTenSix"), "org.hibernate.dialect.DerbyTenSixDialect");
+ dialects.setEL(CommonUtil.createKey("Firebird"), "org.hibernate.dialect.FirebirdDialect");
+ dialects.setEL(CommonUtil.createKey("FrontBase"), "org.hibernate.dialect.FrontBaseDialect");
+ dialects.setEL(CommonUtil.createKey("H2"), "org.hibernate.dialect.H2Dialect");
+ dialects.setEL(CommonUtil.createKey("HANACloudColumnStore"),
+ "org.hibernate.dialect.HANACloudColumnStoreDialect");
+ dialects.setEL(CommonUtil.createKey("HANAColumnStore"), "org.hibernate.dialect.HANAColumnStoreDialect");
+ dialects.setEL(CommonUtil.createKey("HANARowStore"), "org.hibernate.dialect.HANARowStoreDialect");
+ dialects.setEL(CommonUtil.createKey("HSQL"), "org.hibernate.dialect.HSQLDialect");
+ dialects.setEL(CommonUtil.createKey("Informix10"), "org.hibernate.dialect.Informix10Dialect");
+ dialects.setEL(CommonUtil.createKey("Informix"), "org.hibernate.dialect.InformixDialect");
+ dialects.setEL(CommonUtil.createKey("Ingres10"), "org.hibernate.dialect.Ingres10Dialect");
+ dialects.setEL(CommonUtil.createKey("Ingres9"), "org.hibernate.dialect.Ingres9Dialect");
+ dialects.setEL(CommonUtil.createKey("Ingres"), "org.hibernate.dialect.IngresDialect");
+ dialects.setEL(CommonUtil.createKey("Interbase"), "org.hibernate.dialect.InterbaseDialect");
+ dialects.setEL(CommonUtil.createKey("JDataStore"), "org.hibernate.dialect.JDataStoreDialect");
+ dialects.setEL(CommonUtil.createKey("MariaDB102"), "org.hibernate.dialect.MariaDB102Dialect");
+ dialects.setEL(CommonUtil.createKey("MariaDB103"), "org.hibernate.dialect.MariaDB103Dialect");
+ dialects.setEL(CommonUtil.createKey("MariaDB10"), "org.hibernate.dialect.MariaDB10Dialect");
+ dialects.setEL(CommonUtil.createKey("MariaDB53"), "org.hibernate.dialect.MariaDB53Dialect");
+ dialects.setEL(CommonUtil.createKey("MariaDB"), "org.hibernate.dialect.MariaDBDialect");
+ dialects.setEL(CommonUtil.createKey("Mckoi"), "org.hibernate.dialect.MckoiDialect");
+ dialects.setEL(CommonUtil.createKey("MimerSQL"), "org.hibernate.dialect.MimerSQLDialect");
+ dialects.setEL(CommonUtil.createKey("MySQL55"), "org.hibernate.dialect.MySQL55Dialect");
+ dialects.setEL(CommonUtil.createKey("MySQL57"), "org.hibernate.dialect.MySQL57Dialect");
+ dialects.setEL(CommonUtil.createKey("MySQL57InnoDB"), "org.hibernate.dialect.MySQL57InnoDBDialect");
+ dialects.setEL(CommonUtil.createKey("MySQL5"), "org.hibernate.dialect.MySQL5Dialect");
+ dialects.setEL(CommonUtil.createKey("MySQL5InnoDB"), "org.hibernate.dialect.MySQL5InnoDBDialect");
+ dialects.setEL(CommonUtil.createKey("MySQL8"), "org.hibernate.dialect.MySQL8Dialect");
+ dialects.setEL(CommonUtil.createKey("MySQL"), "org.hibernate.dialect.MySQL8Dialect");
+ dialects.setEL(CommonUtil.createKey("MySQLInnoDB"), "org.hibernate.dialect.MySQLInnoDBDialect");
+ dialects.setEL(CommonUtil.createKey("MySQLMyISAM"), "org.hibernate.dialect.MySQLMyISAMDialect");
+ dialects.setEL(CommonUtil.createKey("Oracle10g"), "org.hibernate.dialect.Oracle10gDialect");
+ dialects.setEL(CommonUtil.createKey("Oracle12c"), "org.hibernate.dialect.Oracle12cDialect");
+ dialects.setEL(CommonUtil.createKey("Oracle8i"), "org.hibernate.dialect.Oracle8iDialect");
+ dialects.setEL(CommonUtil.createKey("Oracle9"), "org.hibernate.dialect.Oracle9Dialect");
+ dialects.setEL(CommonUtil.createKey("Oracle9i"), "org.hibernate.dialect.Oracle9iDialect");
+ dialects.setEL(CommonUtil.createKey("Oracle"), "org.hibernate.dialect.OracleDialect");
+ dialects.setEL(CommonUtil.createKey("Pointbase"), "org.hibernate.dialect.PointbaseDialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL10"), "org.hibernate.dialect.PostgreSQL10Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL81"), "org.hibernate.dialect.PostgreSQL81Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL82"), "org.hibernate.dialect.PostgreSQL82Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL91"), "org.hibernate.dialect.PostgreSQL91Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL92"), "org.hibernate.dialect.PostgreSQL92Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL93"), "org.hibernate.dialect.PostgreSQL93Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL94"), "org.hibernate.dialect.PostgreSQL94Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL95"), "org.hibernate.dialect.PostgreSQL95Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL9"), "org.hibernate.dialect.PostgreSQL9Dialect");
+ dialects.setEL(CommonUtil.createKey("PostgreSQL"), "org.hibernate.dialect.PostgreSQLDialect");
+ dialects.setEL(CommonUtil.createKey("PostgresPlus"), "org.hibernate.dialect.PostgresPlusDialect");
+ dialects.setEL(CommonUtil.createKey("Progress"), "org.hibernate.dialect.ProgressDialect");
+ dialects.setEL(CommonUtil.createKey("RDMSOS2200"), "org.hibernate.dialect.RDMSOS2200Dialect");
+ dialects.setEL(CommonUtil.createKey("SAPDB"), "org.hibernate.dialect.SAPDBDialect");
+ dialects.setEL(CommonUtil.createKey("SQLServer2005"), "org.hibernate.dialect.SQLServer2005Dialect");
+ dialects.setEL(CommonUtil.createKey("SQLServer2008"), "org.hibernate.dialect.SQLServer2008Dialect");
+ dialects.setEL(CommonUtil.createKey("SQLServer2012"), "org.hibernate.dialect.SQLServer2012Dialect");
+ dialects.setEL(CommonUtil.createKey("SQLServer"), "org.hibernate.dialect.SQLServerDialect");
+ dialects.setEL(CommonUtil.createKey("Sybase11"), "org.hibernate.dialect.Sybase11Dialect");
+ dialects.setEL(CommonUtil.createKey("SybaseASE157"), "org.hibernate.dialect.SybaseASE157Dialect");
+ dialects.setEL(CommonUtil.createKey("SybaseASE15"), "org.hibernate.dialect.SybaseASE15Dialect");
+ dialects.setEL(CommonUtil.createKey("SybaseAnywhere"), "org.hibernate.dialect.SybaseAnywhereDialect");
+ dialects.setEL(CommonUtil.createKey("Sybase"), "org.hibernate.dialect.SybaseDialect");
+ dialects.setEL(CommonUtil.createKey("Teradata14"), "org.hibernate.dialect.Teradata14Dialect");
+ dialects.setEL(CommonUtil.createKey("Teradata"), "org.hibernate.dialect.TeradataDialect");
+ dialects.setEL(CommonUtil.createKey("TimesTen"), "org.hibernate.dialect.TimesTenDialect");
- /**
- * return a SQL dialect that match the given Name
- *
- * @param name
- * @return
- */
- public static String getDialect(DataSource ds) {
- String name = ds.getClassDefinition().getClassName();
- if ("net.sourceforge.jtds.jdbc.Driver".equalsIgnoreCase(name)) {
- String dsn = ds.getDsnTranslated();
- if (dsn.toLowerCase().indexOf("sybase") != -1) return getDialect("Sybase");
- return getDialect("SQLServer");
- }
- return getDialect(name);
- }
+ }
- public static String getDialect(String name) {
- String d = _getDialect(name);
+ /**
+ * Get the Hibernate dialect for the given Datasource
+ *
+ * @param ds
+ * - Datasource object to check dialect on
+ *
+ * @return the string dialect value, like "org.hibernate.dialect.PostgreSQLDialect"
+ */
+ public static String getDialect(DataSource ds) {
+ String name = ds.getClassDefinition().getClassName();
+ if ("net.sourceforge.jtds.jdbc.Driver".equalsIgnoreCase(name)) {
+ String dsn = ds.getConnectionStringTranslated();
+ if (dsn.toLowerCase().indexOf("sybase") != -1)
+ return getDialect("Sybase");
+ return getDialect("SQLServer");
+ }
+ return getDialect(name);
+ }
- // print.e(name + ":" + d);
- return d;
- }
+ /**
+ * Return a SQL dialect that match the given Name
+ *
+ * @param name
+ * - Dialect name like "Oracle" or "MySQL57"
+ *
+ * @return the full dialect string name, like "org.hibernate.dialect.OracleDialect" or
+ * "org.hibernate.dialect.MySQL57Dialect"
+ */
+ public static String getDialect(String name) {
+ if (Util.isEmpty(name))
+ return null;
+ String dialect = (String) dialects.get(CommonUtil.createKey(name), null);
+ return dialect;
+ }
- public static String _getDialect(String name) {
- if (Util.isEmpty(name)) return null;
- String dialect = (String) dialects.get(CommonUtil.createKey(name), null);
- return dialect;
- }
+ /**
+ * Get all configurable dialects
+ *
+ * @return the configured dialects
+ */
+ public static Struct getDialects() {
+ return dialects;
+ }
- public static Iterator getDialectNames() {
- return dialects.keysAsStringIterator();
- }
+ /**
+ * Get an iterator of dialect key names
+ *
+ * @return a String iteratator to iterate over all known dialects
+ */
+ public static Iterator getDialectNames() {
+ return dialects.keysAsStringIterator();
+ }
}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/Entity.java b/source/java/src/org/lucee/extension/orm/hibernate/Entity.java
deleted file mode 100755
index 173e6a41..00000000
--- a/source/java/src/org/lucee/extension/orm/hibernate/Entity.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package org.lucee.extension.orm.hibernate;
-
-public interface Entity {
- public String name();
-}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/ExceptionUtil.java b/source/java/src/org/lucee/extension/orm/hibernate/ExceptionUtil.java
deleted file mode 100644
index 35be5014..00000000
--- a/source/java/src/org/lucee/extension/orm/hibernate/ExceptionUtil.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package org.lucee.extension.orm.hibernate;
-
-import java.lang.reflect.Method;
-
-import lucee.loader.engine.CFMLEngineFactory;
-import lucee.runtime.Component;
-import lucee.runtime.db.DataSource;
-import lucee.runtime.exp.PageException;
-import lucee.runtime.orm.ORMSession;
-import lucee.runtime.type.Collection.Key;
-
-public class ExceptionUtil {
-
- private static Method setAdditional;
-
- public static PageException createException(SessionFactoryData data, Component cfc, String msg, String detail) {
-
- PageException pe = createException((ORMSession) null, cfc, msg, detail);
- if (data != null) setAddional(pe, data);
- return pe;
- }
-
- public static PageException createException(SessionFactoryData data, Component cfc, Throwable t) {
- PageException pe = createException((ORMSession) null, cfc, t);
- if (data != null) setAddional(pe, data);
- return pe;
- }
-
- public static PageException createException(ORMSession session, Component cfc, Throwable t) {
- return CFMLEngineFactory.getInstance().getORMUtil().createException(session, cfc, t);
- }
-
- public static PageException createException(ORMSession session, Component cfc, String message, String detail) {
- return CFMLEngineFactory.getInstance().getORMUtil().createException(session, cfc, message, detail);
- }
-
- private static void setAddional(PageException pe, SessionFactoryData data) {
- setAdditional(pe, CommonUtil.createKey("Entities"), CFMLEngineFactory.getInstance().getListUtil().toListEL(data.getEntityNames(), ", "));
- setAddional(pe, data.getDataSources());
- }
-
- private static void setAddional(PageException pe, DataSource... sources) {
- if (sources != null && sources.length > 0) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < sources.length; i++) {
- if (i > 0) sb.append(", ");
- sb.append(sources[i].getName());
- }
- setAdditional(pe, CommonUtil.createKey("_Datasource"), sb.toString());
- }
- }
-
- public static void setAdditional(PageException pe, Key name, Object value) {
- try {
- if (setAdditional == null || setAdditional.getDeclaringClass() != pe.getClass()) {
- setAdditional = pe.getClass().getMethod("setAdditional", new Class[] { Key.class, Object.class });
- }
- setAdditional.invoke(pe, new Object[] { name, value });
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
-}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/HBMCreator.java b/source/java/src/org/lucee/extension/orm/hibernate/HBMCreator.java
index ef596811..f939f16d 100755
--- a/source/java/src/org/lucee/extension/orm/hibernate/HBMCreator.java
+++ b/source/java/src/org/lucee/extension/orm/hibernate/HBMCreator.java
@@ -1,5 +1,6 @@
package org.lucee.extension.orm.hibernate;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@@ -11,7 +12,6 @@
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-import lucee.commons.io.log.Log;
import lucee.loader.util.Util;
import lucee.runtime.Component;
import lucee.runtime.PageContext;
@@ -20,1797 +20,2188 @@
import lucee.runtime.exp.PageException;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
+
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ExceptionUtil;
+import org.lucee.extension.orm.hibernate.util.HibernateUtil;
+import org.lucee.extension.orm.hibernate.util.ORMConfigurationUtil;
+import org.lucee.extension.orm.hibernate.util.XMLUtil;
import lucee.runtime.type.Struct;
+import lucee.commons.io.res.Resource;
public class HBMCreator {
- private static final Collection.Key PROPERTY = CommonUtil.createKey("property");
- private static final Collection.Key LINK_TABLE = CommonUtil.createKey("linktable");
- private static final Collection.Key CFC = CommonUtil.createKey("cfc");
- private static final Collection.Key GENERATOR = CommonUtil.createKey("generator");
- private static final Collection.Key PARAMS = CommonUtil.createKey("params");
- private static final Collection.Key SEQUENCE = CommonUtil.createKey("sequence");
- private static final Collection.Key UNIQUE_KEY_NAME = CommonUtil.createKey("uniqueKeyName");
- private static final Collection.Key GENERATED = CommonUtil.createKey("generated");
- private static final Collection.Key FIELDTYPE = CommonUtil.createKey("fieldtype");
- private static final Collection.Key KEY = CommonUtil.createKey("key");
- private static final Collection.Key TYPE = CommonUtil.createKey("type");
-
- public static void createXMLMapping(PageContext pc, DatasourceConnection dc, Component cfc, Element hibernateMapping, SessionFactoryData data) throws PageException {
-
- // MUST Support for embeded objects
- Struct meta = cfc.getMetaData(pc);
-
- String extend = cfc.getExtends();
- boolean isClass = Util.isEmpty(extend);
-
- // MZ: Fetches all inherited persistent properties
- // Property[] _props=getAllPersistentProperties(pc,cfc,dc,meta,isClass);
-
- Property[] _props = getProperties(pc, cfc, dc, meta, isClass, true, data);
-
- Map joins = new HashMap();
- PropertyCollection propColl = splitJoins(cfc, joins, _props, data);
-
- // create class element and attach
- Document doc = CommonUtil.getDocument(hibernateMapping);
-
- StringBuilder comment = new StringBuilder();
- comment.append("\nsource:").append(cfc.getPageSource().getDisplayPath());
- comment.append("\ncompilation-time:").append(CommonUtil.createDateTime(HibernateUtil.getCompileTime(pc, cfc.getPageSource())));
- comment.append("\ndatasource:").append(dc.getDatasource().getName());
- comment.append("\n");
-
- hibernateMapping.appendChild(doc.createComment(comment.toString()));
-
- // print.e(cfc.getAbsName()+";"+isClass+" -> "+cfci.getBaseAbsName()+":"+cfci.isBasePeristent());
- if (!isClass && !cfc.isBasePeristent()) {
- isClass = true;
- }
-
- Element join = null;
- boolean doTable = true;
-
- Element clazz;
- if (isClass) {
- clazz = doc.createElement("class");
- hibernateMapping.appendChild(clazz);
- }
- // extended CFC
- else {
- // MZ: Fetches one level deep
- _props = getProperties(pc, cfc, dc, meta, isClass, false, data);
- // MZ: Reinitiate the property collection
- propColl = splitJoins(cfc, joins, _props, data);
-
- String ext = CommonUtil.last(extend, ".").trim();
- try {
- Component base = data.getEntityByCFCName(ext, false);
- ext = HibernateCaster.getEntityName(base);
- }
- catch (Exception e) {
- Log log = pc.getConfig().getLog("orm");
- log.error("hibernate", e);
- }
-
- String discriminatorValue = toString(cfc, null, meta, "discriminatorValue", data);
- if (!Util.isEmpty(discriminatorValue, true)) {
- doTable = false;
- clazz = doc.createElement("subclass");
- hibernateMapping.appendChild(clazz);
- // addClassAttributes(classNode);
- clazz.setAttribute("extends", ext);
- clazz.setAttribute("discriminator-value", discriminatorValue);
-
- String joincolumn = toString(cfc, null, meta, "joincolumn", false, data);
- if (!Util.isEmpty(joincolumn)) {
- join = doc.createElement("join");
- clazz.appendChild(join);
- doTable = true;
- Element key = doc.createElement("key");
- join.appendChild(key);
- key.setAttribute("column", formatColumn(joincolumn, data));
- }
-
- }
- else {
- // MZ: Match on joinColumn for a joined subclass, otherwise use a union subclass
- String joinColumn = toString(cfc, null, meta, "joincolumn", false, data);
- if (!Util.isEmpty(joinColumn, true)) {
- clazz = doc.createElement("joined-subclass");
- hibernateMapping.appendChild(clazz);
- clazz.setAttribute("extends", ext);
- Element key = doc.createElement("key");
- clazz.appendChild(key);
- key.setAttribute("column", formatColumn(joinColumn, data));
- }
- else {
- // MZ: When no joinColumn exists, default to an explicit table per class
- clazz = doc.createElement("union-subclass");
- clazz.setAttribute("extends", ext);
- doTable = true;
- hibernateMapping.appendChild(clazz);
- }
-
- }
- }
-
- // createXMLMappingTuplizer(clazz,pc);
-
- addGeneralClassAttributes(pc, cfc, meta, clazz, data);
- String tableName = getTableName(pc, meta, cfc, data);
-
- if (join != null) clazz = join;
- if (doTable) addGeneralTableAttributes(pc, dc, cfc, meta, clazz, data);
-
- Struct columnsInfo = null;
- if (data.getORMConfiguration().useDBForMapping()) {
- columnsInfo = data.getTableInfo(dc, getTableName(pc, meta, cfc, data));
- }
-
- if (isClass) setCacheStrategy(cfc, null, doc, meta, clazz, data);
-
- // id
- if (isClass) addId(cfc, doc, clazz, meta, propColl, columnsInfo, tableName, data);
-
- // discriminator
- if (isClass) addDiscriminator(cfc, doc, clazz, pc, meta, data);
-
- // version
- if (isClass) addVersion(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
-
- // property
- addProperty(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
-
- // relations
- addRelation(cfc, clazz, pc, propColl, columnsInfo, tableName, dc, data);
-
- // collection
- addCollection(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
-
- // join
- addJoin(cfc, clazz, pc, joins, columnsInfo, tableName, dc, data);
-
- }
-
- private static Property[] getProperties(PageContext pc, Component cfc, DatasourceConnection dc, Struct meta, boolean isClass, boolean recursivePersistentMappedSuperclass,
- SessionFactoryData data) throws PageException, PageException {
- Property[] _props;
- if (recursivePersistentMappedSuperclass) {
- _props = CommonUtil.getProperties(cfc, true, true, true, true);
- }
- else {
- _props = cfc.getProperties(true, false, false, false);
- }
-
- if (isClass && _props.length == 0 && data.getORMConfiguration().useDBForMapping()) {
- if (meta == null) meta = cfc.getMetaData(pc);
- _props = HibernateUtil.createPropertiesFromTable(dc, getTableName(pc, meta, cfc, data));
- }
- return _props;
- }
-
- private static void addId(Component cfc, Document doc, Element clazz, Struct meta, PropertyCollection propColl, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Property[] _ids = getIds(cfc, propColl, data);
-
- // Property[] _ids = ids.toArray(new Property[ids.size()]);
-
- if (_ids.length == 1) createXMLMappingId(cfc, clazz, _ids[0], columnsInfo, tableName, data);
- else if (_ids.length > 1) createXMLMappingCompositeId(cfc, clazz, _ids, columnsInfo, tableName, data);
- else throw ExceptionUtil.createException(data, cfc, "missing id property for entity [" + HibernateCaster.getEntityName(cfc) + "]", null);
- }
-
- private static PropertyCollection splitJoins(Component cfc, Map joins, Property[] props, SessionFactoryData data) {
- Struct sct = CommonUtil.createStruct();
- ArrayList others = new ArrayList();
- java.util.List list;
- String table;
- Property prop;
- String fieldType;
- boolean isJoin;
- for (int i = 0; i < props.length; i++) {
- prop = props[i];
- table = getTable(cfc, prop, data);
- // joins
- if (!Util.isEmpty(table, true)) {
- isJoin = true;
- // wrong field type
- try {
- fieldType = toString(cfc, prop, sct, FIELDTYPE, false, data);
-
- if ("collection".equalsIgnoreCase(fieldType)) isJoin = false;
- else if ("primary".equals(fieldType)) isJoin = false;
- else if ("version".equals(fieldType)) isJoin = false;
- else if ("timestamp".equals(fieldType)) isJoin = false;
- }
- catch (PageException e) {
- }
-
- // missing column
- String columns = null;
- try {
- if (CommonUtil.isRelated(props[i])) {
- columns = toString(cfc, props[i], prop.getDynamicAttributes(), "fkcolumn", data);
- }
- else {
- columns = toString(cfc, props[i], prop.getDynamicAttributes(), "joincolumn", data);
- }
- }
- catch (PageException e) {
- }
- if (Util.isEmpty(columns)) isJoin = false;
-
- if (isJoin) {
- table = table.trim();
- list = (java.util.List) sct.get(table, null);
- if (list == null) {
- list = new ArrayList();
- sct.setEL(CommonUtil.createKey(table), list);
- }
- list.add(prop);
- continue;
- }
- }
- others.add(prop);
- }
-
- // fill to joins
- Iterator> it = sct.entryIterator();
- Entry e;
- while (it.hasNext()) {
- e = it.next();
- list = (java.util.List) e.getValue();
- joins.put(e.getKey().getString(), new PropertyCollection(e.getKey().getString(), list));
- }
-
- return new PropertyCollection(null, others);
- }
-
- private static Property[] getIds(Component cfc, PropertyCollection pc, SessionFactoryData data) {
- return getIds(cfc, pc.getProperties(), pc.getTableName(), false, data);
- }
-
- private static Property[] getIds(Component cfc, Property[] props, String tableName, boolean ignoreTableName, SessionFactoryData data) {
- ArrayList ids = new ArrayList();
- for (int y = 0; y < props.length; y++) {
- if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data)) continue;
-
- String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
- if ("id".equalsIgnoreCase(fieldType) || CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "id", ',') != -1) ids.add(props[y]);
- }
-
- // no id field defined
- if (ids.size() == 0) {
- String fieldType;
- for (int y = 0; y < props.length; y++) {
- if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data)) continue;
- fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
- if (Util.isEmpty(fieldType, true) && props[y].getName().equalsIgnoreCase("id")) {
- ids.add(props[y]);
- props[y].getDynamicAttributes().setEL(FIELDTYPE, "id");
- }
- }
- }
-
- // still no id field defined
- if (ids.size() == 0 && props.length > 0) {
- String owner = props[0].getOwnerName();
- if (!Util.isEmpty(owner)) owner = CommonUtil.last(owner, ".").trim();
-
- String fieldType;
- if (!Util.isEmpty(owner)) {
- String id = owner + "id";
- for (int y = 0; y < props.length; y++) {
- if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data)) continue;
- fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
- if (Util.isEmpty(fieldType, true) && props[y].getName().equalsIgnoreCase(id)) {
- ids.add(props[y]);
- props[y].getDynamicAttributes().setEL(FIELDTYPE, "id");
- }
- }
- }
- }
- return ids.toArray(new Property[ids.size()]);
- }
-
- private static void addVersion(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Property[] props = propColl.getProperties();
- for (int y = 0; y < props.length; y++) {
- String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
- if ("version".equalsIgnoreCase(fieldType)) createXMLMappingVersion(clazz, pc, cfc, props[y], data);
- else if ("timestamp".equalsIgnoreCase(fieldType)) createXMLMappingTimestamp(clazz, pc, cfc, props[y], data);
- }
- }
-
- private static void addCollection(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Property[] props = propColl.getProperties();
- for (int y = 0; y < props.length; y++) {
- String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
- if ("collection".equalsIgnoreCase(fieldType)) createXMLMappingCollection(clazz, pc, cfc, props[y], data);
- }
- }
-
- private static void addJoin(Component cfc, Element clazz, PageContext pc, Map joins, Struct columnsInfo, String tableName, DatasourceConnection dc,
- SessionFactoryData data) throws PageException {
-
- Iterator> it = joins.entrySet().iterator();
- Entry entry;
- while (it.hasNext()) {
- entry = it.next();
- addJoin(cfc, pc, columnsInfo, clazz, entry.getValue(), dc, data);
- }
-
- }
-
- private static void addJoin(Component cfc, PageContext pc, Struct columnsInfo, Element clazz, PropertyCollection coll, DatasourceConnection dc, SessionFactoryData data)
- throws PageException {
- String table = coll.getTableName();
- Property[] properties = coll.getProperties();
- if (properties.length == 0) return;
-
- Document doc = CommonUtil.getDocument(clazz);
-
- Element join = doc.createElement("join");
- clazz.appendChild(join);
-
- join.setAttribute("table", escape(HibernateUtil.convertTableName(data, coll.getTableName())));
- // addTableInfo(joinNode, table, schema, catalog);
-
- Property first = properties[0];
- String schema = null, catalog = null, mappedBy = null, columns = null;
- if (CommonUtil.isRelated(first)) {
- catalog = toString(cfc, first, first.getDynamicAttributes(), "linkcatalog", data);
- schema = toString(cfc, first, first.getDynamicAttributes(), "linkschema", data);
- columns = toString(cfc, first, first.getDynamicAttributes(), "fkcolumn", data);
-
- }
- else {
- catalog = toString(cfc, first, first.getDynamicAttributes(), "catalog", data);
- schema = toString(cfc, first, first.getDynamicAttributes(), "schema", data);
- mappedBy = toString(cfc, first, first.getDynamicAttributes(), "mappedby", data);
- columns = toString(cfc, first, first.getDynamicAttributes(), "joincolumn", data);
- }
-
- if (!Util.isEmpty(catalog)) join.setAttribute("catalog", catalog);
- if (!Util.isEmpty(schema)) join.setAttribute("schema", schema);
-
- Element key = doc.createElement("key");
- join.appendChild(key);
- if (!Util.isEmpty(mappedBy)) key.setAttribute("property-ref", mappedBy);
- setColumn(doc, key, columns, data);
-
- addProperty(cfc, join, pc, coll, columnsInfo, table, data);
- int count = addRelation(cfc, join, pc, coll, columnsInfo, table, dc, data);
-
- if (count > 0) join.setAttribute("inverse", "true");
-
- }
-
- private static int addRelation(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl, Struct columnsInfo, String tableName, DatasourceConnection dc,
- SessionFactoryData data) throws PageException {
- Property[] props = propColl.getProperties();
- int count = 0;
- for (int y = 0; y < props.length; y++) {
- String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
- if ("one-to-one".equalsIgnoreCase(fieldType)) {
- createXMLMappingOneToOne(clazz, pc, cfc, props[y], data);
- count++;
- }
- else if ("many-to-one".equalsIgnoreCase(fieldType)) {
- createXMLMappingManyToOne(clazz, pc, cfc, props[y], propColl, data);
- count++;
- }
- else if ("one-to-many".equalsIgnoreCase(fieldType)) {
- createXMLMappingOneToMany(dc, cfc, propColl, clazz, pc, props[y], data);
- count++;
- }
- else if ("many-to-many".equalsIgnoreCase(fieldType)) {
- createXMLMappingManyToMany(dc, cfc, propColl, clazz, pc, props[y], data);
- count++;
- }
- }
- return count;
- }
-
- private static void addProperty(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Property[] props = propColl.getProperties();
- for (int y = 0; y < props.length; y++) {
- String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
- if ("column".equalsIgnoreCase(fieldType)) createXMLMappingProperty(clazz, pc, cfc, props[y], columnsInfo, tableName, data);
- }
- }
-
- private static void addDiscriminator(Component cfc, Document doc, Element clazz, PageContext pc, Struct meta, SessionFactoryData data) throws DOMException, PageException {
-
- String str = toString(cfc, null, meta, "discriminatorColumn", data);
- if (!Util.isEmpty(str, true)) {
- Element disc = doc.createElement("discriminator");
- clazz.appendChild(disc);
- disc.setAttribute("column", formatColumn(str, data));
- }
-
- }
-
- private static void addGeneralClassAttributes(PageContext pc, Component cfc, Struct meta, Element clazz, SessionFactoryData data) throws PageException {
-
- // name
- clazz.setAttribute("node", HibernateCaster.toComponentName(cfc));
-
- // entity-name
- String str = toString(cfc, null, meta, "entityname", data);
- if (Util.isEmpty(str, true)) str = HibernateCaster.getEntityName(cfc);
- clazz.setAttribute("entity-name", str);
-
- // batch-size
- Integer i = toInteger(cfc, meta, "batchsize", data);
- if (i != null && i.intValue() > 0) clazz.setAttribute("batch-size", CommonUtil.toString(i));
-
- // dynamic-insert
- Boolean b = toBoolean(cfc, meta, "dynamicinsert", data);
- if (b != null && b.booleanValue()) clazz.setAttribute("dynamic-insert", "true");
-
- // dynamic-update
- b = toBoolean(cfc, meta, "dynamicupdate", data);
- if (b != null && b.booleanValue()) clazz.setAttribute("dynamic-update", "true");
-
- // lazy (dtd defintion:)
- b = toBoolean(cfc, meta, "lazy", data);
- if (b == null) b = Boolean.TRUE;
- clazz.setAttribute("lazy", CommonUtil.toString(b.booleanValue()));
-
- // select-before-update
- b = toBoolean(cfc, meta, "selectbeforeupdate", data);
- if (b != null && b.booleanValue()) clazz.setAttribute("select-before-update", "true");
-
- // optimistic-lock
- str = toString(cfc, null, meta, "optimisticLock", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("all".equals(str) || "dirty".equals(str) || "none".equals(str) || "version".equals(str)) clazz.setAttribute("optimistic-lock", str);
- else throw ExceptionUtil.createException(data, cfc,
- "invalid value [" + str + "] for attribute [optimisticlock] of tag [component], valid values are [all,dirty,none,version]", null);
- }
-
- // read-only
- b = toBoolean(cfc, meta, "readOnly", data);
- if (b != null && b.booleanValue()) clazz.setAttribute("mutable", "false");
-
- // rowid
- str = toString(cfc, null, meta, "rowid", data);
- if (!Util.isEmpty(str, true)) clazz.setAttribute("rowid", str);
-
- // where
- str = toString(cfc, null, meta, "where", data);
- if (!Util.isEmpty(str, true)) clazz.setAttribute("where", str);
-
- }
-
- private static void addGeneralTableAttributes(PageContext pc, DatasourceConnection dc, Component cfc, Struct meta, Element clazz, SessionFactoryData data)
- throws PageException {
- // table
- clazz.setAttribute("table", escape(getTableName(pc, meta, cfc, data)));
-
- // catalog
- String str = toString(cfc, null, meta, "catalog", data);
- if (str == null) // empty string is allowed as input
- str = ORMConfigurationUtil.getCatalog(data.getORMConfiguration(), dc.getDatasource().getName());
-
- if (!Util.isEmpty(str, true)) clazz.setAttribute("catalog", str);
-
- // schema
- str = toString(cfc, null, meta, "schema", data);
- if (str == null)// empty string is allowed as input
- str = ORMConfigurationUtil.getSchema(data.getORMConfiguration(), dc.getDatasource().getName());
- if (!Util.isEmpty(str, true)) clazz.setAttribute("schema", str);
-
- }
-
- private static String escape(String str) {
- if (HibernateUtil.isKeyword(str)) return "`" + str + "`";
- return str;
- }
-
- private static String getTableName(PageContext pc, Struct meta, Component cfc, SessionFactoryData data) throws PageException {
- String tableName = toString(cfc, null, meta, "table", data);
- if (Util.isEmpty(tableName, true)) tableName = HibernateCaster.getEntityName(cfc);
- return HibernateUtil.convertTableName(data, tableName);
- }
-
- private static String getTable(Component cfc, Property prop, SessionFactoryData data) {
- try {
- return HibernateUtil.convertTableName(data, toString(cfc, prop, prop.getDynamicAttributes(), "table", data));
- }
- catch (PageException e) {
- return null;
- }
- }
-
- private static boolean hasTable(Component cfc, Property prop, String tableName, SessionFactoryData data) {
- String t = getTable(cfc, prop, data);
- boolean left = Util.isEmpty(t, true);
- boolean right = Util.isEmpty(tableName, true);
- if (left && right) return true;
- if (left || right) return false;
- return tableName.trim().equalsIgnoreCase(t.trim());
- }
-
- private static void createXMLMappingCompositeId(Component cfc, Element clazz, Property[] props, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Struct meta;
-
- Document doc = CommonUtil.getDocument(clazz);
- Element cid = doc.createElement("composite-id");
- clazz.appendChild(cid);
-
- // cid.setAttribute("mapped","true");
-
- Property prop;
- String fieldType;
- // ids
- for (int y = 0; y < props.length; y++) {
- prop = props[y];
-
- // do not add "key-property" for many-to-one
- meta = prop.getDynamicAttributes();
- fieldType = toString(cfc, prop, meta, "fieldType", data);
- if (CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "many-to-one", ',') != -1) continue;
-
- Element key = doc.createElement("key-property");
- cid.appendChild(key);
-
- // name
- key.setAttribute("name", prop.getName());
-
- // column
- Element column = doc.createElement("column");
- key.appendChild(column);
-
- String str = toString(cfc, prop, meta, "column", data);
- if (Util.isEmpty(str, true)) str = prop.getName();
- column.setAttribute("name", formatColumn(str, data));
- ColumnInfo info = getColumnInfo(columnsInfo, tableName, str, null);
-
- str = toString(cfc, prop, meta, "sqltype", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("sql-type", str);
- str = toString(cfc, prop, meta, "length", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("length", str);
-
- String generator = toString(cfc, prop, meta, "generator", data);
- String type = getType(info, cfc, prop, meta, getDefaultTypeForGenerator(generator, "string"), data);
- if (!Util.isEmpty(type)) key.setAttribute("type", type);
- }
-
- // many-to-one
- for (int y = 0; y < props.length; y++) {
- prop = props[y];
- meta = prop.getDynamicAttributes();
- fieldType = toString(cfc, prop, meta, "fieldType", data);
- if (CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "many-to-one", ',') == -1) continue;
-
- Element key = doc.createElement("key-many-to-one");
- cid.appendChild(key);
-
- // name
- key.setAttribute("name", prop.getName());
-
- // entity-name
- setForeignEntityName(cfc, prop, meta, key, false, data);
-
- // fkcolum
- String str = toString(cfc, prop, meta, "fkcolumn", data);
- setColumn(doc, key, str, data);
-
- // lazy
- setLazy(cfc, prop, meta, key, data);
- }
- }
-
- private static void createXMLMappingId(Component cfc, Element clazz, Property prop, Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
- String str;
-
- Document doc = CommonUtil.getDocument(clazz);
- Element id = doc.createElement("id");
- clazz.appendChild(id);
-
- // access
- str = toString(cfc, prop, meta, "access", data);
- if (!Util.isEmpty(str, true)) id.setAttribute("access", str);
-
- // name
- id.setAttribute("name", prop.getName());
-
- // column
- Element column = doc.createElement("column");
- id.appendChild(column);
-
- str = toString(cfc, prop, meta, "column", data);
- if (Util.isEmpty(str, true)) str = prop.getName();
- column.setAttribute("name", formatColumn(str, data));
- ColumnInfo info = getColumnInfo(columnsInfo, tableName, str, null);
- StringBuilder foreignCFC = new StringBuilder();
- String generator = createXMLMappingGenerator(id, cfc, prop, foreignCFC, data);
-
- str = toString(cfc, prop, meta, "length", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("length", str);
-
- // type
- String type = getType(info, cfc, prop, meta, getDefaultTypeForGenerator(generator, foreignCFC, data), data);
- // print.o(prop.getName()+":"+type+"::"+getDefaultTypeForGenerator(generator,foreignCFC));
- if (!Util.isEmpty(type)) id.setAttribute("type", type);
-
- // unsaved-value
- str = toString(cfc, prop, meta, "unsavedValue", data);
- if (str != null) id.setAttribute("unsaved-value", str);
-
- }
-
- private static String getDefaultTypeForGenerator(String generator, StringBuilder foreignCFC, SessionFactoryData data) {
- String value = getDefaultTypeForGenerator(generator, null);
- if (value != null) return value;
-
- if ("foreign".equalsIgnoreCase(generator)) {
- if (!Util.isEmpty(foreignCFC.toString())) {
- try {
- Component cfc = data.getEntityByCFCName(foreignCFC.toString(), false);
- if (cfc != null) {
- Property[] ids = getIds(cfc, cfc.getProperties(true, false, false, false), null, true, data);
- if (ids != null && ids.length > 0) {
- Property id = ids[0];
- id.getDynamicAttributes();
- Struct meta = id.getDynamicAttributes();
- if (meta != null) {
- String type = CommonUtil.toString(meta.get(TYPE, null));
-
- if (!Util.isEmpty(type) && (!type.equalsIgnoreCase("any") && !type.equalsIgnoreCase("object"))) {
- return type;
- }
-
- String g = CommonUtil.toString(meta.get(GENERATOR, null));
- if (!Util.isEmpty(g)) {
- return getDefaultTypeForGenerator(g, foreignCFC, data);
- }
-
- }
- }
- }
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- }
- }
- return "string";
- }
-
- return "string";
- }
-
- public static String getDefaultTypeForGenerator(String generator, String defaultValue) {
- if ("increment".equalsIgnoreCase(generator)) return "integer";
- if ("identity".equalsIgnoreCase(generator)) return "integer";
- if ("native".equalsIgnoreCase(generator)) return "integer";
- if ("seqhilo".equalsIgnoreCase(generator)) return "string";
- if ("uuid".equalsIgnoreCase(generator)) return "string";
- if ("guid".equalsIgnoreCase(generator)) return "string";
- if ("select".equalsIgnoreCase(generator)) return "string";
- return defaultValue;
- }
-
- private static String getType(ColumnInfo info, Component cfc, Property prop, Struct meta, String defaultValue, SessionFactoryData data) throws PageException {
- // ormType
- String type = toString(cfc, prop, meta, "ormType", data);
- // type=HibernateCaster.toHibernateType(info,type,null);
-
- // dataType
- if (Util.isEmpty(type, true)) {
- type = toString(cfc, prop, meta, "dataType", data);
- // type=HibernateCaster.toHibernateType(info,type,null);
- }
-
- // type
- if (Util.isEmpty(type, true)) {
- type = prop.getType();
- // type=HibernateCaster.toHibernateType(info,type,null);
- }
-
- // type from db info
- if (Util.isEmpty(type, true)) {
- if (info != null) {
- type = info.getTypeName();
- // type=HibernateCaster.toHibernateType(info,type,defaultValue);
- }
- else return defaultValue;
- }
- return HibernateCaster.toHibernateType(info, type, defaultValue);
- }
-
- private static ColumnInfo getColumnInfo(Struct columnsInfo, String tableName, String columnName, ColumnInfo defaultValue) {
- if (columnsInfo != null) {
- ColumnInfo info = (ColumnInfo) columnsInfo.get(CommonUtil.createKey(columnName), null);
- if (info == null) return defaultValue;
- return info;
- }
- return defaultValue;
- }
-
- private static String createXMLMappingGenerator(Element id, Component cfc, Property prop, StringBuilder foreignCFC, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
-
- // generator
- String className = toString(cfc, prop, meta, "generator", data);
- if (Util.isEmpty(className, true)) return null;
-
- Document doc = CommonUtil.getDocument(id);
- Element generator = doc.createElement("generator");
- id.appendChild(generator);
-
- generator.setAttribute("class", className);
-
- // print.e("generator:"+className);
-
- // params
- Object obj = meta.get(PARAMS, null);
- // if(obj!=null){
- Struct sct = null;
- if (obj == null) obj = CommonUtil.createStruct();
- else if (obj instanceof String) obj = CommonUtil.convertToSimpleMap((String) obj);
-
- if (CommonUtil.isStruct(obj)) sct = CommonUtil.toStruct(obj);
- else throw ExceptionUtil.createException(data, cfc, "invalid value for attribute [params] of tag [property]", null);
- className = className.trim().toLowerCase();
-
- // special classes
- if ("foreign".equals(className)) {
- if (!sct.containsKey(PROPERTY)) sct.setEL(PROPERTY, toString(cfc, prop, meta, PROPERTY, true, data));
-
- if (sct.containsKey(PROPERTY)) {
- String p = CommonUtil.toString(sct.get(PROPERTY), null);
- if (!Util.isEmpty(p)) foreignCFC.append(p);
- }
-
- }
- else if ("select".equals(className)) {
- // print.e("select:"+toString(meta, "selectKey",true));
- if (!sct.containsKey(KEY)) sct.setEL(KEY, toString(cfc, prop, meta, "selectKey", true, data));
- }
- else if ("sequence".equals(className)) {
- if (!sct.containsKey(SEQUENCE)) sct.setEL(SEQUENCE, toString(cfc, prop, meta, "sequence", true, data));
- }
-
- // Key[] keys = sct.keys();
- Iterator> it = sct.entryIterator();
- Entry e;
- Element param;
- while (it.hasNext()) {
- e = it.next();
- param = doc.createElement("param");
- generator.appendChild(param);
-
- param.setAttribute("name", e.getKey().getLowerString());
- param.appendChild(doc.createTextNode(CommonUtil.toString(e.getValue())));
-
- }
- // }
- return className;
- }
-
- private static void createXMLMappingProperty(Element clazz, PageContext pc, Component cfc, Property prop, Struct columnsInfo, String tableName, SessionFactoryData data)
- throws PageException {
- Struct meta = prop.getDynamicAttributes();
-
- // get table name
- String columnName = toString(cfc, prop, meta, "column", data);
- if (Util.isEmpty(columnName, true)) columnName = prop.getName();
-
- ColumnInfo info = getColumnInfo(columnsInfo, tableName, columnName, null);
-
- Document doc = CommonUtil.getDocument(clazz);
- final Element property = doc.createElement("property");
- clazz.appendChild(property);
-
- // name
- property.setAttribute("name", prop.getName());
-
- // type
- String str = getType(info, cfc, prop, meta, "string", data);
- property.setAttribute("type", str);
-
- // formula or column
- str = toString(cfc, prop, meta, "formula", data);
- Boolean b;
- if (!Util.isEmpty(str, true)) {
- property.setAttribute("formula", "(" + str + ")");
- }
- else {
- // property.setAttribute("column",columnName);
-
- Element column = doc.createElement("column");
- property.appendChild(column);
- column.setAttribute("name", escape(HibernateUtil.convertColumnName(data, columnName)));
-
- // check
- str = toString(cfc, prop, meta, "check", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("check", str);
-
- // default
- str = toString(cfc, prop, meta, "dbDefault", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("default", str);
-
- // index
- str = toString(cfc, prop, meta, "index", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("index", str);
-
- // length
- Integer i = toInteger(cfc, meta, "length", data);
- if (i != null && i > 0) column.setAttribute("length", CommonUtil.toString(i.intValue()));
-
- // not-null
- b = toBoolean(cfc, meta, "notnull", data);
- if (b != null && b.booleanValue()) column.setAttribute("not-null", "true");
-
- // precision
- i = toInteger(cfc, meta, "precision", data);
- if (i != null && i > -1) column.setAttribute("precision", CommonUtil.toString(i.intValue()));
-
- // scale
- i = toInteger(cfc, meta, "scale", data);
- if (i != null && i > -1) column.setAttribute("scale", CommonUtil.toString(i.intValue()));
-
- // sql-type
- str = toString(cfc, prop, meta, "sqltype", data);
- if (!Util.isEmpty(str, true)) column.setAttribute("sql-type", str);
-
- // unique
- b = toBoolean(cfc, meta, "unique", data);
- if (b != null && b.booleanValue()) column.setAttribute("unique", "true");
-
- // unique-key
- str = toString(cfc, prop, meta, "uniqueKey", data);
- if (Util.isEmpty(str)) str = CommonUtil.toString(meta.get(UNIQUE_KEY_NAME, null), null);
- if (!Util.isEmpty(str, true)) column.setAttribute("unique-key", str);
-
- }
-
- // generated
- str = toString(cfc, prop, meta, "generated", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
-
- if ("always".equals(str) || "insert".equals(str) || "never".equals(str)) property.setAttribute("generated", str);
- else throw invalidValue(cfc, prop, "generated", str, "always,insert,never", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [generated] of column
- // ["+columnName+"], valid values are [always,insert,never]");
- }
-
- // update
- b = toBoolean(cfc, meta, "update", data);
- if (b != null && !b.booleanValue()) property.setAttribute("update", "false");
-
- // insert
- b = toBoolean(cfc, meta, "insert", data);
- if (b != null && !b.booleanValue()) property.setAttribute("insert", "false");
-
- // lazy (dtd defintion:)
- b = toBoolean(cfc, meta, "lazy", data);
- if (b != null && b.booleanValue()) property.setAttribute("lazy", "true");
-
- // optimistic-lock
- b = toBoolean(cfc, meta, "optimisticlock", data);
- if (b != null && !b.booleanValue()) property.setAttribute("optimistic-lock", "false");
-
- }
-
- /*
- * MUST dies kommt aber nicht hier sondern in verarbeitung in component
- */
- private static void createXMLMappingOneToOne(Element clazz, PageContext pc, Component cfc, Property prop, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
-
- Boolean b;
-
- Document doc = CommonUtil.getDocument(clazz);
- Element x2o;
-
- // column
- String fkcolumn = toString(cfc, prop, meta, "fkcolumn", data);
- String linkTable = toString(cfc, prop, meta, "linkTable", data);
-
- if (!Util.isEmpty(linkTable, true) || !Util.isEmpty(fkcolumn, true)) {
- clazz = getJoin(clazz);
-
- x2o = doc.createElement("many-to-one");
- // x2o.setAttribute("column", fkcolumn);
- x2o.setAttribute("unique", "true");
-
- if (!Util.isEmpty(linkTable, true)) {
- setColumn(doc, x2o, linkTable, data);
- }
- else {
- setColumn(doc, x2o, fkcolumn, data);
- }
-
- // update
- b = toBoolean(cfc, meta, "update", data);
- if (b != null) x2o.setAttribute("update", CommonUtil.toString(b.booleanValue()));
-
- // insert
- b = toBoolean(cfc, meta, "insert", data);
- if (b != null) x2o.setAttribute("insert", CommonUtil.toString(b.booleanValue()));
-
- // not-null
- b = toBoolean(cfc, meta, "notNull", data);
- if (b != null) x2o.setAttribute("not-null", CommonUtil.toString(b.booleanValue()));
-
- // optimistic-lock
- b = toBoolean(cfc, meta, "optimisticLock", data);
- if (b != null) x2o.setAttribute("optimistic-lock", CommonUtil.toString(b.booleanValue()));
-
- // not-found
- b = toBoolean(cfc, meta, "missingRowIgnored", data);
- if (b != null && b.booleanValue()) x2o.setAttribute("not-found", "ignore");
-
- /*
- * / index str=toString(meta,"index"); if(!Util.isEmpty(str,true)) x2o.setAttribute("index", str);
- */
-
- }
- else {
- x2o = doc.createElement("one-to-one");
- }
- clazz.appendChild(x2o);
-
- // access
- String str = toString(cfc, prop, meta, "access", data);
- if (!Util.isEmpty(str, true)) x2o.setAttribute("access", str);
-
- // constrained
- b = toBoolean(cfc, meta, "constrained", data);
- if (b != null && b.booleanValue()) x2o.setAttribute("constrained", "true");
-
- // formula
- str = toString(cfc, prop, meta, "formula", data);
- if (!Util.isEmpty(str, true)) x2o.setAttribute("formula", str);
-
- // embed-xml
- str = toString(cfc, prop, meta, "embedXml", data);
- if (!Util.isEmpty(str, true)) x2o.setAttribute("embed-xml", str);
-
- // property-ref
- str = toString(cfc, prop, meta, "mappedBy", data);
- if (!Util.isEmpty(str, true)) x2o.setAttribute("property-ref", str);
-
- // foreign-key
- str = toString(cfc, prop, meta, "foreignKeyName", data);
- if (Util.isEmpty(str, true)) str = toString(cfc, prop, meta, "foreignKey", data);
- if (!Util.isEmpty(str, true)) x2o.setAttribute("foreign-key", str);
-
- setForeignEntityName(cfc, prop, meta, x2o, true, data);
-
- createXMLMappingXToX(x2o, pc, cfc, prop, meta, data);
- }
-
- private static Component loadForeignCFC(PageContext pc, Component cfc, Property prop, Struct meta, SessionFactoryData data) throws PageException {
- // entity
- String str = toString(cfc, prop, meta, "entityName", data);
- Component fcfc = null;
-
- if (!Util.isEmpty(str, true)) {
- fcfc = data.getEntityByEntityName(str, false);
- if (fcfc != null) return fcfc;
- }
-
- str = toString(cfc, prop, meta, "cfc", false, data);
- if (!Util.isEmpty(str, true)) {
- return data.getEntityByCFCName(str, false);
- }
- return null;
- }
-
- private static void createXMLMappingCollection(Element clazz, PageContext pc, Component cfc, Property prop, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
- Document doc = CommonUtil.getDocument(clazz);
- Element el = null;
-
- // collection type
- String str = prop.getType();
- if (Util.isEmpty(str, true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str)) str = "array";
- else str = str.trim().toLowerCase();
-
- // bag
- if ("array".equals(str) || "bag".equals(str)) {
- el = doc.createElement("bag");
- }
- // map
- else if ("struct".equals(str) || "map".equals(str)) {
- el = doc.createElement("map");
-
- // map-key
- str = toString(cfc, prop, meta, "structKeyColumn", true, data);
- if (!Util.isEmpty(str, true)) {
- Element mapKey = doc.createElement("map-key");
- el.appendChild(mapKey);
- mapKey.setAttribute("column", str);
-
- // type
- str = toString(cfc, prop, meta, "structKeyType", data);
- if (!Util.isEmpty(str, true)) mapKey.setAttribute("type", str);
- else mapKey.setAttribute("type", "string");
- }
- }
- else throw invalidValue(cfc, prop, "collectiontype", str, "array,struct", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [collectiontype], valid values are
- // [array,struct]");
-
- setBeforeJoin(clazz, el);
-
- // name
- el.setAttribute("name", prop.getName());
-
- // table
- str = toString(cfc, prop, meta, "table", true, data);
- el.setAttribute("table", escape(HibernateUtil.convertTableName(data, str)));
-
- // catalog
- str = toString(cfc, prop, meta, "catalog", data);
- if (!Util.isEmpty(str, true)) el.setAttribute("catalog", str);
-
- // schema
- str = toString(cfc, prop, meta, "schema", data);
- if (!Util.isEmpty(str, true)) el.setAttribute("schema", str);
-
- // mutable
- Boolean b = toBoolean(cfc, meta, "readonly", data);
- if (b != null && b.booleanValue()) el.setAttribute("mutable", "false");
-
- // order-by
- str = toString(cfc, prop, meta, "orderby", data);
- if (!Util.isEmpty(str, true)) el.setAttribute("order-by", str);
-
- // element-column
- str = toString(cfc, prop, meta, "elementcolumn", data);
- if (!Util.isEmpty(str, true)) {
- Element element = doc.createElement("element");
- el.appendChild(element);
-
- // column
- element.setAttribute("column", formatColumn(str, data));
-
- // type
- str = toString(cfc, prop, meta, "elementtype", data);
- if (!Util.isEmpty(str, true)) element.setAttribute("type", str);
- }
-
- // batch-size
- Integer i = toInteger(cfc, meta, "batchsize", data);
- if (i != null && i.intValue() > 1) el.setAttribute("batch-size", CommonUtil.toString(i.intValue()));
-
- // column
- str = toString(cfc, prop, meta, "fkcolumn", data);
- if (Util.isEmpty(str, true)) str = toString(cfc, prop, meta, "column", data);
- if (!Util.isEmpty(str, true)) {
- Element key = doc.createElement("key");
- CommonUtil.setFirst(el, key);
- // el.appendChild(key);
-
- // column
- key.setAttribute("column", formatColumn(str, data));
-
- // property-ref
- str = toString(cfc, prop, meta, "mappedBy", data);
- if (!Util.isEmpty(str, true)) key.setAttribute("property-ref", str);
- }
-
- // cache
- setCacheStrategy(cfc, prop, doc, meta, el, data);
-
- // optimistic-lock
- b = toBoolean(cfc, meta, "optimisticlock", data);
- if (b != null && !b.booleanValue()) el.setAttribute("optimistic-lock", "false");
-
- }
-
- private static void setBeforeJoin(Element clazz, Element el) {
- Element join;
- if (clazz.getNodeName().equals("join")) {
- join = clazz;
- clazz = getClazz(clazz);
- }
- else {
- join = getJoin(clazz);
- }
-
- if (join == clazz) clazz.appendChild(el);
- else clazz.insertBefore(el, join);
-
- }
-
- private static Element getClazz(Element join) {
- if (join.getNodeName().equals("join")) {
- return (Element) join.getParentNode();
- }
- return join;
- }
-
- private static Element getJoin(Element clazz) {
- if (clazz.getNodeName().equals("subclass")) {
- NodeList joins = clazz.getElementsByTagName("join");
- if (joins != null && joins.getLength() > 0) return (Element) joins.item(0);
- }
- return clazz;
- }
-
- private static void createXMLMappingManyToMany(DatasourceConnection dc, Component cfc, PropertyCollection propColl, Element clazz, PageContext pc, Property prop,
- SessionFactoryData data) throws PageException {
- Element el = createXMLMappingXToMany(propColl, clazz, pc, cfc, prop, data);
- Struct meta = prop.getDynamicAttributes();
- Document doc = CommonUtil.getDocument(clazz);
- Element m2m = doc.createElement("many-to-many");
- el.appendChild(m2m);
-
- // link
- setLink(dc, cfc, prop, el, meta, true, data);
-
- setForeignEntityName(cfc, prop, meta, m2m, true, data);
-
- // order-by
- String str = toString(cfc, prop, meta, "orderby", data);
- if (!Util.isEmpty(str, true)) m2m.setAttribute("order-by", str);
-
- // column
- str = toString(cfc, prop, meta, "inversejoincolumn", data);
-
- // build fkcolumn name
- if (Util.isEmpty(str, true)) {
- Component other = loadForeignCFC(pc, cfc, prop, meta, data);
- if (other != null) {
- boolean isClass = Util.isEmpty(other.getExtends());
- // MZ: Recursive search for persistent mappedSuperclass properties
- Property[] _props = getProperties(pc, other, dc, meta, isClass, true, data);
- PropertyCollection _propColl = splitJoins(cfc, new HashMap(), _props, data);
- _props = _propColl.getProperties();
-
- Struct m;
- Property _prop = null;
- for (int i = 0; i < _props.length; i++) {
- m = _props[i].getDynamicAttributes();
- // fieldtype
- String fieldtype = CommonUtil.toString(m.get(FIELDTYPE, null), null);
- if ("many-to-many".equalsIgnoreCase(fieldtype)) {
- // linktable
- String currLinkTable = CommonUtil.toString(meta.get(LINK_TABLE, null), null);
- String othLinkTable = CommonUtil.toString(m.get(LINK_TABLE, null), null);
- if (currLinkTable.equals(othLinkTable)) {
- // cfc name
- String cfcName = CommonUtil.toString(m.get(CFC, null), null);
- if (cfc.equalTo(cfcName)) {
- _prop = _props[i];
- }
- }
- }
- }
- str = createM2MFKColumnName(other, _prop, _propColl, data);
- }
- }
- setColumn(doc, m2m, str, data);
-
- // not-found
- Boolean b = toBoolean(cfc, meta, "missingrowignored", data);
- if (b != null && b.booleanValue()) m2m.setAttribute("not-found", "ignore");
-
- // property-ref
- str = toString(cfc, prop, meta, "mappedby", data);
- if (!Util.isEmpty(str, true)) m2m.setAttribute("property-ref", str);
-
- // foreign-key
- str = toString(cfc, prop, meta, "foreignKeyName", data);
- if (Util.isEmpty(str, true)) str = toString(cfc, prop, meta, "foreignKey", data);
- if (!Util.isEmpty(str, true)) m2m.setAttribute("foreign-key", str);
- }
-
- private static boolean setLink(DatasourceConnection dc, Component cfc, Property prop, Element el, Struct meta, boolean linkTableRequired, SessionFactoryData data)
- throws PageException {
- String str = toString(cfc, prop, meta, "linktable", linkTableRequired, data);
-
- if (!Util.isEmpty(str, true)) {
-
- el.setAttribute("table", escape(HibernateUtil.convertTableName(data, str)));
-
- // schema
- str = toString(cfc, prop, meta, "linkschema", data);
- if (Util.isEmpty(str, true)) str = ORMConfigurationUtil.getSchema(data.getORMConfiguration(), dc.getDatasource().getName());
- if (!Util.isEmpty(str, true)) el.setAttribute("schema", str);
-
- // catalog
- str = toString(cfc, prop, meta, "linkcatalog", data);
- if (Util.isEmpty(str, true)) str = ORMConfigurationUtil.getCatalog(data.getORMConfiguration(), dc.getDatasource().getName());
- if (!Util.isEmpty(str, true)) el.setAttribute("catalog", str);
- return true;
- }
- return false;
- }
-
- private static void createXMLMappingOneToMany(DatasourceConnection dc, Component cfc, PropertyCollection propColl, Element clazz, PageContext pc, Property prop,
- SessionFactoryData data) throws PageException {
- Element el = createXMLMappingXToMany(propColl, clazz, pc, cfc, prop, data);
- Struct meta = prop.getDynamicAttributes();
- Document doc = CommonUtil.getDocument(clazz);
- Element x2m;
-
- // order-by
- String str = toString(cfc, prop, meta, "orderby", data);
- if (!Util.isEmpty(str, true)) el.setAttribute("order-by", str);
-
- // link
- if (setLink(dc, cfc, prop, el, meta, false, data)) {
- x2m = doc.createElement("many-to-many");
- x2m.setAttribute("unique", "true");
-
- str = toString(cfc, prop, meta, "inversejoincolumn", data);
- setColumn(doc, x2m, str, data);
- }
- else {
- x2m = doc.createElement("one-to-many");
- }
- el.appendChild(x2m);
-
- // entity-name
-
- setForeignEntityName(cfc, prop, meta, x2m, true, data);
-
- }
-
- private static Element createXMLMappingXToMany(PropertyCollection propColl, Element clazz, PageContext pc, Component cfc, Property prop, SessionFactoryData data)
- throws PageException {
- final Struct meta = prop.getDynamicAttributes();
- Document doc = CommonUtil.getDocument(clazz);
- Element el = null;
-
- // collection type
- String str = prop.getType();
- if (Util.isEmpty(str, true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str)) str = "array";
- else str = str.trim().toLowerCase();
-
- Element mapKey = null;
- // bag
- if ("array".equals(str) || "bag".equals(str)) {
- el = doc.createElement("bag");
-
- }
- // map
- else if ("struct".equals(str) || "map".equals(str)) {
- el = doc.createElement("map");
-
- // map-key
- mapKey = doc.createElement("map-key");
- // el.appendChild(mapKey);
-
- // column
- str = toString(cfc, prop, meta, "structKeyColumn", true, data);
- mapKey.setAttribute("column", formatColumn(str, data));
-
- // type
- str = toString(cfc, prop, meta, "structKeyType", data);
- if (!Util.isEmpty(str, true)) mapKey.setAttribute("type", str);
- else mapKey.setAttribute("type", "string");// MUST get type dynamicly
- }
- else throw invalidValue(cfc, prop, "collectiontype", str, "array,struct", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [collectiontype], valid values are
- // [array,struct]");
-
- setBeforeJoin(clazz, el);
-
- // batch-size
- Integer i = toInteger(cfc, meta, "batchsize", data);
- if (i != null) {
- if (i.intValue() > 1) el.setAttribute("batch-size", CommonUtil.toString(i.intValue()));
- }
-
- // cacheUse
- setCacheStrategy(cfc, prop, doc, meta, el, data);
-
- // column
- str = createFKColumnName(cfc, prop, propColl, data);
-
- if (!Util.isEmpty(str, true)) {
- Element key = doc.createElement("key");
- el.appendChild(key);
-
- // column
- setColumn(doc, key, str, data);
-
- // property-ref
- str = toString(cfc, prop, meta, "mappedBy", data);
- if (!Util.isEmpty(str, true)) key.setAttribute("property-ref", str);
- }
-
- // inverse
- Boolean b = toBoolean(cfc, meta, "inverse", data);
- if (b != null && b.booleanValue()) el.setAttribute("inverse", "true");
-
- // mutable
- b = toBoolean(cfc, meta, "readonly", data);
- if (b != null && b.booleanValue()) el.setAttribute("mutable", "false");
-
- // optimistic-lock
- b = toBoolean(cfc, meta, "optimisticlock", data);
- if (b != null && !b.booleanValue()) el.setAttribute("optimistic-lock", "false");
-
- // where
- str = toString(cfc, prop, meta, "where", data);
- if (!Util.isEmpty(str, true)) el.setAttribute("where", str);
-
- // add map key
- if (mapKey != null) el.appendChild(mapKey);
-
- createXMLMappingXToX(el, pc, cfc, prop, meta, data);
-
- return el;
- }
-
- private static String createFKColumnName(Component cfc, Property prop, PropertyCollection propColl, SessionFactoryData data) throws PageException {
-
- // fk column from local defintion
- String str = prop == null ? null : toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", data);
- if (!Util.isEmpty(str)) return str;
-
- // no local defintion, get from Foreign enity
- Struct meta = prop.getDynamicAttributes();
- String type = toString(cfc, prop, meta, "fieldtype", false, data);
- String otherType;
- if ("many-to-one".equalsIgnoreCase(type)) otherType = "one-to-many";
- else if ("one-to-many".equalsIgnoreCase(type)) otherType = "many-to-one";
- else return createM2MFKColumnName(cfc, prop, propColl, data);
-
- String feName = toString(cfc, prop, meta, "cfc", true, data);
- Component feCFC = data.getEntityByCFCName(feName, false);
- Property[] feProps = feCFC.getProperties(true, false, false, false);
-
- Property p;
- Component _cfc;
- for (int i = 0; i < feProps.length; i++) {
- p = feProps[i];
-
- // compare fieldType
- str = toString(feCFC, p, p.getDynamicAttributes(), "fieldtype", false, data);
- if (!otherType.equalsIgnoreCase(str)) continue;
-
- // compare cfc
- str = toString(feCFC, p, p.getDynamicAttributes(), "cfc", false, data);
- if (Util.isEmpty(str)) continue;
- _cfc = data.getEntityByCFCName(str, false);
- if (_cfc == null || !_cfc.equals(cfc)) continue;
-
- // get fkcolumn
- str = toString(_cfc, p, p.getDynamicAttributes(), "fkcolumn", data);
- if (!Util.isEmpty(str)) return str;
-
- }
- throw ExceptionUtil.createException(data, null, "cannot terminate foreign key column name for component " + cfc.getName(), null);
- }
-
- private static String createM2MFKColumnName(Component cfc, Property prop, PropertyCollection propColl, SessionFactoryData data) throws PageException {
-
- String str = prop == null ? null : toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", data);
- if (Util.isEmpty(str)) {
- Property[] ids = getIds(cfc, propColl, data);
- if (ids.length == 1) {
- str = toString(cfc, ids[0], ids[0].getDynamicAttributes(), "column", data);
- if (Util.isEmpty(str, true)) str = ids[0].getName();
- }
- else if (prop != null) str = toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", true, data);
- else throw ExceptionUtil.createException(data, null, "cannot terminate foreign key column name for component " + cfc.getName(), null);
-
- str = HibernateCaster.getEntityName(cfc) + "_" + str;
- }
- return str;
- }
-
- private static void setForeignEntityName(Component cfc, Property prop, Struct meta, Element el, boolean cfcRequired, SessionFactoryData data) throws PageException {
- // entity
- String str = cfcRequired ? null : toString(cfc, prop, meta, "entityName", data);
- if (!Util.isEmpty(str, true)) {
- el.setAttribute("entity-name", str);
- }
- else {
- // cfc
- // createFKColumnName( cfc, prop, propColl);
-
- str = toString(cfc, prop, meta, "cfc", cfcRequired, data);
- if (!Util.isEmpty(str, true)) {
- Component _cfc = data.getEntityByCFCName(str, false);
- str = HibernateCaster.getEntityName(_cfc);
- el.setAttribute("entity-name", str);
- }
- }
- }
-
- private static void setCacheStrategy(Component cfc, Property prop, Document doc, Struct meta, Element el, SessionFactoryData data) throws PageException {
- String strategy = toString(cfc, prop, meta, "cacheuse", data);
-
- if (!Util.isEmpty(strategy, true)) {
- strategy = strategy.trim().toLowerCase();
- if ("read-only".equals(strategy) || "nonstrict-read-write".equals(strategy) || "read-write".equals(strategy) || "transactional".equals(strategy)) {
- Element cache = doc.createElement("cache");
- CommonUtil.setFirst(el, cache);
- el.appendChild(cache);
- cache.setAttribute("usage", strategy);
- String name = toString(cfc, prop, meta, "cacheName", data);
- if (!Util.isEmpty(name, true)) {
- cache.setAttribute("region", name);
- }
- }
- else throw ExceptionUtil.createException(data, cfc,
- "invalid value [" + strategy + "] for attribute [cacheuse], valid values are [read-only,nonstrict-read-write,read-write,transactional]", null);
- }
-
- }
-
- private static void setColumn(Document doc, Element el, String columnValue, SessionFactoryData data) throws PageException {
- if (Util.isEmpty(columnValue, true)) return;
-
- String[] arr = CommonUtil.toStringArray(columnValue, ",");
- if (arr.length == 1) {
- el.setAttribute("column", formatColumn(arr[0], data));
- }
- else {
- Element column;
- for (int i = 0; i < arr.length; i++) {
- column = doc.createElement("column");
- el.appendChild(column);
- column.setAttribute("name", formatColumn(arr[i], data));
- }
- }
- }
-
- private static void createXMLMappingManyToOne(Element clazz, PageContext pc, Component cfc, Property prop, PropertyCollection propColl, SessionFactoryData data)
- throws PageException {
- Struct meta = prop.getDynamicAttributes();
- Boolean b;
-
- Document doc = CommonUtil.getDocument(clazz);
- clazz = getJoin(clazz);
-
- Element m2o = doc.createElement("many-to-one");
- clazz.appendChild(m2o);
-
- // columns
- String linktable = toString(cfc, prop, meta, "linktable", data);
- String _columns;
- if (!Util.isEmpty(linktable, true)) _columns = toString(cfc, prop, meta, "inversejoincolumn", data);
- else _columns = createFKColumnName(cfc, prop, propColl, data);// toString(cfc,prop,meta,"fkcolumn");
- setColumn(doc, m2o, _columns, data);
-
- // cfc
- setForeignEntityName(cfc, prop, meta, m2o, true, data);
-
- // column
- // String str=toString(prop,meta,"column",true);
- // m2o.setAttribute("column", str);
-
- // insert
- b = toBoolean(cfc, meta, "insert", data);
- if (b != null && !b.booleanValue()) m2o.setAttribute("insert", "false");
-
- // update
- b = toBoolean(cfc, meta, "update", data);
- if (b != null && !b.booleanValue()) m2o.setAttribute("update", "false");
-
- // property-ref
- String str = toString(cfc, prop, meta, "mappedBy", data);
- if (!Util.isEmpty(str, true)) m2o.setAttribute("property-ref", str);
-
- // update
- b = toBoolean(cfc, meta, "unique", data);
- if (b != null && b.booleanValue()) m2o.setAttribute("unique", "true");
-
- // not-null
- b = toBoolean(cfc, meta, "notnull", data);
- if (b != null && b.booleanValue()) m2o.setAttribute("not-null", "true");
-
- // optimistic-lock
- b = toBoolean(cfc, meta, "optimisticLock", data);
- if (b != null && !b.booleanValue()) m2o.setAttribute("optimistic-lock", "false");
-
- // not-found
- b = toBoolean(cfc, meta, "missingRowIgnored", data);
- if (b != null && b.booleanValue()) m2o.setAttribute("not-found", "ignore");
-
- // index
- str = toString(cfc, prop, meta, "index", data);
- if (!Util.isEmpty(str, true)) m2o.setAttribute("index", str);
-
- // unique-key
- str = toString(cfc, prop, meta, "uniqueKeyName", data);
- if (Util.isEmpty(str, true)) str = toString(cfc, prop, meta, "uniqueKey", data);
- if (!Util.isEmpty(str, true)) m2o.setAttribute("unique-key", str);
-
- // foreign-key
- str = toString(cfc, prop, meta, "foreignKeyName", data);
- if (Util.isEmpty(str, true)) str = toString(cfc, prop, meta, "foreignKey", data);
- if (!Util.isEmpty(str, true)) m2o.setAttribute("foreign-key", str);
-
- // access
- str = toString(cfc, prop, meta, "access", data);
- if (!Util.isEmpty(str, true)) m2o.setAttribute("access", str);
-
- createXMLMappingXToX(m2o, pc, cfc, prop, meta, data);
-
- }
-
- private static String formatColumn(String name, SessionFactoryData data) throws PageException {
- name = name.trim();
- return escape(HibernateUtil.convertColumnName(data, name));
- }
-
- /*
- *
- *
- *
- *
- */
- private static void createXMLMappingXToX(Element x2x, PageContext pc, Component cfc, Property prop, Struct meta, SessionFactoryData data) throws PageException {
- x2x.setAttribute("name", prop.getName());
-
- // cascade
- String str = toString(cfc, prop, meta, "cascade", data);
- if (!Util.isEmpty(str, true)) x2x.setAttribute("cascade", str);
-
- // fetch
- str = toString(cfc, prop, meta, "fetch", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("join".equals(str) || "select".equals(str)) x2x.setAttribute("fetch", str);
- else throw invalidValue(cfc, prop, "fetch", str, "join,select", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [fetch], valid values are
- // [join,select]");
- }
-
- // lazy
- setLazy(cfc, prop, meta, x2x, data);
-
- }
-
- private static void setLazy(Component cfc, Property prop, Struct meta, Element x2x, SessionFactoryData data) throws PageException {
- String str = toString(cfc, prop, meta, "lazy", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim();
- String name = x2x.getNodeName();
- Boolean b = CommonUtil.toBoolean(str, null);
-
- //
- //
- if ("many-to-one".equals(name) || "one-to-one".equals(name)) {
- if (b != null) x2x.setAttribute("lazy", b.booleanValue() ? "proxy" : "false");
- else if ("proxy".equalsIgnoreCase(str)) x2x.setAttribute("lazy", "proxy");
- else if ("no-proxy".equalsIgnoreCase(str)) x2x.setAttribute("lazy", "no-proxy");
- else throw invalidValue(cfc, prop, "lazy", str, "true,false,proxy,no-proxy", data);
- }
-
- //
- //
- else if ("many-to-many".equals(name) || "key-many-to-one".equals(name)) {
- if (b != null) x2x.setAttribute("lazy", b.booleanValue() ? "proxy" : "false");
- else if ("proxy".equalsIgnoreCase(str)) x2x.setAttribute("lazy", "proxy");
- throw invalidValue(cfc, prop, "lazy", str, "true,false,proxy", data);
-
- }
-
- else {
- if (b != null) x2x.setAttribute("lazy", b.booleanValue() ? "true" : "false");
- else if ("extra".equalsIgnoreCase(str)) x2x.setAttribute("lazy", "extra");
- else throw invalidValue(cfc, prop, "lazy", str, "true,false,extra", data);
- }
- }
- }
-
- private static void createXMLMappingTimestamp(Element clazz, PageContext pc, Component cfc, Property prop, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
- String str;
- Boolean b;
-
- Document doc = CommonUtil.getDocument(clazz);
- Element timestamp = doc.createElement("timestamp");
- clazz.appendChild(timestamp);
-
- timestamp.setAttribute("name", prop.getName());
-
- // access
- str = toString(cfc, prop, meta, "access", data);
- if (!Util.isEmpty(str, true)) timestamp.setAttribute("access", str);
-
- // column
- str = toString(cfc, prop, meta, "column", data);
- if (Util.isEmpty(str, true)) str = prop.getName();
- timestamp.setAttribute("column", formatColumn(str, data));
-
- // generated
- b = toBoolean(cfc, meta, "generated", data);
- if (b != null) timestamp.setAttribute("generated", b.booleanValue() ? "always" : "never");
-
- // source
- str = toString(cfc, prop, meta, "source", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("db".equals(str) || "vm".equals(str)) timestamp.setAttribute("source", str);
- else throw invalidValue(cfc, prop, "source", str, "db,vm", data);
- }
-
- // unsavedValue
- str = toString(cfc, prop, meta, "unsavedValue", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("null".equals(str) || "undefined".equals(str)) timestamp.setAttribute("unsaved-value", str);
- else throw invalidValue(cfc, prop, "unsavedValue", str, "null, undefined", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [unsavedValue], valid values are
- // [null, undefined]");
- }
- }
-
- private static PageException invalidValue(Component cfc, Property prop, String attrName, String invalid, String valid, SessionFactoryData data) {
- String owner = prop.getOwnerName();
- if (Util.isEmpty(owner)) return ExceptionUtil.createException(data, cfc,
- "invalid value [" + invalid + "] for attribute [" + attrName + "] of property [" + prop.getName() + "], valid values are [" + valid + "]", null);
- return ExceptionUtil.createException(data, cfc, "invalid value [" + invalid + "] for attribute [" + attrName + "] of property [" + prop.getName() + "] of Component ["
- + CommonUtil.last(owner, ".") + "], valid values are [" + valid + "]", null);
- }
-
- private static void createXMLMappingVersion(Element clazz, PageContext pc, Component cfc, Property prop, SessionFactoryData data) throws PageException {
- Struct meta = prop.getDynamicAttributes();
-
- Document doc = CommonUtil.getDocument(clazz);
- Element version = doc.createElement("version");
- clazz.appendChild(version);
-
- version.setAttribute("name", prop.getName());
-
- // column
- String str = toString(cfc, prop, meta, "column", data);
- if (Util.isEmpty(str, true)) str = prop.getName();
- version.setAttribute("column", formatColumn(str, data));
-
- // access
- str = toString(cfc, prop, meta, "access", data);
- if (!Util.isEmpty(str, true)) version.setAttribute("access", str);
-
- // generated
- Object o = meta.get(GENERATED, null);
- if (o != null) {
- Boolean b = CommonUtil.toBoolean(o, null);
- str = null;
- if (b != null) {
- str = b.booleanValue() ? "always" : "never";
- }
- else {
- str = CommonUtil.toString(o, null);
- if ("always".equalsIgnoreCase(str)) str = "always";
- else if ("never".equalsIgnoreCase(str)) str = "never";
- else throw invalidValue(cfc, prop, "generated", o.toString(), "true,false,always,never", data);
- // throw new ORMException("invalid value ["+o+"] for attribute [generated] of property
- // ["+prop.getName()+"], valid values are [true,false,always,never]");
- }
- version.setAttribute("generated", str);
- }
-
- // insert
- Boolean b = toBoolean(cfc, meta, "insert", data);
- if (b != null && !b.booleanValue()) version.setAttribute("insert", "false");
-
- // type
- String typeName = "dataType";
- str = toString(cfc, prop, meta, typeName, data);
- if (Util.isEmpty(str, true)) {
- typeName = "ormType";
- str = toString(cfc, prop, meta, typeName, data);
- }
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("int".equals(str) || "integer".equals(str)) version.setAttribute("type", "integer");
- else if ("long".equals(str)) version.setAttribute("type", "long");
- else if ("short".equals(str)) version.setAttribute("type", "short");
- else throw invalidValue(cfc, prop, typeName, str, "int,integer,long,short", data);
- // throw new ORMException("invalid value ["+str+"] for attribute ["+typeName+"], valid values are
- // [int,integer,long,short]");
- }
- else version.setAttribute("type", "integer");
-
- // unsavedValue
- str = toString(cfc, prop, meta, "unsavedValue", data);
- if (!Util.isEmpty(str, true)) {
- str = str.trim().toLowerCase();
- if ("null".equals(str) || "negative".equals(str) || "undefined".equals(str)) version.setAttribute("unsaved-value", str);
- else throw invalidValue(cfc, prop, "unsavedValue", str, "null, negative, undefined", data);
- // throw new ORMException("invalid value ["+str+"] for attribute [unsavedValue], valid values are
- // [null, negative, undefined]");
- }
- }
-
- private static String toString(Component cfc, Property prop, Struct sct, String key, SessionFactoryData data) throws PageException {
- return toString(cfc, prop, sct, key, false, data);
- }
-
- private static String toString(Component cfc, Property prop, Struct sct, String key, boolean throwErrorWhenNotExist, SessionFactoryData data) throws PageException {
- return toString(cfc, prop, sct, CommonUtil.createKey(key), throwErrorWhenNotExist, data);
- }
-
- private static String toString(Component cfc, Property prop, Struct sct, Collection.Key key, boolean throwErrorWhenNotExist, SessionFactoryData data) throws PageException {
- Object value = sct.get(key, null);
- if (value == null) {
- if (throwErrorWhenNotExist) {
- if (prop == null) throw ExceptionUtil.createException(data, cfc, "attribute [" + key + "] is required", null);
- throw ExceptionUtil.createException(data, cfc, "attribute [" + key + "] of property [" + prop.getName() + "] of Component [" + _getCFCName(prop) + "] is required",
- null);
- }
- return null;
- }
-
- String str = CommonUtil.toString(value, null);
- if (str == null) {
- if (prop == null)
- throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value) + "] for attribute [" + key + "], value must be a string", null);
- throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value) + "] for attribute [" + key + "] of property [" + prop.getName()
- + "] of Component [" + _getCFCName(prop) + "], value must be a string", null);
- }
- return str;
- }
-
- private static String _getCFCName(Property prop) {
- String owner = prop.getOwnerName();
- return CommonUtil.last(owner, ".");
- }
-
- private static Boolean toBoolean(Component cfc, Struct sct, String key, SessionFactoryData data) throws PageException {
- Object value = sct.get(CommonUtil.createKey(key), null);
- if (value == null) return null;
-
- Boolean b = CommonUtil.toBoolean(value, null);
- if (b == null)
- throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value) + "] for attribute [" + key + "], value must be a boolean", null);
- return b;
- }
-
- private static Integer toInteger(Component cfc, Struct sct, String key, SessionFactoryData data) throws PageException {
- Object value = sct.get(CommonUtil.createKey(key), null);
- if (value == null) return null;
-
- Integer i = CommonUtil.toInteger(value, null);
- if (i == null)
- throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value) + "] for attribute [" + key + "], value must be a numeric value", null);
- return i;
- }
-
+ /**
+ * Hibernate DOCTYPE mapping ID
+ *
+ * @see Hibernate documentation schema-generation-database-objects
+ */
+ public static final String HIBERNATE_3_PUBLIC_ID = "-//Hibernate/Hibernate Mapping DTD 3.0//EN";
+
+ /**
+ * Hibernate doctype reference
+ *
+ * @see Hibernate documentation schema-generation-database-objects
+ */
+ // public static final String HIBERNATE_3_SYSTEM_ID = "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd";
+ public static final String HIBERNATE_3_SYSTEM_ID = "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd";
+
+ /**
+ * Full XML doctype for Hibernate mappings
+ *
+ * @see Hibernate documentation schema-generation-database-objects
+ */
+ public static final String HIBERNATE_3_DOCTYPE_DEFINITION = "";
+
+ private static final Collection.Key PROPERTY = CommonUtil.createKey("property");
+ private static final Collection.Key LINK_TABLE = CommonUtil.createKey("linktable");
+ private static final Collection.Key CFC = CommonUtil.createKey("cfc");
+ private static final Collection.Key GENERATOR = CommonUtil.createKey("generator");
+ private static final Collection.Key PARAMS = CommonUtil.createKey("params");
+ private static final Collection.Key SEQUENCE = CommonUtil.createKey("sequence");
+ private static final Collection.Key UNIQUE_KEY_NAME = CommonUtil.createKey("uniqueKeyName");
+ private static final Collection.Key GENERATED = CommonUtil.createKey("generated");
+ private static final Collection.Key FIELDTYPE = CommonUtil.createKey("fieldtype");
+ private static final Collection.Key KEY = CommonUtil.createKey("key");
+ private static final Collection.Key TYPE = CommonUtil.createKey("type");
+
+ /**
+ * Generate an XML node tree defining a Hibernate mapping for the given Component
+ *
+ * @param pc
+ * Lucee PageContext object
+ * @param dc
+ * Lucee DatasourceConnection object
+ * @param cfc
+ * Lucee Component to create the mapping XML for
+ * @param data
+ * SessionFactoryData instance to pull Hibernate metadata from
+ *
+ * @return XML root node
+ *
+ * @throws PageException
+ */
+ public static Element createXMLMapping(PageContext pc, DatasourceConnection dc, Component cfc,
+ SessionFactoryData data) throws PageException {
+ Document doc = XMLUtil.newDocument();
+
+ Element hibernateMapping = doc.createElement("hibernate-mapping");
+ doc.appendChild(hibernateMapping);
+
+ // MUST Support for embeded objects
+ Struct meta = cfc.getMetaData(pc);
+
+ String extend = cfc.getExtends();
+ boolean isClass = Util.isEmpty(extend);
+
+ // MZ: Fetches all inherited persistent properties
+ // Property[] _props=getAllPersistentProperties(pc,cfc,dc,meta,isClass);
+
+ Property[] _props = getProperties(pc, cfc, dc, meta, isClass, true, data);
+
+ Map joins = new HashMap();
+ PropertyCollection propColl = splitJoins(cfc, joins, _props, data);
+
+ StringBuilder comment = new StringBuilder();
+ comment.append("\nsource:").append(cfc.getPageSource().getDisplayPath());
+ comment.append("\ncompilation-time:")
+ .append(CommonUtil.createDateTime(HibernateUtil.getCompileTime(pc, cfc.getPageSource())));
+ comment.append("\ndatasource:").append(dc.getDatasource().getName());
+ comment.append("\n");
+
+ hibernateMapping.appendChild(doc.createComment(comment.toString()));
+
+ // print.e(cfc.getAbsName()+";"+isClass+" -> "+cfci.getBaseAbsName()+":"+cfci.isBasePeristent());
+ if (!isClass && !cfc.isBasePeristent()) {
+ isClass = true;
+ }
+
+ Element join = null;
+ boolean doTable = true;
+
+ Element clazz;
+ if (isClass) {
+ clazz = doc.createElement("class");
+ hibernateMapping.appendChild(clazz);
+ }
+ // extended CFC
+ else {
+ // MZ: Fetches one level deep
+ _props = getProperties(pc, cfc, dc, meta, isClass, false, data);
+ // MZ: Reinitiate the property collection
+ propColl = splitJoins(cfc, joins, _props, data);
+
+ String ext = CommonUtil.last(extend, ".").trim();
+ Component base = data.getEntityByCFCName(ext, false);
+ ext = HibernateCaster.getEntityName(base);
+
+ String discriminatorValue = toString(cfc, null, meta, "discriminatorValue", data);
+ if (!Util.isEmpty(discriminatorValue, true)) {
+ doTable = false;
+ clazz = doc.createElement("subclass");
+ hibernateMapping.appendChild(clazz);
+ // addClassAttributes(classNode);
+ clazz.setAttribute("extends", ext);
+ clazz.setAttribute("discriminator-value", discriminatorValue);
+
+ String joincolumn = toString(cfc, null, meta, "joincolumn", false, data);
+ if (!Util.isEmpty(joincolumn)) {
+ join = doc.createElement("join");
+ clazz.appendChild(join);
+ doTable = true;
+ Element key = doc.createElement("key");
+ join.appendChild(key);
+ key.setAttribute("column", formatColumn(joincolumn, data));
+ }
+
+ } else {
+ // MZ: Match on joinColumn for a joined subclass, otherwise use a union subclass
+ String joinColumn = toString(cfc, null, meta, "joincolumn", false, data);
+ if (!Util.isEmpty(joinColumn, true)) {
+ clazz = doc.createElement("joined-subclass");
+ hibernateMapping.appendChild(clazz);
+ clazz.setAttribute("extends", ext);
+ Element key = doc.createElement("key");
+ clazz.appendChild(key);
+ key.setAttribute("column", formatColumn(joinColumn, data));
+ } else {
+ // MZ: When no joinColumn exists, default to an explicit table per class
+ clazz = doc.createElement("union-subclass");
+ clazz.setAttribute("extends", ext);
+ doTable = true;
+ hibernateMapping.appendChild(clazz);
+ }
+
+ }
+ }
+
+ // createXMLMappingTuplizer(clazz,pc);
+
+ addGeneralClassAttributes(pc, cfc, meta, clazz, data);
+ String tableName = getTableName(pc, meta, cfc, data);
+
+ if (join != null)
+ clazz = join;
+ if (doTable)
+ addGeneralTableAttributes(pc, dc, cfc, meta, clazz, data);
+
+ Struct columnsInfo = null;
+ if (data.getORMConfiguration().useDBForMapping()) {
+ columnsInfo = data.getTableInfo(dc, getTableName(pc, meta, cfc, data));
+ }
+
+ if (isClass)
+ setCacheStrategy(cfc, null, doc, meta, clazz, data);
+
+ // id
+ if (isClass)
+ addId(cfc, doc, clazz, meta, propColl, columnsInfo, tableName, data);
+
+ // discriminator
+ if (isClass)
+ addDiscriminator(cfc, doc, clazz, pc, meta, data);
+
+ // version
+ if (isClass)
+ addVersion(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
+
+ // property
+ addProperty(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
+
+ // relations
+ addRelation(cfc, clazz, pc, propColl, columnsInfo, tableName, dc, data);
+
+ // collection
+ addCollection(cfc, clazz, pc, propColl, columnsInfo, tableName, data);
+
+ // join
+ addJoin(cfc, clazz, pc, joins, columnsInfo, tableName, dc, data);
+
+ return hibernateMapping;
+ }
+
+ private static Property[] getProperties(PageContext pc, Component cfc, DatasourceConnection dc, Struct meta,
+ boolean isClass, boolean recursivePersistentMappedSuperclass, SessionFactoryData data)
+ throws PageException, PageException {
+ Property[] _props;
+ if (recursivePersistentMappedSuperclass) {
+ _props = CommonUtil.getProperties(cfc, true, true, true, true);
+ } else {
+ _props = cfc.getProperties(true, false, false, false);
+ }
+
+ if (isClass && _props.length == 0 && data.getORMConfiguration().useDBForMapping()) {
+ if (meta == null)
+ meta = cfc.getMetaData(pc);
+ _props = HibernateUtil.createPropertiesFromTable(dc, getTableName(pc, meta, cfc, data));
+ }
+ return _props;
+ }
+
+ private static void addId(Component cfc, Document doc, Element clazz, Struct meta, PropertyCollection propColl,
+ Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
+ Property[] _ids = getIds(cfc, propColl, data);
+
+ // Property[] _ids = ids.toArray(new Property[ids.size()]);
+
+ if (_ids.length == 1)
+ createXMLMappingId(cfc, clazz, _ids[0], columnsInfo, tableName, data);
+ else if (_ids.length > 1)
+ createXMLMappingCompositeId(cfc, clazz, _ids, columnsInfo, tableName, data);
+ else
+ throw ExceptionUtil.createException(data, cfc,
+ "missing id property for entity [" + HibernateCaster.getEntityName(cfc) + "]", null);
+ }
+
+ private static PropertyCollection splitJoins(Component cfc, Map joins, Property[] props,
+ SessionFactoryData data) {
+ Struct sct = CommonUtil.createStruct();
+ ArrayList others = new ArrayList();
+ java.util.List list;
+ String table;
+ Property prop;
+ String fieldType;
+ boolean isJoin;
+ for (int i = 0; i < props.length; i++) {
+ prop = props[i];
+ table = getTable(cfc, prop, data);
+ // joins
+ if (!Util.isEmpty(table, true)) {
+ isJoin = true;
+ // wrong field type
+ try {
+ fieldType = toString(cfc, prop, sct, FIELDTYPE, false, data);
+
+ if ("collection".equalsIgnoreCase(fieldType))
+ isJoin = false;
+ else if ("primary".equals(fieldType))
+ isJoin = false;
+ else if ("version".equals(fieldType))
+ isJoin = false;
+ else if ("timestamp".equals(fieldType))
+ isJoin = false;
+ } catch (PageException e) {
+ }
+
+ // missing column
+ String columns = null;
+ try {
+ if (CommonUtil.isRelated(props[i])) {
+ columns = toString(cfc, props[i], prop.getDynamicAttributes(), "fkcolumn", data);
+ } else {
+ columns = toString(cfc, props[i], prop.getDynamicAttributes(), "joincolumn", data);
+ }
+ } catch (PageException e) {
+ }
+ if (Util.isEmpty(columns))
+ isJoin = false;
+
+ if (isJoin) {
+ table = table.trim();
+ list = (java.util.List) sct.get(table, null);
+ if (list == null) {
+ list = new ArrayList();
+ sct.setEL(CommonUtil.createKey(table), list);
+ }
+ list.add(prop);
+ continue;
+ }
+ }
+ others.add(prop);
+ }
+
+ // fill to joins
+ Iterator> it = sct.entryIterator();
+ Entry e;
+ while (it.hasNext()) {
+ e = it.next();
+ list = (java.util.List) e.getValue();
+ joins.put(e.getKey().getString(), new PropertyCollection(e.getKey().getString(), list));
+ }
+
+ return new PropertyCollection(null, others);
+ }
+
+ private static Property[] getIds(Component cfc, PropertyCollection pc, SessionFactoryData data) {
+ return getIds(cfc, pc.getProperties(), pc.getTableName(), false, data);
+ }
+
+ private static Property[] getIds(Component cfc, Property[] props, String tableName, boolean ignoreTableName,
+ SessionFactoryData data) {
+ ArrayList ids = new ArrayList();
+ for (int y = 0; y < props.length; y++) {
+ if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data))
+ continue;
+
+ String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
+ if ("id".equalsIgnoreCase(fieldType) || CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "id", ',') != -1)
+ ids.add(props[y]);
+ }
+
+ // no id field defined
+ if (ids.size() == 0) {
+ String fieldType;
+ for (int y = 0; y < props.length; y++) {
+ if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data))
+ continue;
+ fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
+ if (Util.isEmpty(fieldType, true) && props[y].getName().equalsIgnoreCase("id")) {
+ ids.add(props[y]);
+ props[y].getDynamicAttributes().setEL(FIELDTYPE, "id");
+ }
+ }
+ }
+
+ // still no id field defined
+ if (ids.size() == 0 && props.length > 0) {
+ String owner = props[0].getOwnerName();
+ if (!Util.isEmpty(owner))
+ owner = CommonUtil.last(owner, ".").trim();
+
+ String fieldType;
+ if (!Util.isEmpty(owner)) {
+ String id = owner + "id";
+ for (int y = 0; y < props.length; y++) {
+ if (!ignoreTableName && !hasTable(cfc, props[y], tableName, data))
+ continue;
+ fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
+ if (Util.isEmpty(fieldType, true) && props[y].getName().equalsIgnoreCase(id)) {
+ ids.add(props[y]);
+ props[y].getDynamicAttributes().setEL(FIELDTYPE, "id");
+ }
+ }
+ }
+ }
+ return ids.toArray(new Property[ids.size()]);
+ }
+
+ private static void addVersion(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl,
+ Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
+ Property[] props = propColl.getProperties();
+ for (int y = 0; y < props.length; y++) {
+ String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, null), null);
+ if ("version".equalsIgnoreCase(fieldType))
+ createXMLMappingVersion(clazz, pc, cfc, props[y], data);
+ else if ("timestamp".equalsIgnoreCase(fieldType))
+ createXMLMappingTimestamp(clazz, pc, cfc, props[y], data);
+ }
+ }
+
+ private static void addCollection(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl,
+ Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
+ Property[] props = propColl.getProperties();
+ for (int y = 0; y < props.length; y++) {
+ String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
+ if ("collection".equalsIgnoreCase(fieldType))
+ createXMLMappingCollection(clazz, pc, cfc, props[y], data);
+ }
+ }
+
+ private static void addJoin(Component cfc, Element clazz, PageContext pc, Map joins,
+ Struct columnsInfo, String tableName, DatasourceConnection dc, SessionFactoryData data)
+ throws PageException {
+
+ Iterator> it = joins.entrySet().iterator();
+ Entry entry;
+ while (it.hasNext()) {
+ entry = it.next();
+ addJoin(cfc, pc, columnsInfo, clazz, entry.getValue(), dc, data);
+ }
+
+ }
+
+ private static void addJoin(Component cfc, PageContext pc, Struct columnsInfo, Element clazz,
+ PropertyCollection coll, DatasourceConnection dc, SessionFactoryData data) throws PageException {
+ String table = coll.getTableName();
+ Property[] properties = coll.getProperties();
+ if (properties.length == 0)
+ return;
+
+ Document doc = XMLUtil.getDocument(clazz);
+
+ Element join = doc.createElement("join");
+ clazz.appendChild(join);
+
+ join.setAttribute("table", escape(HibernateUtil.convertTableName(data, coll.getTableName())));
+ // addTableInfo(joinNode, table, schema, catalog);
+
+ Property first = properties[0];
+ String schema = null, catalog = null, mappedBy = null, columns = null;
+ if (CommonUtil.isRelated(first)) {
+ catalog = toString(cfc, first, first.getDynamicAttributes(), "linkcatalog", data);
+ schema = toString(cfc, first, first.getDynamicAttributes(), "linkschema", data);
+ columns = toString(cfc, first, first.getDynamicAttributes(), "fkcolumn", data);
+
+ } else {
+ catalog = toString(cfc, first, first.getDynamicAttributes(), "catalog", data);
+ schema = toString(cfc, first, first.getDynamicAttributes(), "schema", data);
+ mappedBy = toString(cfc, first, first.getDynamicAttributes(), "mappedby", data);
+ columns = toString(cfc, first, first.getDynamicAttributes(), "joincolumn", data);
+ }
+
+ if (!Util.isEmpty(catalog))
+ join.setAttribute("catalog", catalog);
+ if (!Util.isEmpty(schema))
+ join.setAttribute("schema", schema);
+
+ Element key = doc.createElement("key");
+ join.appendChild(key);
+ if (!Util.isEmpty(mappedBy))
+ key.setAttribute("property-ref", mappedBy);
+ setColumn(doc, key, columns, data);
+
+ addProperty(cfc, join, pc, coll, columnsInfo, table, data);
+ int count = addRelation(cfc, join, pc, coll, columnsInfo, table, dc, data);
+
+ if (count > 0)
+ join.setAttribute("inverse", "true");
+
+ }
+
+ private static int addRelation(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl,
+ Struct columnsInfo, String tableName, DatasourceConnection dc, SessionFactoryData data)
+ throws PageException {
+ Property[] props = propColl.getProperties();
+ int count = 0;
+ for (int y = 0; y < props.length; y++) {
+ String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
+ if ("one-to-one".equalsIgnoreCase(fieldType)) {
+ createXMLMappingOneToOne(clazz, pc, cfc, props[y], data);
+ count++;
+ } else if ("many-to-one".equalsIgnoreCase(fieldType)) {
+ createXMLMappingManyToOne(clazz, pc, cfc, props[y], propColl, data);
+ count++;
+ } else if ("one-to-many".equalsIgnoreCase(fieldType)) {
+ createXMLMappingOneToMany(dc, cfc, propColl, clazz, pc, props[y], data);
+ count++;
+ } else if ("many-to-many".equalsIgnoreCase(fieldType)) {
+ createXMLMappingManyToMany(dc, cfc, propColl, clazz, pc, props[y], data);
+ count++;
+ }
+ }
+ return count;
+ }
+
+ private static void addProperty(Component cfc, Element clazz, PageContext pc, PropertyCollection propColl,
+ Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
+ Property[] props = propColl.getProperties();
+ for (int y = 0; y < props.length; y++) {
+ String fieldType = CommonUtil.toString(props[y].getDynamicAttributes().get(FIELDTYPE, "column"), "column");
+ if ("column".equalsIgnoreCase(fieldType))
+ createXMLMappingProperty(clazz, pc, cfc, props[y], columnsInfo, tableName, data);
+ }
+ }
+
+ private static void addDiscriminator(Component cfc, Document doc, Element clazz, PageContext pc, Struct meta,
+ SessionFactoryData data) throws DOMException, PageException {
+
+ String str = toString(cfc, null, meta, "discriminatorColumn", data);
+ if (!Util.isEmpty(str, true)) {
+ Element disc = doc.createElement("discriminator");
+ clazz.appendChild(disc);
+ disc.setAttribute("column", formatColumn(str, data));
+ }
+
+ }
+
+ private static void addGeneralClassAttributes(PageContext pc, Component cfc, Struct meta, Element clazz,
+ SessionFactoryData data) throws PageException {
+
+ // name
+ clazz.setAttribute("node", HibernateCaster.toComponentName(cfc));
+
+ // entity-name
+ String str = toString(cfc, null, meta, "entityname", data);
+ if (Util.isEmpty(str, true))
+ str = HibernateCaster.getEntityName(cfc);
+ clazz.setAttribute("entity-name", str);
+
+ // batch-size
+ Integer i = toInteger(cfc, meta, "batchsize", data);
+ if (i != null && i.intValue() > 0)
+ clazz.setAttribute("batch-size", CommonUtil.toString(i));
+
+ // dynamic-insert
+ Boolean b = toBoolean(cfc, meta, "dynamicinsert", data);
+ if (b != null && b.booleanValue())
+ clazz.setAttribute("dynamic-insert", "true");
+
+ // dynamic-update
+ b = toBoolean(cfc, meta, "dynamicupdate", data);
+ if (b != null && b.booleanValue())
+ clazz.setAttribute("dynamic-update", "true");
+
+ // lazy (dtd defintion:)
+ b = toBoolean(cfc, meta, "lazy", data);
+ if (b == null)
+ b = Boolean.TRUE;
+ clazz.setAttribute("lazy", CommonUtil.toString(b.booleanValue()));
+
+ // select-before-update
+ b = toBoolean(cfc, meta, "selectbeforeupdate", data);
+ if (b != null && b.booleanValue())
+ clazz.setAttribute("select-before-update", "true");
+
+ // optimistic-lock
+ str = toString(cfc, null, meta, "optimisticLock", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("all".equals(str) || "dirty".equals(str) || "none".equals(str) || "version".equals(str))
+ clazz.setAttribute("optimistic-lock", str);
+ else
+ throw ExceptionUtil.createException(data, cfc, "invalid value [" + str
+ + "] for attribute [optimisticlock] of tag [component], valid values are [all,dirty,none,version]",
+ null);
+ }
+
+ // read-only
+ b = toBoolean(cfc, meta, "readOnly", data);
+ if (b != null && b.booleanValue())
+ clazz.setAttribute("mutable", "false");
+
+ // rowid
+ str = toString(cfc, null, meta, "rowid", data);
+ if (!Util.isEmpty(str, true))
+ clazz.setAttribute("rowid", str);
+
+ // where
+ str = toString(cfc, null, meta, "where", data);
+ if (!Util.isEmpty(str, true))
+ clazz.setAttribute("where", str);
+
+ }
+
+ private static void addGeneralTableAttributes(PageContext pc, DatasourceConnection dc, Component cfc, Struct meta,
+ Element clazz, SessionFactoryData data) throws PageException {
+ // table
+ clazz.setAttribute("table", escape(getTableName(pc, meta, cfc, data)));
+
+ // catalog
+ String str = toString(cfc, null, meta, "catalog", data);
+ if (str == null) // empty string is allowed as input
+ str = ORMConfigurationUtil.getCatalog(data.getORMConfiguration(), dc.getDatasource().getName());
+
+ if (!Util.isEmpty(str, true))
+ clazz.setAttribute("catalog", str);
+
+ // schema
+ str = toString(cfc, null, meta, "schema", data);
+ if (str == null)// empty string is allowed as input
+ str = ORMConfigurationUtil.getSchema(data.getORMConfiguration(), dc.getDatasource().getName());
+ if (!Util.isEmpty(str, true))
+ clazz.setAttribute("schema", str);
+
+ }
+
+ private static String escape(String str) {
+ if (HibernateUtil.isKeyword(str))
+ return "`" + str + "`";
+ return str;
+ }
+
+ private static String getTableName(PageContext pc, Struct meta, Component cfc, SessionFactoryData data)
+ throws PageException {
+ String tableName = toString(cfc, null, meta, "table", data);
+ if (Util.isEmpty(tableName, true))
+ tableName = HibernateCaster.getEntityName(cfc);
+ return HibernateUtil.convertTableName(data, tableName);
+ }
+
+ private static String getTable(Component cfc, Property prop, SessionFactoryData data) {
+ try {
+ return HibernateUtil.convertTableName(data,
+ toString(cfc, prop, prop.getDynamicAttributes(), "table", data));
+ } catch (PageException e) {
+ return null;
+ }
+ }
+
+ private static boolean hasTable(Component cfc, Property prop, String tableName, SessionFactoryData data) {
+ String t = getTable(cfc, prop, data);
+ boolean left = Util.isEmpty(t, true);
+ boolean right = Util.isEmpty(tableName, true);
+ if (left && right)
+ return true;
+ if (left || right)
+ return false;
+ return tableName.trim().equalsIgnoreCase(t.trim());
+ }
+
+ private static void createXMLMappingCompositeId(Component cfc, Element clazz, Property[] props, Struct columnsInfo,
+ String tableName, SessionFactoryData data) throws PageException {
+ Struct meta;
+
+ Document doc = XMLUtil.getDocument(clazz);
+ Element cid = doc.createElement("composite-id");
+ clazz.appendChild(cid);
+
+ // cid.setAttribute("mapped","true");
+
+ Property prop;
+ String fieldType;
+ // ids
+ for (int y = 0; y < props.length; y++) {
+ prop = props[y];
+
+ // do not add "key-property" for many-to-one
+ meta = prop.getDynamicAttributes();
+ fieldType = toString(cfc, prop, meta, "fieldType", data);
+ if (CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "many-to-one", ',') != -1)
+ continue;
+
+ Element key = doc.createElement("key-property");
+ cid.appendChild(key);
+
+ // name
+ key.setAttribute("name", prop.getName());
+
+ // column
+ Element column = doc.createElement("column");
+ key.appendChild(column);
+
+ String str = toString(cfc, prop, meta, "column", data);
+ if (Util.isEmpty(str, true))
+ str = prop.getName();
+ column.setAttribute("name", formatColumn(str, data));
+ ColumnInfo info = getColumnInfo(columnsInfo, tableName, str, null);
+
+ str = toString(cfc, prop, meta, "sqltype", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("sql-type", str);
+ str = toString(cfc, prop, meta, "length", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("length", str);
+
+ String generator = toString(cfc, prop, meta, "generator", data);
+ String type = getType(info, cfc, prop, meta, getDefaultTypeForGenerator(generator, "string"), data);
+ if (!Util.isEmpty(type))
+ key.setAttribute("type", type);
+ }
+
+ // many-to-one
+ for (int y = 0; y < props.length; y++) {
+ prop = props[y];
+ meta = prop.getDynamicAttributes();
+ fieldType = toString(cfc, prop, meta, "fieldType", data);
+ if (CommonUtil.listFindNoCaseIgnoreEmpty(fieldType, "many-to-one", ',') == -1)
+ continue;
+
+ Element key = doc.createElement("key-many-to-one");
+ cid.appendChild(key);
+
+ // name
+ key.setAttribute("name", prop.getName());
+
+ // entity-name
+ setForeignEntityName(cfc, prop, meta, key, false, data);
+
+ // fkcolum
+ String str = toString(cfc, prop, meta, "fkcolumn", data);
+ setColumn(doc, key, str, data);
+
+ // lazy
+ setLazy(cfc, prop, meta, key, data);
+ }
+ }
+
+ private static void createXMLMappingId(Component cfc, Element clazz, Property prop, Struct columnsInfo,
+ String tableName, SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+ String str;
+
+ Document doc = XMLUtil.getDocument(clazz);
+ Element id = doc.createElement("id");
+ clazz.appendChild(id);
+
+ // access
+ str = toString(cfc, prop, meta, "access", data);
+ if (!Util.isEmpty(str, true))
+ id.setAttribute("access", str);
+
+ // name
+ id.setAttribute("name", prop.getName());
+
+ // column
+ Element column = doc.createElement("column");
+ id.appendChild(column);
+
+ str = toString(cfc, prop, meta, "column", data);
+ if (Util.isEmpty(str, true))
+ str = prop.getName();
+ column.setAttribute("name", formatColumn(str, data));
+ ColumnInfo info = getColumnInfo(columnsInfo, tableName, str, null);
+ StringBuilder foreignCFC = new StringBuilder();
+ String generator = createXMLMappingGenerator(id, cfc, prop, foreignCFC, data);
+
+ str = toString(cfc, prop, meta, "length", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("length", str);
+
+ // type
+ String type = getType(info, cfc, prop, meta, getDefaultTypeForGenerator(generator, foreignCFC, data), data);
+ // print.o(prop.getName()+":"+type+"::"+getDefaultTypeForGenerator(generator,foreignCFC));
+ if (!Util.isEmpty(type))
+ id.setAttribute("type", type);
+
+ // unsaved-value
+ str = toString(cfc, prop, meta, "unsavedValue", data);
+ if (str != null)
+ id.setAttribute("unsaved-value", str);
+
+ }
+
+ private static String getDefaultTypeForGenerator(String generator, StringBuilder foreignCFC,
+ SessionFactoryData data) {
+ String value = getDefaultTypeForGenerator(generator, null);
+ if (value != null)
+ return value;
+
+ if ("foreign".equalsIgnoreCase(generator)) {
+ if (!Util.isEmpty(foreignCFC.toString())) {
+ try {
+ Component cfc = data.getEntityByCFCName(foreignCFC.toString(), false);
+ if (cfc != null) {
+ Property[] ids = getIds(cfc, cfc.getProperties(true, false, false, false), null, true, data);
+ if (ids != null && ids.length > 0) {
+ Property id = ids[0];
+ id.getDynamicAttributes();
+ Struct meta = id.getDynamicAttributes();
+ if (meta != null) {
+ String type = CommonUtil.toString(meta.get(TYPE, null));
+
+ if (!Util.isEmpty(type)
+ && (!type.equalsIgnoreCase("any") && !type.equalsIgnoreCase("object"))) {
+ return type;
+ }
+
+ String g = CommonUtil.toString(meta.get(GENERATOR, null));
+ if (!Util.isEmpty(g)) {
+ return getDefaultTypeForGenerator(g, foreignCFC, data);
+ }
+
+ }
+ }
+ }
+ } catch (Throwable t) {
+ if (t instanceof ThreadDeath)
+ throw (ThreadDeath) t;
+ }
+ }
+ return "string";
+ }
+
+ return "string";
+ }
+
+ public static String getDefaultTypeForGenerator(String generator, String defaultValue) {
+ if ("increment".equalsIgnoreCase(generator))
+ return "integer";
+ if ("identity".equalsIgnoreCase(generator))
+ return "integer";
+ if ("native".equalsIgnoreCase(generator))
+ return "integer";
+ if ("seqhilo".equalsIgnoreCase(generator))
+ return "string";
+ if ("uuid".equalsIgnoreCase(generator))
+ return "string";
+ if ("guid".equalsIgnoreCase(generator))
+ return "string";
+ if ("select".equalsIgnoreCase(generator))
+ return "string";
+ return defaultValue;
+ }
+
+ private static String getType(ColumnInfo info, Component cfc, Property prop, Struct meta, String defaultValue,
+ SessionFactoryData data) throws PageException {
+ // ormType
+ String type = toString(cfc, prop, meta, "ormType", data);
+ // type=HibernateCaster.toHibernateType(info,type,null);
+
+ // dataType
+ if (Util.isEmpty(type, true)) {
+ type = toString(cfc, prop, meta, "dataType", data);
+ // type=HibernateCaster.toHibernateType(info,type,null);
+ }
+
+ // type
+ if (Util.isEmpty(type, true)) {
+ type = prop.getType();
+ // type=HibernateCaster.toHibernateType(info,type,null);
+ }
+
+ // type from db info
+ if (Util.isEmpty(type, true)) {
+ if (info != null) {
+ type = info.getTypeName();
+ // type=HibernateCaster.toHibernateType(info,type,defaultValue);
+ } else
+ return defaultValue;
+ }
+ return HibernateCaster.toHibernateType(info, type, defaultValue);
+ }
+
+ private static ColumnInfo getColumnInfo(Struct columnsInfo, String tableName, String columnName,
+ ColumnInfo defaultValue) {
+ if (columnsInfo != null) {
+ ColumnInfo info = (ColumnInfo) columnsInfo.get(CommonUtil.createKey(columnName), null);
+ if (info == null)
+ return defaultValue;
+ return info;
+ }
+ return defaultValue;
+ }
+
+ private static String createXMLMappingGenerator(Element id, Component cfc, Property prop, StringBuilder foreignCFC,
+ SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+
+ // generator
+ String className = toString(cfc, prop, meta, "generator", data);
+ if (Util.isEmpty(className, true))
+ return null;
+
+ Document doc = XMLUtil.getDocument(id);
+ Element generator = doc.createElement("generator");
+ id.appendChild(generator);
+
+ generator.setAttribute("class", className);
+
+ // print.e("generator:"+className);
+
+ // params
+ Object obj = meta.get(PARAMS, null);
+ // if(obj!=null){
+ Struct sct = null;
+ if (obj == null)
+ obj = CommonUtil.createStruct();
+ else if (obj instanceof String)
+ obj = CommonUtil.convertToSimpleMap((String) obj);
+
+ if (CommonUtil.isStruct(obj))
+ sct = CommonUtil.toStruct(obj);
+ else
+ throw ExceptionUtil.createException(data, cfc, "invalid value for attribute [params] of tag [property]",
+ null);
+ className = className.trim().toLowerCase();
+
+ // special classes
+ if ("foreign".equals(className)) {
+ if (!sct.containsKey(PROPERTY))
+ sct.setEL(PROPERTY, toString(cfc, prop, meta, PROPERTY, true, data));
+
+ if (sct.containsKey(PROPERTY)) {
+ String p = CommonUtil.toString(sct.get(PROPERTY), null);
+ if (!Util.isEmpty(p))
+ foreignCFC.append(p);
+ }
+
+ } else if ("select".equals(className)) {
+ // print.e("select:"+toString(meta, "selectKey",true));
+ if (!sct.containsKey(KEY))
+ sct.setEL(KEY, toString(cfc, prop, meta, "selectKey", true, data));
+ } else if ("sequence".equals(className)) {
+ if (!sct.containsKey(SEQUENCE))
+ sct.setEL(SEQUENCE, toString(cfc, prop, meta, "sequence", true, data));
+ }
+
+ // Key[] keys = sct.keys();
+ Iterator> it = sct.entryIterator();
+ Entry e;
+ Element param;
+ while (it.hasNext()) {
+ e = it.next();
+ param = doc.createElement("param");
+ generator.appendChild(param);
+
+ param.setAttribute("name", e.getKey().getLowerString());
+ param.appendChild(doc.createTextNode(CommonUtil.toString(e.getValue())));
+
+ }
+ // }
+ return className;
+ }
+
+ private static void createXMLMappingProperty(Element clazz, PageContext pc, Component cfc, Property prop,
+ Struct columnsInfo, String tableName, SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+
+ // get table name
+ String columnName = toString(cfc, prop, meta, "column", data);
+ if (Util.isEmpty(columnName, true))
+ columnName = prop.getName();
+
+ ColumnInfo info = getColumnInfo(columnsInfo, tableName, columnName, null);
+
+ Document doc = XMLUtil.getDocument(clazz);
+ final Element property = doc.createElement("property");
+ clazz.appendChild(property);
+
+ // name
+ property.setAttribute("name", prop.getName());
+
+ // type
+ String str = getType(info, cfc, prop, meta, "string", data);
+ property.setAttribute("type", str);
+
+ // formula or column
+ str = toString(cfc, prop, meta, "formula", data);
+ Boolean b;
+ if (!Util.isEmpty(str, true)) {
+ property.setAttribute("formula", "(" + str + ")");
+ } else {
+ String length = null;
+ // property.setAttribute("column",columnName);
+
+ Element column = doc.createElement("column");
+ property.appendChild(column);
+ column.setAttribute("name", escape(HibernateUtil.convertColumnName(data, columnName)));
+
+ // check
+ str = toString(cfc, prop, meta, "check", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("check", str);
+
+ // default
+ str = toString(cfc, prop, meta, "dbDefault", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("default", str);
+
+ // index
+ str = toString(cfc, prop, meta, "index", data);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("index", str);
+
+ // length
+ Integer i = toInteger(cfc, meta, "length", data);
+ if (i != null && i > 0) {
+ length = CommonUtil.toString(i.intValue());
+ column.setAttribute("length", length);
+ }
+
+ // not-null
+ b = toBoolean(cfc, meta, "notnull", data);
+ if (b != null && b.booleanValue())
+ column.setAttribute("not-null", "true");
+
+ // precision
+ i = toInteger(cfc, meta, "precision", data);
+ if (i != null && i > -1)
+ column.setAttribute("precision", CommonUtil.toString(i.intValue()));
+
+ // scale
+ i = toInteger(cfc, meta, "scale", data);
+ if (i != null && i > -1)
+ column.setAttribute("scale", CommonUtil.toString(i.intValue()));
+
+ // sql-type
+ str = toString(cfc, prop, meta, "sqltype", data);
+ if (!Util.isEmpty(str, true)) {
+ if ((str == "varchar" || str == "nvarchar") && length != null) {
+ str += "(" + length + ")";
+ }
+ column.setAttribute("sql-type", str);
+ }
+
+ // unique
+ b = toBoolean(cfc, meta, "unique", data);
+ if (b != null && b.booleanValue())
+ column.setAttribute("unique", "true");
+
+ // unique-key
+ str = toString(cfc, prop, meta, "uniqueKey", data);
+ if (Util.isEmpty(str))
+ str = CommonUtil.toString(meta.get(UNIQUE_KEY_NAME, null), null);
+ if (!Util.isEmpty(str, true))
+ column.setAttribute("unique-key", str);
+
+ }
+
+ // generated
+ str = toString(cfc, prop, meta, "generated", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+
+ if ("always".equals(str) || "insert".equals(str) || "never".equals(str))
+ property.setAttribute("generated", str);
+ else
+ throw invalidValue(cfc, prop, "generated", str, "always,insert,never", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [generated] of column
+ // ["+columnName+"], valid values are [always,insert,never]");
+ }
+
+ // update
+ b = toBoolean(cfc, meta, "update", data);
+ if (b != null && !b.booleanValue())
+ property.setAttribute("update", "false");
+
+ // insert
+ b = toBoolean(cfc, meta, "insert", data);
+ if (b != null && !b.booleanValue())
+ property.setAttribute("insert", "false");
+
+ // lazy (dtd defintion:)
+ b = toBoolean(cfc, meta, "lazy", data);
+ if (b != null && b.booleanValue())
+ property.setAttribute("lazy", "true");
+
+ // optimistic-lock
+ b = toBoolean(cfc, meta, "optimisticlock", data);
+ if (b != null && !b.booleanValue())
+ property.setAttribute("optimistic-lock", "false");
+
+ }
+
+ /*
+ * MUST dies kommt aber nicht hier sondern in verarbeitung in component
+ */
+ private static void createXMLMappingOneToOne(Element clazz, PageContext pc, Component cfc, Property prop,
+ SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+
+ Boolean b;
+
+ Document doc = XMLUtil.getDocument(clazz);
+ Element x2o;
+
+ // column
+ String fkcolumn = toString(cfc, prop, meta, "fkcolumn", data);
+ String linkTable = toString(cfc, prop, meta, "linkTable", data);
+
+ if (!Util.isEmpty(linkTable, true) || !Util.isEmpty(fkcolumn, true)) {
+ clazz = getJoin(clazz);
+
+ x2o = doc.createElement("many-to-one");
+ // x2o.setAttribute("column", fkcolumn);
+ x2o.setAttribute("unique", "true");
+
+ if (!Util.isEmpty(linkTable, true)) {
+ setColumn(doc, x2o, linkTable, data);
+ } else {
+ setColumn(doc, x2o, fkcolumn, data);
+ }
+
+ // update
+ b = toBoolean(cfc, meta, "update", data);
+ if (b != null)
+ x2o.setAttribute("update", CommonUtil.toString(b.booleanValue()));
+
+ // insert
+ b = toBoolean(cfc, meta, "insert", data);
+ if (b != null)
+ x2o.setAttribute("insert", CommonUtil.toString(b.booleanValue()));
+
+ // not-null
+ b = toBoolean(cfc, meta, "notNull", data);
+ if (b != null)
+ x2o.setAttribute("not-null", CommonUtil.toString(b.booleanValue()));
+
+ // optimistic-lock
+ b = toBoolean(cfc, meta, "optimisticLock", data);
+ if (b != null)
+ x2o.setAttribute("optimistic-lock", CommonUtil.toString(b.booleanValue()));
+
+ // not-found
+ b = toBoolean(cfc, meta, "missingRowIgnored", data);
+ if (b != null && b.booleanValue())
+ x2o.setAttribute("not-found", "ignore");
+
+ /*
+ * / index str=toString(meta,"index"); if(!Util.isEmpty(str,true)) x2o.setAttribute("index", str);
+ */
+
+ } else {
+ x2o = doc.createElement("one-to-one");
+ }
+ clazz.appendChild(x2o);
+
+ // access
+ String str = toString(cfc, prop, meta, "access", data);
+ if (!Util.isEmpty(str, true))
+ x2o.setAttribute("access", str);
+
+ // constrained
+ b = toBoolean(cfc, meta, "constrained", data);
+ if (b != null && b.booleanValue())
+ x2o.setAttribute("constrained", "true");
+
+ // formula
+ str = toString(cfc, prop, meta, "formula", data);
+ if (!Util.isEmpty(str, true))
+ x2o.setAttribute("formula", str);
+
+ // embed-xml
+ str = toString(cfc, prop, meta, "embedXml", data);
+ if (!Util.isEmpty(str, true))
+ x2o.setAttribute("embed-xml", str);
+
+ // property-ref
+ str = toString(cfc, prop, meta, "mappedBy", data);
+ if (!Util.isEmpty(str, true))
+ x2o.setAttribute("property-ref", str);
+
+ // foreign-key
+ str = toString(cfc, prop, meta, "foreignKeyName", data);
+ if (Util.isEmpty(str, true))
+ str = toString(cfc, prop, meta, "foreignKey", data);
+ if (!Util.isEmpty(str, true))
+ x2o.setAttribute("foreign-key", str);
+
+ setForeignEntityName(cfc, prop, meta, x2o, true, data);
+
+ createXMLMappingXToX(x2o, pc, cfc, prop, meta, data);
+ }
+
+ private static Component loadForeignCFC(PageContext pc, Component cfc, Property prop, Struct meta,
+ SessionFactoryData data) throws PageException {
+ // entity
+ String str = toString(cfc, prop, meta, "entityName", data);
+ Component fcfc = null;
+
+ if (!Util.isEmpty(str, true)) {
+ fcfc = data.getEntityByEntityName(str, false);
+ if (fcfc != null)
+ return fcfc;
+ }
+
+ str = toString(cfc, prop, meta, "cfc", false, data);
+ if (!Util.isEmpty(str, true)) {
+ return data.getEntityByCFCName(str, false);
+ }
+ return null;
+ }
+
+ private static void createXMLMappingCollection(Element clazz, PageContext pc, Component cfc, Property prop,
+ SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+ Document doc = XMLUtil.getDocument(clazz);
+ Element el = null;
+
+ // collection type
+ String str = prop.getType();
+ if (Util.isEmpty(str, true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str))
+ str = "array";
+ else
+ str = str.trim().toLowerCase();
+
+ // bag
+ if ("array".equals(str) || "bag".equals(str)) {
+ el = doc.createElement("bag");
+ }
+ // map
+ else if ("struct".equals(str) || "map".equals(str)) {
+ el = doc.createElement("map");
+
+ // map-key
+ str = toString(cfc, prop, meta, "structKeyColumn", true, data);
+ if (!Util.isEmpty(str, true)) {
+ Element mapKey = doc.createElement("map-key");
+ el.appendChild(mapKey);
+ mapKey.setAttribute("column", str);
+
+ // type
+ str = toString(cfc, prop, meta, "structKeyType", data);
+ if (!Util.isEmpty(str, true))
+ mapKey.setAttribute("type", str);
+ else
+ mapKey.setAttribute("type", "string");
+ }
+ } else
+ throw invalidValue(cfc, prop, "collectiontype", str, "array,struct", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [collectiontype], valid values are
+ // [array,struct]");
+
+ setBeforeJoin(clazz, el);
+
+ // name
+ el.setAttribute("name", prop.getName());
+
+ // table
+ str = toString(cfc, prop, meta, "table", true, data);
+ el.setAttribute("table", escape(HibernateUtil.convertTableName(data, str)));
+
+ // catalog
+ str = toString(cfc, prop, meta, "catalog", data);
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("catalog", str);
+
+ // schema
+ str = toString(cfc, prop, meta, "schema", data);
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("schema", str);
+
+ // mutable
+ Boolean b = toBoolean(cfc, meta, "readonly", data);
+ if (b != null && b.booleanValue())
+ el.setAttribute("mutable", "false");
+
+ // order-by
+ str = toString(cfc, prop, meta, "orderby", data);
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("order-by", str);
+
+ // element-column
+ str = toString(cfc, prop, meta, "elementcolumn", data);
+ if (!Util.isEmpty(str, true)) {
+ Element element = doc.createElement("element");
+ el.appendChild(element);
+
+ // column
+ element.setAttribute("column", formatColumn(str, data));
+
+ // type
+ str = toString(cfc, prop, meta, "elementtype", data);
+ if (!Util.isEmpty(str, true))
+ element.setAttribute("type", str);
+ }
+
+ // batch-size
+ Integer i = toInteger(cfc, meta, "batchsize", data);
+ if (i != null && i.intValue() > 1)
+ el.setAttribute("batch-size", CommonUtil.toString(i.intValue()));
+
+ // column
+ str = toString(cfc, prop, meta, "fkcolumn", data);
+ if (Util.isEmpty(str, true))
+ str = toString(cfc, prop, meta, "column", data);
+ if (!Util.isEmpty(str, true)) {
+ Element key = doc.createElement("key");
+ CommonUtil.setFirst(el, key);
+ // el.appendChild(key);
+
+ // column
+ key.setAttribute("column", formatColumn(str, data));
+
+ // property-ref
+ str = toString(cfc, prop, meta, "mappedBy", data);
+ if (!Util.isEmpty(str, true))
+ key.setAttribute("property-ref", str);
+ }
+
+ // cache
+ setCacheStrategy(cfc, prop, doc, meta, el, data);
+
+ // optimistic-lock
+ b = toBoolean(cfc, meta, "optimisticlock", data);
+ if (b != null && !b.booleanValue())
+ el.setAttribute("optimistic-lock", "false");
+
+ }
+
+ private static void setBeforeJoin(Element clazz, Element el) {
+ Element join;
+ if (clazz.getNodeName().equals("join")) {
+ join = clazz;
+ clazz = getClazz(clazz);
+ } else {
+ join = getJoin(clazz);
+ }
+
+ if (join == clazz)
+ clazz.appendChild(el);
+ else
+ clazz.insertBefore(el, join);
+
+ }
+
+ private static Element getClazz(Element join) {
+ if (join.getNodeName().equals("join")) {
+ return (Element) join.getParentNode();
+ }
+ return join;
+ }
+
+ private static Element getJoin(Element clazz) {
+ if (clazz.getNodeName().equals("subclass")) {
+ NodeList joins = clazz.getElementsByTagName("join");
+ if (joins != null && joins.getLength() > 0)
+ return (Element) joins.item(0);
+ }
+ return clazz;
+ }
+
+ private static void createXMLMappingManyToMany(DatasourceConnection dc, Component cfc, PropertyCollection propColl,
+ Element clazz, PageContext pc, Property prop, SessionFactoryData data) throws PageException {
+ Element el = createXMLMappingXToMany(propColl, clazz, pc, cfc, prop, data);
+ Struct meta = prop.getDynamicAttributes();
+ Document doc = XMLUtil.getDocument(clazz);
+ Element m2m = doc.createElement("many-to-many");
+ el.appendChild(m2m);
+
+ // link
+ setLink(dc, cfc, prop, el, meta, true, data);
+
+ setForeignEntityName(cfc, prop, meta, m2m, true, data);
+
+ // order-by
+ String str = toString(cfc, prop, meta, "orderby", data);
+ if (!Util.isEmpty(str, true))
+ m2m.setAttribute("order-by", str);
+
+ // column
+ str = toString(cfc, prop, meta, "inversejoincolumn", data);
+
+ // build fkcolumn name
+ if (Util.isEmpty(str, true)) {
+ Component other = loadForeignCFC(pc, cfc, prop, meta, data);
+ if (other != null) {
+ boolean isClass = Util.isEmpty(other.getExtends());
+ // MZ: Recursive search for persistent mappedSuperclass properties
+ Property[] _props = getProperties(pc, other, dc, meta, isClass, true, data);
+ PropertyCollection _propColl = splitJoins(cfc, new HashMap(), _props, data);
+ _props = _propColl.getProperties();
+
+ Struct m;
+ Property _prop = null;
+ for (int i = 0; i < _props.length; i++) {
+ m = _props[i].getDynamicAttributes();
+ // fieldtype
+ String fieldtype = CommonUtil.toString(m.get(FIELDTYPE, null), null);
+ if ("many-to-many".equalsIgnoreCase(fieldtype)) {
+ // linktable
+ String currLinkTable = CommonUtil.toString(meta.get(LINK_TABLE, null), null);
+ String othLinkTable = CommonUtil.toString(m.get(LINK_TABLE, null), null);
+ if (currLinkTable.equals(othLinkTable)) {
+ // cfc name
+ String cfcName = CommonUtil.toString(m.get(CFC, null), null);
+ if (cfc.equalTo(cfcName)) {
+ _prop = _props[i];
+ }
+ }
+ }
+ }
+ str = createM2MFKColumnName(other, _prop, _propColl, data);
+ }
+ }
+ setColumn(doc, m2m, str, data);
+
+ // not-found
+ Boolean b = toBoolean(cfc, meta, "missingrowignored", data);
+ if (b != null && b.booleanValue())
+ m2m.setAttribute("not-found", "ignore");
+
+ // property-ref
+ str = toString(cfc, prop, meta, "mappedby", data);
+ if (!Util.isEmpty(str, true))
+ m2m.setAttribute("property-ref", str);
+
+ // foreign-key
+ str = toString(cfc, prop, meta, "foreignKeyName", data);
+ if (Util.isEmpty(str, true))
+ str = toString(cfc, prop, meta, "foreignKey", data);
+ if (!Util.isEmpty(str, true))
+ m2m.setAttribute("foreign-key", str);
+ }
+
+ private static boolean setLink(DatasourceConnection dc, Component cfc, Property prop, Element el, Struct meta,
+ boolean linkTableRequired, SessionFactoryData data) throws PageException {
+ String str = toString(cfc, prop, meta, "linktable", linkTableRequired, data);
+
+ if (!Util.isEmpty(str, true)) {
+
+ el.setAttribute("table", escape(HibernateUtil.convertTableName(data, str)));
+
+ // schema
+ str = toString(cfc, prop, meta, "linkschema", data);
+ if (Util.isEmpty(str, true))
+ str = ORMConfigurationUtil.getSchema(data.getORMConfiguration(), dc.getDatasource().getName());
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("schema", str);
+
+ // catalog
+ str = toString(cfc, prop, meta, "linkcatalog", data);
+ if (Util.isEmpty(str, true))
+ str = ORMConfigurationUtil.getCatalog(data.getORMConfiguration(), dc.getDatasource().getName());
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("catalog", str);
+ return true;
+ }
+ return false;
+ }
+
+ private static void createXMLMappingOneToMany(DatasourceConnection dc, Component cfc, PropertyCollection propColl,
+ Element clazz, PageContext pc, Property prop, SessionFactoryData data) throws PageException {
+ Element el = createXMLMappingXToMany(propColl, clazz, pc, cfc, prop, data);
+ Struct meta = prop.getDynamicAttributes();
+ Document doc = XMLUtil.getDocument(clazz);
+ Element x2m;
+
+ // order-by
+ String str = toString(cfc, prop, meta, "orderby", data);
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("order-by", str);
+
+ // link
+ if (setLink(dc, cfc, prop, el, meta, false, data)) {
+ x2m = doc.createElement("many-to-many");
+ x2m.setAttribute("unique", "true");
+
+ str = toString(cfc, prop, meta, "inversejoincolumn", data);
+ setColumn(doc, x2m, str, data);
+ } else {
+ x2m = doc.createElement("one-to-many");
+ }
+ el.appendChild(x2m);
+
+ // entity-name
+
+ setForeignEntityName(cfc, prop, meta, x2m, true, data);
+
+ }
+
+ private static Element createXMLMappingXToMany(PropertyCollection propColl, Element clazz, PageContext pc,
+ Component cfc, Property prop, SessionFactoryData data) throws PageException {
+ final Struct meta = prop.getDynamicAttributes();
+ Document doc = XMLUtil.getDocument(clazz);
+ Element el = null;
+
+ // collection type
+ String str = prop.getType();
+ if (Util.isEmpty(str, true) || "any".equalsIgnoreCase(str) || "object".equalsIgnoreCase(str))
+ str = "array";
+ else
+ str = str.trim().toLowerCase();
+
+ Element mapKey = null;
+ // bag
+ if ("array".equals(str) || "bag".equals(str)) {
+ el = doc.createElement("bag");
+
+ }
+ // map
+ else if ("struct".equals(str) || "map".equals(str)) {
+ el = doc.createElement("map");
+
+ // map-key
+ mapKey = doc.createElement("map-key");
+ // el.appendChild(mapKey);
+
+ // column
+ str = toString(cfc, prop, meta, "structKeyColumn", true, data);
+ mapKey.setAttribute("column", formatColumn(str, data));
+
+ // type
+ str = toString(cfc, prop, meta, "structKeyType", data);
+ if (!Util.isEmpty(str, true))
+ mapKey.setAttribute("type", str);
+ else
+ mapKey.setAttribute("type", "string");// MUST get type dynamicly
+ } else
+ throw invalidValue(cfc, prop, "collectiontype", str, "array,struct", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [collectiontype], valid values are
+ // [array,struct]");
+
+ setBeforeJoin(clazz, el);
+
+ // batch-size
+ Integer i = toInteger(cfc, meta, "batchsize", data);
+ if (i != null) {
+ if (i.intValue() > 1)
+ el.setAttribute("batch-size", CommonUtil.toString(i.intValue()));
+ }
+
+ // cacheUse
+ setCacheStrategy(cfc, prop, doc, meta, el, data);
+
+ // column
+ str = createFKColumnName(cfc, prop, propColl, data);
+
+ if (!Util.isEmpty(str, true)) {
+ Element key = doc.createElement("key");
+ el.appendChild(key);
+
+ // column
+ setColumn(doc, key, str, data);
+
+ // property-ref
+ str = toString(cfc, prop, meta, "mappedBy", data);
+ if (!Util.isEmpty(str, true))
+ key.setAttribute("property-ref", str);
+ }
+
+ // inverse
+ Boolean b = toBoolean(cfc, meta, "inverse", data);
+ if (b != null && b.booleanValue())
+ el.setAttribute("inverse", "true");
+
+ // mutable
+ b = toBoolean(cfc, meta, "readonly", data);
+ if (b != null && b.booleanValue())
+ el.setAttribute("mutable", "false");
+
+ // optimistic-lock
+ b = toBoolean(cfc, meta, "optimisticlock", data);
+ if (b != null && !b.booleanValue())
+ el.setAttribute("optimistic-lock", "false");
+
+ // where
+ str = toString(cfc, prop, meta, "where", data);
+ if (!Util.isEmpty(str, true))
+ el.setAttribute("where", str);
+
+ // add map key
+ if (mapKey != null)
+ el.appendChild(mapKey);
+
+ createXMLMappingXToX(el, pc, cfc, prop, meta, data);
+
+ return el;
+ }
+
+ private static String createFKColumnName(Component cfc, Property prop, PropertyCollection propColl,
+ SessionFactoryData data) throws PageException {
+
+ // fk column from local defintion
+ String str = prop == null ? null : toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", data);
+ if (!Util.isEmpty(str))
+ return str;
+
+ // no local defintion, get from Foreign enity
+ Struct meta = prop.getDynamicAttributes();
+ String type = toString(cfc, prop, meta, "fieldtype", false, data);
+ String otherType;
+ if ("many-to-one".equalsIgnoreCase(type))
+ otherType = "one-to-many";
+ else if ("one-to-many".equalsIgnoreCase(type))
+ otherType = "many-to-one";
+ else
+ return createM2MFKColumnName(cfc, prop, propColl, data);
+
+ String feName = toString(cfc, prop, meta, "cfc", true, data);
+ Component feCFC = data.getEntityByCFCName(feName, false);
+ Property[] feProps = feCFC.getProperties(true, false, false, false);
+
+ Property p;
+ Component _cfc;
+ for (int i = 0; i < feProps.length; i++) {
+ p = feProps[i];
+
+ // compare fieldType
+ str = toString(feCFC, p, p.getDynamicAttributes(), "fieldtype", false, data);
+ if (!otherType.equalsIgnoreCase(str))
+ continue;
+
+ // compare cfc
+ str = toString(feCFC, p, p.getDynamicAttributes(), "cfc", false, data);
+ if (Util.isEmpty(str))
+ continue;
+ _cfc = data.getEntityByCFCName(str, false);
+ if (_cfc == null || !_cfc.equals(cfc))
+ continue;
+
+ // get fkcolumn
+ str = toString(_cfc, p, p.getDynamicAttributes(), "fkcolumn", data);
+ if (!Util.isEmpty(str))
+ return str;
+
+ }
+ throw ExceptionUtil.createException(data, null,
+ "cannot terminate foreign key column name for component " + cfc.getName(), null);
+ }
+
+ private static String createM2MFKColumnName(Component cfc, Property prop, PropertyCollection propColl,
+ SessionFactoryData data) throws PageException {
+
+ String str = prop == null ? null : toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", data);
+ if (Util.isEmpty(str)) {
+ Property[] ids = getIds(cfc, propColl, data);
+ if (ids.length == 1) {
+ str = toString(cfc, ids[0], ids[0].getDynamicAttributes(), "column", data);
+ if (Util.isEmpty(str, true))
+ str = ids[0].getName();
+ } else if (prop != null)
+ str = toString(cfc, prop, prop.getDynamicAttributes(), "fkcolumn", true, data);
+ else
+ throw ExceptionUtil.createException(data, null,
+ "cannot terminate foreign key column name for component " + cfc.getName(), null);
+
+ str = HibernateCaster.getEntityName(cfc) + "_" + str;
+ }
+ return str;
+ }
+
+ private static void setForeignEntityName(Component cfc, Property prop, Struct meta, Element el, boolean cfcRequired,
+ SessionFactoryData data) throws PageException {
+ // entity
+ String str = cfcRequired ? null : toString(cfc, prop, meta, "entityName", data);
+ if (!Util.isEmpty(str, true)) {
+ el.setAttribute("entity-name", str);
+ } else {
+ // cfc
+ // createFKColumnName( cfc, prop, propColl);
+
+ str = toString(cfc, prop, meta, "cfc", cfcRequired, data);
+ if (!Util.isEmpty(str, true)) {
+ Component _cfc = data.getEntityByCFCName(str, false);
+ str = HibernateCaster.getEntityName(_cfc);
+ el.setAttribute("entity-name", str);
+ }
+ }
+ }
+
+ private static void setCacheStrategy(Component cfc, Property prop, Document doc, Struct meta, Element el,
+ SessionFactoryData data) throws PageException {
+ String strategy = toString(cfc, prop, meta, "cacheuse", data);
+
+ if (!Util.isEmpty(strategy, true)) {
+ strategy = strategy.trim().toLowerCase();
+ if ("read-only".equals(strategy) || "nonstrict-read-write".equals(strategy) || "read-write".equals(strategy)
+ || "transactional".equals(strategy)) {
+ Element cache = doc.createElement("cache");
+ CommonUtil.setFirst(el, cache);
+ el.appendChild(cache);
+ cache.setAttribute("usage", strategy);
+ String name = toString(cfc, prop, meta, "cacheName", data);
+ if (!Util.isEmpty(name, true)) {
+ cache.setAttribute("region", name);
+ }
+ } else
+ throw ExceptionUtil.createException(data, cfc, "invalid value [" + strategy
+ + "] for attribute [cacheuse], valid values are [read-only,nonstrict-read-write,read-write,transactional]",
+ null);
+ }
+
+ }
+
+ private static void setColumn(Document doc, Element el, String columnValue, SessionFactoryData data)
+ throws PageException {
+ if (Util.isEmpty(columnValue, true))
+ return;
+
+ String[] arr = CommonUtil.toStringArray(columnValue, ",");
+ if (arr.length == 1) {
+ el.setAttribute("column", formatColumn(arr[0], data));
+ } else {
+ Element column;
+ for (int i = 0; i < arr.length; i++) {
+ column = doc.createElement("column");
+ el.appendChild(column);
+ column.setAttribute("name", formatColumn(arr[i], data));
+ }
+ }
+ }
+
+ private static void createXMLMappingManyToOne(Element clazz, PageContext pc, Component cfc, Property prop,
+ PropertyCollection propColl, SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+ Boolean b;
+
+ Document doc = XMLUtil.getDocument(clazz);
+ clazz = getJoin(clazz);
+
+ Element m2o = doc.createElement("many-to-one");
+ clazz.appendChild(m2o);
+
+ // columns
+ String linktable = toString(cfc, prop, meta, "linktable", data);
+ String _columns;
+ if (!Util.isEmpty(linktable, true))
+ _columns = toString(cfc, prop, meta, "inversejoincolumn", data);
+ else
+ _columns = createFKColumnName(cfc, prop, propColl, data);// toString(cfc,prop,meta,"fkcolumn");
+ setColumn(doc, m2o, _columns, data);
+
+ // cfc
+ setForeignEntityName(cfc, prop, meta, m2o, true, data);
+
+ // column
+ // String str=toString(prop,meta,"column",true);
+ // m2o.setAttribute("column", str);
+
+ // insert
+ b = toBoolean(cfc, meta, "insert", data);
+ if (b != null && !b.booleanValue())
+ m2o.setAttribute("insert", "false");
+
+ // update
+ b = toBoolean(cfc, meta, "update", data);
+ if (b != null && !b.booleanValue())
+ m2o.setAttribute("update", "false");
+
+ // property-ref
+ String str = toString(cfc, prop, meta, "mappedBy", data);
+ if (!Util.isEmpty(str, true))
+ m2o.setAttribute("property-ref", str);
+
+ // update
+ b = toBoolean(cfc, meta, "unique", data);
+ if (b != null && b.booleanValue())
+ m2o.setAttribute("unique", "true");
+
+ // not-null
+ b = toBoolean(cfc, meta, "notnull", data);
+ if (b != null && b.booleanValue())
+ m2o.setAttribute("not-null", "true");
+
+ // optimistic-lock
+ b = toBoolean(cfc, meta, "optimisticLock", data);
+ if (b != null && !b.booleanValue())
+ m2o.setAttribute("optimistic-lock", "false");
+
+ // not-found
+ b = toBoolean(cfc, meta, "missingRowIgnored", data);
+ if (b != null && b.booleanValue())
+ m2o.setAttribute("not-found", "ignore");
+
+ // index
+ str = toString(cfc, prop, meta, "index", data);
+ if (!Util.isEmpty(str, true))
+ m2o.setAttribute("index", str);
+
+ // unique-key
+ str = toString(cfc, prop, meta, "uniqueKeyName", data);
+ if (Util.isEmpty(str, true))
+ str = toString(cfc, prop, meta, "uniqueKey", data);
+ if (!Util.isEmpty(str, true))
+ m2o.setAttribute("unique-key", str);
+
+ // foreign-key
+ str = toString(cfc, prop, meta, "foreignKeyName", data);
+ if (Util.isEmpty(str, true))
+ str = toString(cfc, prop, meta, "foreignKey", data);
+ if (!Util.isEmpty(str, true))
+ m2o.setAttribute("foreign-key", str);
+
+ // access
+ str = toString(cfc, prop, meta, "access", data);
+ if (!Util.isEmpty(str, true))
+ m2o.setAttribute("access", str);
+
+ createXMLMappingXToX(m2o, pc, cfc, prop, meta, data);
+
+ }
+
+ private static String formatColumn(String name, SessionFactoryData data) throws PageException {
+ name = name.trim();
+ return escape(HibernateUtil.convertColumnName(data, name));
+ }
+
+ /*
+ *
+ *
+ *
+ *
+ */
+ private static void createXMLMappingXToX(Element x2x, PageContext pc, Component cfc, Property prop, Struct meta,
+ SessionFactoryData data) throws PageException {
+ x2x.setAttribute("name", prop.getName());
+
+ // cascade
+ String str = toString(cfc, prop, meta, "cascade", data);
+ if (!Util.isEmpty(str, true))
+ x2x.setAttribute("cascade", str);
+
+ // fetch
+ str = toString(cfc, prop, meta, "fetch", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("join".equals(str) || "select".equals(str))
+ x2x.setAttribute("fetch", str);
+ else
+ throw invalidValue(cfc, prop, "fetch", str, "join,select", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [fetch], valid values are
+ // [join,select]");
+ }
+
+ // lazy
+ setLazy(cfc, prop, meta, x2x, data);
+
+ }
+
+ private static void setLazy(Component cfc, Property prop, Struct meta, Element x2x, SessionFactoryData data)
+ throws PageException {
+ String str = toString(cfc, prop, meta, "lazy", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim();
+ String name = x2x.getNodeName();
+ Boolean b = CommonUtil.toBoolean(str, null);
+
+ //
+ //
+ if ("many-to-one".equals(name) || "one-to-one".equals(name)) {
+ if (b != null)
+ x2x.setAttribute("lazy", b.booleanValue() ? "proxy" : "false");
+ else if ("proxy".equalsIgnoreCase(str))
+ x2x.setAttribute("lazy", "proxy");
+ else if ("no-proxy".equalsIgnoreCase(str))
+ x2x.setAttribute("lazy", "no-proxy");
+ else
+ throw invalidValue(cfc, prop, "lazy", str, "true,false,proxy,no-proxy", data);
+ }
+
+ //
+ //
+ else if ("many-to-many".equals(name) || "key-many-to-one".equals(name)) {
+ if (b != null)
+ x2x.setAttribute("lazy", b.booleanValue() ? "proxy" : "false");
+ else if ("proxy".equalsIgnoreCase(str))
+ x2x.setAttribute("lazy", "proxy");
+ throw invalidValue(cfc, prop, "lazy", str, "true,false,proxy", data);
+
+ }
+
+ else {
+ if (b != null)
+ x2x.setAttribute("lazy", b.booleanValue() ? "true" : "false");
+ else if ("extra".equalsIgnoreCase(str))
+ x2x.setAttribute("lazy", "extra");
+ else
+ throw invalidValue(cfc, prop, "lazy", str, "true,false,extra", data);
+ }
+ }
+ }
+
+ private static void createXMLMappingTimestamp(Element clazz, PageContext pc, Component cfc, Property prop,
+ SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+ String str;
+ Boolean b;
+
+ Document doc = XMLUtil.getDocument(clazz);
+ Element timestamp = doc.createElement("timestamp");
+ clazz.appendChild(timestamp);
+
+ timestamp.setAttribute("name", prop.getName());
+
+ // access
+ str = toString(cfc, prop, meta, "access", data);
+ if (!Util.isEmpty(str, true))
+ timestamp.setAttribute("access", str);
+
+ // column
+ str = toString(cfc, prop, meta, "column", data);
+ if (Util.isEmpty(str, true))
+ str = prop.getName();
+ timestamp.setAttribute("column", formatColumn(str, data));
+
+ // generated
+ b = toBoolean(cfc, meta, "generated", data);
+ if (b != null)
+ timestamp.setAttribute("generated", b.booleanValue() ? "always" : "never");
+
+ // source
+ str = toString(cfc, prop, meta, "source", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("db".equals(str) || "vm".equals(str))
+ timestamp.setAttribute("source", str);
+ else
+ throw invalidValue(cfc, prop, "source", str, "db,vm", data);
+ }
+
+ // unsavedValue
+ str = toString(cfc, prop, meta, "unsavedValue", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("null".equals(str) || "undefined".equals(str))
+ timestamp.setAttribute("unsaved-value", str);
+ else
+ throw invalidValue(cfc, prop, "unsavedValue", str, "null, undefined", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [unsavedValue], valid values are
+ // [null, undefined]");
+ }
+ }
+
+ private static PageException invalidValue(Component cfc, Property prop, String attrName, String invalid,
+ String valid, SessionFactoryData data) {
+ String owner = prop.getOwnerName();
+ if (Util.isEmpty(owner))
+ return ExceptionUtil.createException(data, cfc, "invalid value [" + invalid + "] for attribute [" + attrName
+ + "] of property [" + prop.getName() + "], valid values are [" + valid + "]", null);
+ return ExceptionUtil.createException(data, cfc,
+ "invalid value [" + invalid + "] for attribute [" + attrName + "] of property [" + prop.getName()
+ + "] of Component [" + CommonUtil.last(owner, ".") + "], valid values are [" + valid + "]",
+ null);
+ }
+
+ private static void createXMLMappingVersion(Element clazz, PageContext pc, Component cfc, Property prop,
+ SessionFactoryData data) throws PageException {
+ Struct meta = prop.getDynamicAttributes();
+
+ Document doc = XMLUtil.getDocument(clazz);
+ Element version = doc.createElement("version");
+ clazz.appendChild(version);
+
+ version.setAttribute("name", prop.getName());
+
+ // column
+ String str = toString(cfc, prop, meta, "column", data);
+ if (Util.isEmpty(str, true))
+ str = prop.getName();
+ version.setAttribute("column", formatColumn(str, data));
+
+ // access
+ str = toString(cfc, prop, meta, "access", data);
+ if (!Util.isEmpty(str, true))
+ version.setAttribute("access", str);
+
+ // generated
+ Object o = meta.get(GENERATED, null);
+ if (o != null) {
+ Boolean b = CommonUtil.toBoolean(o, null);
+ str = null;
+ if (b != null) {
+ str = b.booleanValue() ? "always" : "never";
+ } else {
+ str = CommonUtil.toString(o, null);
+ if ("always".equalsIgnoreCase(str))
+ str = "always";
+ else if ("never".equalsIgnoreCase(str))
+ str = "never";
+ else
+ throw invalidValue(cfc, prop, "generated", o.toString(), "true,false,always,never", data);
+ // throw new ORMException("invalid value ["+o+"] for attribute [generated] of property
+ // ["+prop.getName()+"], valid values are [true,false,always,never]");
+ }
+ version.setAttribute("generated", str);
+ }
+
+ // insert
+ Boolean b = toBoolean(cfc, meta, "insert", data);
+ if (b != null && !b.booleanValue())
+ version.setAttribute("insert", "false");
+
+ // type
+ String typeName = "dataType";
+ str = toString(cfc, prop, meta, typeName, data);
+ if (Util.isEmpty(str, true)) {
+ typeName = "ormType";
+ str = toString(cfc, prop, meta, typeName, data);
+ }
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("int".equals(str) || "integer".equals(str))
+ version.setAttribute("type", "integer");
+ else if ("long".equals(str))
+ version.setAttribute("type", "long");
+ else if ("short".equals(str))
+ version.setAttribute("type", "short");
+ else
+ throw invalidValue(cfc, prop, typeName, str, "int,integer,long,short", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute ["+typeName+"], valid values are
+ // [int,integer,long,short]");
+ } else
+ version.setAttribute("type", "integer");
+
+ // unsavedValue
+ str = toString(cfc, prop, meta, "unsavedValue", data);
+ if (!Util.isEmpty(str, true)) {
+ str = str.trim().toLowerCase();
+ if ("null".equals(str) || "negative".equals(str) || "undefined".equals(str))
+ version.setAttribute("unsaved-value", str);
+ else
+ throw invalidValue(cfc, prop, "unsavedValue", str, "null, negative, undefined", data);
+ // throw new ORMException("invalid value ["+str+"] for attribute [unsavedValue], valid values are
+ // [null, negative, undefined]");
+ }
+ }
+
+ private static String toString(Component cfc, Property prop, Struct sct, String key, SessionFactoryData data)
+ throws PageException {
+ return toString(cfc, prop, sct, key, false, data);
+ }
+
+ private static String toString(Component cfc, Property prop, Struct sct, String key, boolean throwErrorWhenNotExist,
+ SessionFactoryData data) throws PageException {
+ return toString(cfc, prop, sct, CommonUtil.createKey(key), throwErrorWhenNotExist, data);
+ }
+
+ private static String toString(Component cfc, Property prop, Struct sct, Collection.Key key,
+ boolean throwErrorWhenNotExist, SessionFactoryData data) throws PageException {
+ Object value = sct.get(key, null);
+ if (value == null) {
+ if (throwErrorWhenNotExist) {
+ if (prop == null)
+ throw ExceptionUtil.createException(data, cfc, "attribute [" + key + "] is required", null);
+ throw ExceptionUtil.createException(data, cfc, "attribute [" + key + "] of property [" + prop.getName()
+ + "] of Component [" + _getCFCName(prop) + "] is required", null);
+ }
+ return null;
+ }
+
+ String str = CommonUtil.toString(value, null);
+ if (str == null) {
+ if (prop == null)
+ throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value)
+ + "] for attribute [" + key + "], value must be a string", null);
+ throw ExceptionUtil.createException(data, cfc,
+ "invalid type [" + CommonUtil.toTypeName(value) + "] for attribute [" + key + "] of property ["
+ + prop.getName() + "] of Component [" + _getCFCName(prop) + "], value must be a string",
+ null);
+ }
+ return str;
+ }
+
+ private static String _getCFCName(Property prop) {
+ String owner = prop.getOwnerName();
+ return CommonUtil.last(owner, ".");
+ }
+
+ private static Boolean toBoolean(Component cfc, Struct sct, String key, SessionFactoryData data)
+ throws PageException {
+ Object value = sct.get(CommonUtil.createKey(key), null);
+ if (value == null)
+ return null;
+
+ Boolean b = CommonUtil.toBoolean(value, null);
+ if (b == null)
+ throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value)
+ + "] for attribute [" + key + "], value must be a boolean", null);
+ return b;
+ }
+
+ private static Integer toInteger(Component cfc, Struct sct, String key, SessionFactoryData data)
+ throws PageException {
+ Object value = sct.get(CommonUtil.createKey(key), null);
+ if (value == null)
+ return null;
+
+ Integer i = CommonUtil.toInteger(value, null);
+ if (i == null)
+ throw ExceptionUtil.createException(data, cfc, "invalid type [" + CommonUtil.toTypeName(value)
+ + "] for attribute [" + key + "], value must be a numeric value", null);
+ return i;
+ }
+
+ /**
+ * Convert the document to a file-ready XML string.
+ *
+ * Will prepend the XML head tags.
+ *
+ * @param document
+ * The W3C document root element for converting to an XML string
+ *
+ * @return a fully-formed HBM XML document ready to save to a file.
+ *
+ * @throws PageException
+ */
+ public static String toMappingString(Element document) throws PageException {
+ return getXMLOpen() + XMLUtil.toString(document);
+ }
+
+ /**
+ * Save the XML dom to a hibernate mapping file (myEntity.hbm.xml)
+ *
+ * @param cfc
+ * Lucee Component (entity) that we're saving the mapping for
+ * @param xml
+ * Fully-formed hibernate mapping XML
+ */
+ public static void saveMapping(Component cfc, String xml) {
+ Resource res = getMappingResource(cfc);
+ if (res != null) {
+ try {
+ CommonUtil.write(res, xml, CommonUtil.UTF8(), false);
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ /**
+ * Get the hibernate mapping XML as a string.
+ *
+ * @param cfc
+ * Lucee Component (entity) for which to load the HBM mapping xml file
+ *
+ * @return A giant XML string
+ */
+ public static String loadMapping(Component cfc) throws PageException, IOException {
+
+ Resource resource = getMappingResource(cfc);
+ if (resource == null)
+ throw ExceptionUtil.createException("Hibernate mapping not found for entity: " + cfc.getName());
+
+ String xml = CommonUtil.toString(resource, CommonUtil.UTF8());
+ // return CommonUtil.toXML(xml).getOwnerDocument().getDocumentElement();
+ return xml;
+ }
+
+ /**
+ * Get the last modified time for this component's mapping. Will return 0 if no mapping found.
+ *
+ * @param cfc
+ * The Lucee component (persistent entity) we're pulling the modification date for
+ *
+ * @return A long value representing the time the file was last modified, measured in milliseconds
+ * since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an
+ * I/O error occurs
+ *
+ * @see {lucee.commons.io.res.Resource#lastModified}
+ */
+ public static long getMappingLastModified(Component cfc) {
+ Resource res = getMappingResource(cfc);
+ if (res == null)
+ return 0;
+ return res.lastModified();
+ }
+
+ /**
+ * Get the HBM mapping file ( i.e. `models/myEntity.hbm.xml`) for this persistent Component/entity.
+ *
+ * @param cfc
+ * Lucee Component
+ *
+ * @return Lucee Resource, i.e. a Lucee-fied File object
+ */
+ public static Resource getMappingResource(Component cfc) {
+ Resource res = cfc.getPageSource().getResource();
+ if (res == null)
+ return null;
+ return res.getParentResource().getRealResource(res.getName() + ".hbm.xml");
+ }
+
+ /**
+ * Get the opening of a Hibernate mapping XML file, including tag and DOCTYPE declaration
+ */
+ public static String getXMLOpen() {
+ StringBuilder xml = new StringBuilder();
+ xml.append("\n");
+ xml.append(HIBERNATE_3_DOCTYPE_DEFINITION + "\n");
+ // xml.append("\n");
+ return xml.toString();
+ }
+
+ /**
+ * Strip the open/close tags (i.e. ``, ``, ``) from an hbm.xml file.
+ *
+ * Useful for assembling multiple entities into a single `` element for sending to Hibernate.
+ *
+ * @param xml
+ * XML string from which to strip open and close tags
+ *
+ * @return an XML string with the DOCTYPE, `` and `` elements removed
+ */
+ public static String stripXMLOpenClose(String xml) {
+ return xml.replaceAll("<\\?xml[^>]+>", "").replaceAll("]+>", "").replaceAll("?hibernate-mapping>",
+ "");
+ }
}
class PropertyCollection {
- private Property[] properties;
- private String tableName;
-
- public PropertyCollection(String tableName, Property[] properties) {
- this.tableName = tableName;
- this.properties = properties;
- }
-
- public PropertyCollection(String tableName, java.util.List properties) {
- this.tableName = tableName;
- this.properties = properties.toArray(new Property[properties.size()]);
- }
-
- public Property[] getProperties() {
- return properties;
- }
-
- public String getTableName() {
- return tableName;
- }
+ private Property[] properties;
+ private String tableName;
+
+ public PropertyCollection(String tableName, Property[] properties) {
+ this.tableName = tableName;
+ this.properties = properties;
+ }
+
+ public PropertyCollection(String tableName, java.util.List properties) {
+ this.tableName = tableName;
+ this.properties = properties.toArray(new Property[properties.size()]);
+ }
+
+ public Property[] getProperties() {
+ return properties;
+ }
+
+ public String getTableName() {
+ return tableName;
+ }
}
diff --git a/source/java/src/org/lucee/extension/orm/hibernate/HibernateCaster.java b/source/java/src/org/lucee/extension/orm/hibernate/HibernateCaster.java
index 208ba0c3..41720ce3 100755
--- a/source/java/src/org/lucee/extension/orm/hibernate/HibernateCaster.java
+++ b/source/java/src/org/lucee/extension/orm/hibernate/HibernateCaster.java
@@ -12,6 +12,9 @@
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.Type;
+import org.lucee.extension.orm.hibernate.util.CommonUtil;
+import org.lucee.extension.orm.hibernate.util.ExceptionUtil;
+import org.lucee.extension.orm.hibernate.util.HibernateUtil;
import lucee.commons.lang.types.RefBoolean;
import lucee.loader.engine.CFMLEngineFactory;
@@ -31,591 +34,676 @@
public class HibernateCaster {
- private static final int NULL = -178696;
-
- public static Object toCFML(Object src) {
- if (src == null) return null;
- if (src instanceof Collection) return src;
-
- if (src instanceof List) {
- return toCFML((List) src);
- }
- /*
- * if(src instanceof Map){ return toCFML(pc,(Map) src); }
- */
- return src;
- }
-
- public static Array toCFML(List src) {
- int size = src.size();
-
- Array trg = CommonUtil.createArray();
- for (int i = 0; i < size; i++) {
- trg.setEL(i + 1, toCFML(src.get(i)));
- }
- return trg;
- }
-
- /*
- * public static Object toCFML(PageContext pc,Map src) throws PageException {
- *
- * Object type =src.remove("$type$"); if(type instanceof String){
- *
- * Component cfc = toComponent(pc, (String)type); return toCFML(pc,src, cfc); }
- *
- *
- * Iterator> it = src.entrySet().iterator(); Struct
- * trg=CommonUtil.createStruct(); Map.Entry entry; while(it.hasNext()){
- * entry=it.next(); trg.setEL(entry.getKey(),toCFML(pc,entry.getValue())); } return trg; }
- */
-
- public static String getEntityName(Component cfc) {
-
- String name = null;
- try {
- name = CommonUtil.toString(cfc.getMetaStructItem(CommonUtil.ENTITY_NAME), null);
- }
- catch (Throwable t) {
- if (t instanceof ThreadDeath) throw (ThreadDeath) t;
- try {
- Struct md = cfc.getMetaData(CommonUtil.pc());
- name = CommonUtil.toString(md.get(CommonUtil.ENTITY_NAME), null);
-
- }
- catch (PageException e) {}
- }
-
- if (!Util.isEmpty(name)) {
- return name;
- }
- return getName(cfc);
-
- }
-
- private static String getName(Component cfc) {
- String name = null;
- // MUSTMUST cfc.getName() should return the real case, this should not be needed
- name = cfc.getPageSource().getDisplayPath();
- name = CommonUtil.last(name, "\\/");
- int index = name.lastIndexOf('.');
- name = name.substring(0, index);
- return name;
- }
-
- public static int cascade(ORMSession session, String cascade) throws PageException {
- int c = cascade(cascade, -1);
- if (c != -1) return c;
- throw ExceptionUtil.createException(session, null,
- "invalid cascade defintion [" + cascade + "], valid values are [all,all-delete-orphan,delete,delete-orphan,refresh,save-update]", null);
- }
-
- public static int cascade(String cascade, int defaultValue) {
- cascade = cascade.trim().toLowerCase();
- if ("all".equals(cascade)) return HibernateConstants.CASCADE_ALL;
-
- if ("save-update".equals(cascade)) return HibernateConstants.CASCADE_SAVE_UPDATE;
- if ("save_update".equals(cascade)) return HibernateConstants.CASCADE_SAVE_UPDATE;
- if ("saveupdate".equals(cascade)) return HibernateConstants.CASCADE_SAVE_UPDATE;
-
- if ("delete".equals(cascade)) return HibernateConstants.CASCADE_DELETE;
-
- if ("delete-orphan".equals(cascade)) return HibernateConstants.CASCADE_DELETE_ORPHAN;
- if ("delete_orphan".equals(cascade)) return HibernateConstants.CASCADE_DELETE_ORPHAN;
- if ("deleteorphan".equals(cascade)) return HibernateConstants.CASCADE_DELETE_ORPHAN;
-
- if ("all-delete-orphan".equals(cascade)) return HibernateConstants.CASCADE_ALL_DELETE_ORPHAN;
- if ("all_delete_orphan".equals(cascade)) return HibernateConstants.CASCADE_ALL_DELETE_ORPHAN;
- if ("alldeleteorphan".equals(cascade)) return HibernateConstants.CASCADE_ALL_DELETE_ORPHAN;
-
- if ("refresh".equals(cascade)) return HibernateConstants.REFRESH;
-
- return defaultValue;
- }
-
- public static int collectionType(ORMSession session, String strCollectionType) throws PageException {
- int ct = collectionType(strCollectionType, -1);
- if (ct != -1) return ct;
- throw ExceptionUtil.createException(session, null, "invalid collectionType defintion [" + strCollectionType + "], valid values are [array,struct]", null);
- }
-
- public static int collectionType(String strCollectionType, int defaultValue) {
- strCollectionType = strCollectionType.trim().toLowerCase();
- if ("struct".equals(strCollectionType)) return HibernateConstants.COLLECTION_TYPE_STRUCT;
- if ("array".equals(strCollectionType)) return HibernateConstants.COLLECTION_TYPE_ARRAY;
-
- return defaultValue;
- }
-
- public static String toHibernateType(ColumnInfo info, String type, String defaultValue) {
-
- // no type defined
- if (Util.isEmpty(type, true)) {
- return HibernateCaster.toHibernateType(info, defaultValue);
- }
-
- // type defined
- String tmp = HibernateCaster.toHibernateType(type, null);
- if (tmp != null) return tmp;
-
- if (info != null) {
- tmp = HibernateCaster.toHibernateType(info, defaultValue);
- return tmp;
- }
- return defaultValue;
-
- }
-
- public static int toSQLType(String type, int defaultValue) {
- type = type.trim().toLowerCase();
- type = toHibernateType(type, type);
- if ("long".equals(type)) return Types.BIGINT;
- if ("binary".equals(type)) return Types.BINARY;
- if ("boolean".equals(type)) return Types.BIT;
- if ("blob".equals(type)) return Types.BLOB;
- if ("boolean".equals(type)) return Types.BOOLEAN;
- if ("character".equals(type)) return Types.CHAR;
- if ("clob".equals(type)) return Types.CLOB;
- if ("date".equals(type)) return Types.DATE;
- if ("big_decimal".equals(type)) return Types.DECIMAL;
- if ("big_integer".equals(type)) return Types.NUMERIC;
- if ("double".equals(type)) return Types.DOUBLE;
- if ("float".equals(type)) return Types.FLOAT;
- if ("integer".equals(type)) return Types.INTEGER;
- if ("binary".equals(type)) return Types.VARBINARY;
- if ("string".equals(type)) return Types.VARCHAR;
- if ("short".equals(type)) return Types.SMALLINT;
- if ("time".equals(type)) return Types.TIME;
- if ("timestamp".equals(type)) return Types.TIMESTAMP;
- if ("byte".equals(type)) return Types.TINYINT;
-
- return defaultValue;
- }
-
- public static String toHibernateType(ColumnInfo info, String defaultValue) {
- if (info == null) return defaultValue;
-
- String rtn = toHibernateType(info.getType(), info.getSize(), null);
- if (rtn != null) return rtn;
- return toHibernateType(info.getTypeName(), defaultValue);
- }
-
- public static String toHibernateType(int type, int size, String defaultValue) {
- // MUST do better
- switch (type) {
- case Types.ARRAY:
- return "";
- case Types.BIGINT:
- return "long";
- case Types.BINARY:
- return "binary";
- case Types.BIT:
- return "boolean";
- case Types.BLOB:
- return "blob";
- case Types.BOOLEAN:
- return "boolean";
- case Types.CHAR:
- return "string";
- // if(size>1) return "string";
- // return "character";
- case Types.CLOB:
- return "clob";
- // case Types.DATALINK: return "";
- case Types.DATE:
- return "date";
- case Types.DECIMAL:
- return "big_decimal";
- // case Types.DISTINCT: return "";
- case Types.DOUBLE:
- return "double";
- case Types.FLOAT:
- return "float";
- case Types.INTEGER:
- return "integer";
- // case Types.JAVA_OBJECT: return "";
- case Types.LONGVARBINARY:
- return "binary";
- case Types.LONGVARCHAR:
- return "string";
- // case Types.NULL: return "";
- case Types.NUMERIC:
- return "big_decimal";
- // case Types.OTHER: return "";
- // case Types.REAL: return "";
- // case Types.REF: return "";
- case Types.SMALLINT:
- return "short";
- // case Types.STRUCT: return "";
- case Types.TIME:
- return "time";
- case Types.TIMESTAMP:
- return "timestamp";
- case Types.TINYINT:
- return "byte";
- case Types.VARBINARY:
- return "binary";
- case Types.NVARCHAR:
- return "string";
- case Types.VARCHAR:
- return "string";
- }
- return defaultValue;
- }
-
- public static String toHibernateType(ORMSession session, String type) throws PageException {
- String res = toHibernateType(type, null);
- if (res == null) throw ExceptionUtil.createException(session, null, "the type [" + type + "] is not supported", null);
- return res;
- }
-
- // calendar_date: A type mapping for a Calendar object that represents a date
- // calendar: A type mapping for a Calendar object that represents a datetime.
- public static String toHibernateType(String type, String defaultValue) {
- type = type.trim().toLowerCase();
- type = Util.replace(type, "java.lang.", "", true);
- type = Util.replace(type, "java.util.", "", true);
- type = Util.replace(type, "java.sql.", "", true);
-
- // return same value
- if ("long".equals(type)) return type;
- if ("binary".equals(type)) return type;
- if ("boolean".equals(type)) return type;
- if ("blob".equals(type)) return "binary";
- if ("boolean".equals(type)) return type;
- if ("character".equals(type)) return type;
- if ("clob".equals(type)) return "text";
- if ("date".equals(type)) return type;
- if ("big_decimal".equals(type)) return type;
- if ("double".equals(type)) return type;
- if ("float".equals(type)) return type;
- if ("integer".equals(type)) return type;
- if ("binary".equals(type)) return type;
- if ("string".equals(type)) return type;
- if ("big_integer".equals(type)) return type;
- if ("short".equals(type)) return type;
- if ("time".equals(type)) return type;
- if ("timestamp".equals(type)) return type;
- if ("byte".equals(type)) return type;
- if ("binary".equals(type)) return type;
- if ("string".equals(type)) return type;
- if ("text".equals(type)) return type;
- if ("calendar".equals(type)) return type;
- if ("calendar_date".equals(type)) return type;
- if ("locale".equals(type)) return type;
- if ("timezone".equals(type)) return type;
- if ("currency".equals(type)) return type;
-
- if ("imm_date".equals(type)) return type;
- if ("imm_time".equals(type)) return type;
- if ("imm_timestamp".equals(type)) return type;
- if ("imm_calendar".equals(type)) return type;
- if ("imm_calendar_date".equals(type)) return type;
- if ("imm_serializable".equals(type)) return type;
- if ("imm_binary".equals(type)) return type;
-
- // return different value
- if ("bigint".equals(type)) return "long";
- if ("bit".equals(type)) return "boolean";
-
- if ("int".equals(type)) return "integer";
- if ("char".equals(type)) return "character";
-
- if ("bool".equals(type)) return "boolean";
- if ("yes-no".equals(type)) return "yes_no";
- if ("yesno".equals(type)) return "yes_no";
- if ("yes_no".equals(type)) return "yes_no";
- if ("true-false".equals(type)) return "true_false";
- if ("truefalse".equals(type)) return "true_false";
- if ("true_false".equals(type)) return "true_false";
- if ("varchar".equals(type)) return "string";
- if ("big-decimal".equals(type)) return "big_decimal";
- if ("bigdecimal".equals(type)) return "big_decimal";
- if ("java.math.bigdecimal".equals(type)) return "big_decimal";
- if ("big-integer".equals(type)) return "big_integer";
- if ("biginteger".equals(type)) return "big_integer";
- if ("bigint".equals(type)) return "big_integer";
- if ("java.math.biginteger".equals(type)) return "big_integer";
- if ("byte[]".equals(type)) return "binary";
- if ("serializable".equals(type)) return "serializable";
-
- if ("datetime".equals(type)) return "timestamp";
- if ("numeric".equals(type)) return "double";
- if ("number".equals(type)) return "double";
- if ("numeric".equals(type)) return "double";
- if ("char".equals(type)) return "character";
- if ("nchar".equals(type)) return "character";
- if ("decimal".equals(type)) return "double";
- if ("eurodate".equals(type)) return "timestamp";
- if ("usdate".equals(type)) return "timestamp";
- if ("int".equals(type)) return "integer";
- if ("varchar".equals(type)) return "string";
- if ("nvarchar".equals(type)) return "string";
-
- return defaultValue;
-
- // FUTURE
- /*
- *
- * add support for - any, object,other
- *
- * add support for custom types https://issues.jboss.org/browse/RAILO-1341 - array - base64 - guid -
- * memory - node, xml - query - struct - uuid - variablename, variable_name - variablestring,
- * variable_string
- *
- */
-
- }
-
- public static Object toHibernateValue(PageContext pc, Object value, String type) throws PageException {
- type = toHibernateType(type, null);
- // return same value
- if ("long".equals(type)) return CommonUtil.toLong(value);
- if ("binary".equals(type) || "imm_binary".equals(type)) return CommonUtil.toBinary(value);
- if ("boolean".equals(type) || "yes_no".equals(type) || "true_false".equals(type)) return CommonUtil.toBoolean(value);
- if ("character".equals(type)) return CommonUtil.toCharacter(value);
- if ("date".equals(type) || "imm_date".equals(type)) return CommonUtil.toDate(value, pc.getTimeZone());
- if ("big_decimal".equals(type)) return CommonUtil.toBigDecimal(value);
- if ("double".equals(type)) return CommonUtil.toDouble(value);
- if ("float".equals(type)) return CommonUtil.toFloat(value);
- if ("integer".equals(type)) return CommonUtil.toInteger(value);
- if ("string".equals(type)) return CommonUtil.toString(value);
- if ("big_integer".equals(type)) return new BigInteger(CommonUtil.toString(value));
- if ("short".equals(type)) return CommonUtil.toShort(value);
- if ("time".equals(type) || "imm_time".equals(type)) return new Time(CommonUtil.toDate(value, pc.getTimeZone()).getTime());
- if ("timestamp".equals(type) || "imm_timestamp".equals(type)) return new Timestamp(CommonUtil.toDate(value, pc.getTimeZone()).getTime());
- if ("byte".equals(type)) return CommonUtil.toBinary(value);
- if ("text".equals(type)) return CommonUtil.toString(value);
- if ("calendar".equals(type) || "calendar_date".equals(type) || "imm_calendar".equals(type) || "imm_calendar_date".equals(type))
- return CommonUtil.toCalendar(CommonUtil.toDate(value, pc.getTimeZone()), pc.getTimeZone(), pc.getLocale());
- if ("locale".equals(type)) return CommonUtil.toLocale(CommonUtil.toString(value));
- if ("timezone".equals(type)) return CommonUtil.toTimeZone(value, null);
- if ("currency".equals(type)) return value;
-
- if ("imm_serializable".equals(type)) return value;
- if ("serializable".equals(type)) return "serializable";
-
- return value;
- }
-
- /**
- * translate CFMl specific types to Hibernate/SQL specific types
- *
- * @param engine
- * @param ci
- * @param value
- * @return
- * @throws PageException
- */
- public static Object toSQL(ColumnInfo ci, Object value, RefBoolean isArray) throws PageException {
- return toSQL(ci.getType(), value, isArray);
- }
-
- /**
- * translate CFMl specific types to Hibernate/SQL specific types
- *
- * @param engine
- * @param type
- * @param value
- * @return
- * @throws PageException
- */
- public static Object toSQL(Type type, Object value, RefBoolean isArray) throws PageException {
- int t = toSQLType(type.getName(), Types.OTHER);
- // if(t==Types.OTHER) return value;
- return toSQL(t, value, isArray);
- }
-
- /**
- * translate CFMl specific type to SQL specific types
- *
- * @param engine
- * @param sqlType
- * @param value
- * @return
- * @throws PageException
- */
- private static Object toSQL(int sqlType, Object value, RefBoolean isArray) throws PageException {
- if (sqlType == Types.OTHER && value instanceof PersistentCollection) {
- return value;
- }
-
- if (isArray != null) isArray.setValue(false);
-
- Boolean _isArray = null;
- boolean hasType = sqlType != Types.OTHER;
-
- // first we try to convert without any checking
- if (hasType) {
- try {
- return CommonUtil.toSqlType(CommonUtil.toSQLItem(value, sqlType));
- }
- catch (PageException pe) {
- _isArray = CommonUtil.isArray(value);
- if (!_isArray.booleanValue()) throw pe;
- }
- }
-
- // already a hibernate type
-
- // can only be null if type is other
- if (_isArray == null) {
- if (!CommonUtil.isArray(value)) return value;
- }
-
- // at this point it is for sure that the value is an array
- if (isArray != null) isArray.setValue(true);
- Array src = CommonUtil.toArray(value);
- Iterator