diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml
index bf786c32eb7..4e5aa5ec1aa 100644
--- a/.github/workflows/build-linux.yml
+++ b/.github/workflows/build-linux.yml
@@ -24,7 +24,7 @@ jobs:
- name: Build with Maven
# qa skips documentation - we check it on Jenkins CI
# We skip checkstyle too - we check it on Jenkins CI
- run: mvn -B -e -ntp install -Pqa '-Dcheckstyle.skip=true'
+ run: mvn -B -e -ntp install -Pqa,snapshots '-Dcheckstyle.skip=true'
- name: Upload server logs
uses: actions/upload-artifact@v4
if: failure()
diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml
index d831f076e77..f02f1f68631 100644
--- a/.github/workflows/build-macos.yml
+++ b/.github/workflows/build-macos.yml
@@ -22,9 +22,9 @@ jobs:
- name: Build with Maven
# qa skips documentation - we check it on Jenkins CI
# We skip checkstyle too - we check it on Jenkins CI
- run: mvn -B -e -ntp install -Pqa '-Dcheckstyle.skip=true' -Pfastest
+ run: mvn -B -e -ntp install -Pqa,snapshots '-Dcheckstyle.skip=true' -Pfastest
- name: Test GF Starts
- run: mvn -B -e -ntp install '-Dcheckstyle.skip=true' -pl :glassfish-itest-tools
+ run: mvn -B -e -ntp install -Psnapshots '-Dcheckstyle.skip=true' -pl :glassfish-itest-tools
- name: Upload server logs
uses: actions/upload-artifact@v4
if: failure()
diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml
index 973aaae8be8..5e5c35d8999 100644
--- a/.github/workflows/build-windows.yml
+++ b/.github/workflows/build-windows.yml
@@ -22,7 +22,7 @@ jobs:
- name: Build with Maven
# qa skips documentation - we check it on Jenkins CI
# We skip checkstyle too - we check it on Jenkins CI
- run: mvn -B -e -ntp install -Pqa '-Dcheckstyle.skip=true'
+ run: mvn -B -e -ntp install '-Pqa,snapshots' '-Dcheckstyle.skip=true'
- name: Upload server logs
uses: actions/upload-artifact@v4
if: failure()
diff --git a/Jenkinsfile b/Jenkinsfile
index c038c05d823..84ecf99e55d 100644
--- a/Jenkinsfile
+++ b/Jenkinsfile
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2022, 2025 Contributors to the Eclipse Foundation
+* Copyright (c) 2022, 2026 Contributors to the Eclipse Foundation
* Copyright (c) 2018, 2021 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -329,10 +329,10 @@ pipeline {
timeout(time: 1, unit: 'HOURS') {
sh '''
# Validate the structure in all submodules (especially version ids)
- mvn -V -B -e -fae clean validate -Ptck,set-version-id
+ mvn -V -B -e -fae clean validate -Ptck,set-version-id,snapshots
'''
sh '''
- mvn -B -e install -Pfastest,ci -T4C
+ mvn -B -e install -Pfastest,ci,snapshots -T4C
'''
sh '''
mvn -B -e clean
@@ -378,7 +378,7 @@ pipeline {
dumpSysInfo()
timeout(time: 4, unit: 'HOURS') {
sh '''
- mvn -B -e clean verify -Pqa,ci,ci-main-tests
+ mvn -B -e clean verify -Pqa,ci,ci-main-tests,snapshots
'''
}
} finally {
diff --git a/appserver/admin/backup/src/main/java/com/sun/enterprise/backup/StringHelper.java b/appserver/admin/backup/src/main/java/com/sun/enterprise/backup/StringHelper.java
index ca3926496c8..b941c665345 100644
--- a/appserver/admin/backup/src/main/java/com/sun/enterprise/backup/StringHelper.java
+++ b/appserver/admin/backup/src/main/java/com/sun/enterprise/backup/StringHelper.java
@@ -50,7 +50,7 @@ static String get(String s)
* Convenience method which calls get(String, Object[])
* @return the String from LocalStrings or the supplied String if it doesn't exist --
* using the one supplied argument
- * @see get(String, Object[])
+ * @see #get(String, Object[])
*/
static String get(String s, Object o)
{
@@ -61,7 +61,7 @@ static String get(String s, Object o)
* Convenience method which calls get(String, Object[])
* @return the String from LocalStrings or the supplied String if it doesn't exist --
* using the two supplied arguments
- * @see get(String, Object[])
+ * @see #get(String, Object[])
*/
static String get(String s, Object o1, Object o2)
{
@@ -72,7 +72,7 @@ static String get(String s, Object o1, Object o2)
* Convenience method which calls get(String, Object[])
* @return the String from LocalStrings or the supplied String if it doesn't exist --
* using the three supplied arguments
- * @see get(String, Object[])
+ * @see #get(String, Object[])
*/
static String get(String s, Object o1, Object o2, Object o3)
{
diff --git a/appserver/admingui/common/src/main/help/en/help/idx-3.html b/appserver/admingui/common/src/main/help/en/help/idx-3.html
index 656cf1a279c..1984a5ce1be 100644
--- a/appserver/admingui/common/src/main/help/en/help/idx-3.html
+++ b/appserver/admingui/common/src/main/help/en/help/idx-3.html
@@ -1,5 +1,6 @@
-
-
-
- Properties Specific to the SolarisRealm Class
-
-The following property is required for a Solaris realm.
-
-JAAS Context
-
-The JAAS (Java Authentication and Authorization Service) context (the identifier for the login module to use for this realm). The only valid value is solarisRealm.
-
-
-The following optional property is available for a Solaris realm.
-
-Assign Groups
-
-A comma-separated list of group names. All clients who present valid certificates are assigned to these groups, for example, employee,manager, where these are the names of user groups.
-
-
-
-
-Copyright © 2005, 2017, Oracle and/or its affiliates. All rights reserved. Legal Notices
diff --git a/appserver/admingui/common/src/main/help/en/help/task-realmedit.html b/appserver/admingui/common/src/main/help/en/help/task-realmedit.html
index 376e8cc3c6c..560fecc92ac 100644
--- a/appserver/admingui/common/src/main/help/en/help/task-realmedit.html
+++ b/appserver/admingui/common/src/main/help/en/help/task-realmedit.html
@@ -1,5 +1,6 @@
org.glassfish.external
- ant
+ ant-osgi
true
diff --git a/appserver/featuresets/embedded-all/pom.xml b/appserver/featuresets/embedded-all/pom.xml
index 362efee67be..7df74861439 100644
--- a/appserver/featuresets/embedded-all/pom.xml
+++ b/appserver/featuresets/embedded-all/pom.xml
@@ -185,7 +185,7 @@
org.glassfish.external
- dbschema
+ dbschema-osgi
diff --git a/appserver/featuresets/embedded-web/pom.xml b/appserver/featuresets/embedded-web/pom.xml
index 5f579342e21..89be09c9cc8 100644
--- a/appserver/featuresets/embedded-web/pom.xml
+++ b/appserver/featuresets/embedded-web/pom.xml
@@ -1,7 +1,7 @@
-
- jakarta.inject
- jakarta.inject-api
-
org.glassfish.hk2.external
aopalliance-repackaged
@@ -126,564 +120,547 @@
- org.glassfish.hk2
- osgi-adapter
+ org.hibernate.validator
+ hibernate-validator
-
-
-
- jakarta.cdi
- jakarta.cdi-api
+ org.hibernate.validator
+ hibernate-validator-cdi
- jakarta.cdi
- jakarta.cdi-lang-model-api
+ org.javassist
+ javassist
- jakarta.interceptor
- jakarta.interceptor-api
+ jakarta.inject
+ jakarta.inject-api
- org.jboss.weld
- weld-osgi-bundle
+ org.jboss.logging
+ jboss-logging
+
+
+ com.fasterxml
+ classmate
+
+
+
+ org.glassfish.main.grizzly
+ nucleus-grizzly-all
+ ${project.version}
+
+
+
+ org.glassfish.main.grizzly
+ glassfish-grizzly-extra-all
+ ${project.version}
+
+
+
+ org.glassfish.main.admin
+ admin-cli
+ ${project.version}
+
- org.jboss.jdeparser
- jdeparser
+ com.sun.xml.bind
+ jaxb-osgi
- org.jboss.logging
- jboss-logging-processor
+ com.github.mwiede
+ jsch
+
+
+ org.glassfish.main.cluster
+ cluster-common
- org.jboss.classfilewriter
- jboss-classfilewriter
-
-
- org.glassfish.main.web
- cdi-api-fragment
+ org.glassfish.main.admin
+ admin-util
${project.version}
+
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
- org.glassfish.main.web
- gf-weld-connector
+ org.glassfish.main.common
+ common-util
${project.version}
- org.glassfish.main.web
- weld-integration
+ org.glassfish.main.common
+ glassfish-jdk-extensions
${project.version}
- org.glassfish.main.web
- weld-integration-fragment
+ org.glassfish.main.admin
+ config-api
${project.version}
- org.javassist
- javassist
+ org.glassfish.main.hk2
+ config-types
+ ${project.version}
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
- org.jboss.logging
- jboss-logging
+ org.glassfish.main.deployment
+ deployment-admin
+ ${project.version}
-
-
-
- jakarta.ws.rs
- jakarta.ws.rs-api
+ org.glassfish.main.deployment
+ deployment-autodeploy
+ ${project.version}
- org.glassfish.jersey.media
- jersey-media-moxy
+ org.glassfish.main.deployment
+ deployment-common
+ ${project.version}
- org.glassfish.jersey.ext.cdi
- jersey-cdi1x
+ org.glassfish.gmbal
+ gmbal
- org.glassfish.jersey.ext.cdi
- jersey-cdi1x-servlet
+ org.glassfish.gmbal
+ gmbal-api-only
- org.glassfish.jersey.ext.cdi
- jersey-cdi1x-transaction
+ org.glassfish.main.common
+ internal-api
+ ${project.version}
- org.glassfish.jersey.containers
- jersey-container-servlet
+ org.glassfish.main.common
+ glassfish-api
+ ${project.version}
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
- org.glassfish.jersey.media
- jersey-media-json-processing
+ org.glassfish.main.admin
+ launcher
+ ${project.version}
- org.glassfish.jersey.ext
- jersey-mvc
+ org.glassfish.main.core
+ logging
+ ${project.version}
- org.glassfish.jersey.ext
- jersey-mvc-jsp
+ org.glassfish.main.common
+ scattered-archive-api
+ ${project.version}
- org.glassfish.jersey.core
- jersey-server
+ org.glassfish.main.common
+ simple-glassfish-api
+ ${project.version}
- org.glassfish.jersey.core
- jersey-client
+ org.glassfish.external
+ management-api
- org.glassfish.jersey.containers
- jersey-container-grizzly2-http
+ org.glassfish.main.flashlight
+ flashlight-framework
+ ${project.version}
- org.glassfish.jersey.media
- jersey-media-jaxb
+ org.glassfish.main.flashlight
+ flashlight-agent
+ ${project.version}
- org.glassfish.jersey.media
- jersey-media-json-jettison
+ org.glassfish.main.flashlight
+ flashlight-extra-jdk-packages
+ ${project.version}
- org.glassfish.jersey.media
- jersey-media-json-jackson
+ org.glassfish.main.admin
+ server-mgmt
+ ${project.version}
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
+ org.glassfish.annotations
+ logging-annotation-processor
+
+
- org.glassfish.jersey.media
- jersey-media-sse
+ org.glassfish.main.core
+ kernel
+ ${project.version}
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
- org.glassfish.jersey.media
- jersey-media-multipart
+ org.glassfish.main.core
+ glassfish
+ ${project.version}
- org.glassfish.jersey.ext
- jersey-bean-validation
+ org.glassfish.main.core
+ glassfish-osgi-bootstrap
+ ${project.version}
- org.glassfish.jersey.ext
- jersey-entity-filtering
+ org.glassfish.main.core
+ api-exporter
+ ${project.version}
- org.glassfish.jersey.core
- jersey-common
+ org.glassfish.hk2
+ osgi-adapter
- org.glassfish.jersey.inject
- jersey-hk2
+ org.glassfish.main.security
+ security
+ ${project.version}
- org.glassfish.jersey.media
- jersey-media-json-binding
+ org.glassfish.main.security
+ security-services
+ ${project.version}
- com.fasterxml.jackson.core
- jackson-core
+ org.glassfish.main.security
+ ssl-impl
+ ${project.version}
- com.fasterxml.jackson.core
- jackson-databind
+ org.jvnet.mimepull
+ mimepull
- com.fasterxml.jackson.core
- jackson-annotations
+ jakarta.annotation
+ jakarta.annotation-api
+
- com.fasterxml.jackson.module
- jackson-module-jakarta-xmlbind-annotations
-
-
- *
- *
-
-
+ org.glassfish.main.common
+ glassfish-naming
+ ${project.version}
- org.codehaus.jettison
- jettison
+ org.glassfish.main.deployment
+ nucleus-dtds
+ ${project.version}
+ zip
-
-
-
- jakarta.json
- jakarta.json-api
+ org.glassfish.main.deployment
+ nucleus-schemas
+ ${project.version}
+ zip
- org.eclipse.parsson
- parsson
+ org.glassfish.main.admin
+ monitoring-core
+ ${project.version}
- org.eclipse.parsson
- parsson-media
+ org.glassfish.main.cluster
+ gms-bootstrap
+ ${project.version}
+
+
- jakarta.json.bind
- jakarta.json.bind-api
+ org.glassfish.main.admin
+ gf-restadmin-connector
+ ${project.version}
-
-
-
- jakarta.validation
- jakarta.validation-api
+ org.glassfish.main.admin
+ rest-client
+ ${project.version}
- org.hibernate.validator
- hibernate-validator
+ org.glassfish.main.admin
+ rest-service
+ ${project.version}
+
+
+ com.sun.xml.bind
+ jaxb-osgi
+
+
+
- org.hibernate.validator
- hibernate-validator-cdi
+ org.glassfish.main.security
+ security-ee
+ ${project.version}
-
-
-
- jakarta.transaction
- jakarta.transaction-api
+ org.glassfish.main.common
+ amx-jakartaee
+ ${project.version}
+
+
+ org.glassfish.main.common
+ amx-core
+
+
- org.glassfish.main.transaction
- jta
+ org.glassfish.main.common
+ annotation-framework
${project.version}
+
+
+ org.glassfish.annotations
+ logging-annotation-processor
+
+
- org.glassfish.main.transaction
- jts
+ org.glassfish.main.common
+ container-common
${project.version}
- org.glassfish.main.transaction
- transaction-internal-api
+ org.glassfish.main.deployment
+ dol
${project.version}
+
+
+ org.glassfish.annotations
+ logging-annotation-processor
+
+
-
-
-
- jakarta.persistence
- jakarta.persistence-api
+ org.glassfish.main.deployment
+ deployment-jakartaee-core
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.asm
+ org.glassfish.main.deployment
+ appserver-dtds
+ ${project.version}
+ zip
- org.eclipse.persistence
- org.eclipse.persistence.core
+ org.glassfish.main.deployment
+ appserver-schemas
+ ${project.version}
+ zip
- org.eclipse.persistence
- org.eclipse.persistence.jpa
+ org.glassfish.main.admin
+ appserver-cli
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.jpa.jpql
+ org.glassfish.main.admin
+ cli-optional
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.jpa.modelgen.processor
+ org.glassfish.main.admin
+ admin-core
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.moxy
+ org.glassfish.main.ejb
+ ejb-internal-api
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.dbws
+ org.glassfish.main.connectors
+ connectors-internal-api
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.oracle
+ org.glassfish.main.orb
+ orb-connector
+ ${project.version}
- org.eclipse.persistence
- org.eclipse.persistence.json
+ org.glassfish.corba
+ glassfish-corba-orb
+
+
+ org.glassfish.main.orb
+ orb-enabler
- org.glassfish.main.persistence
- gf-jpa-connector
- ${project.version}
+ org.glassfish.ha
+ ha-api
- org.glassfish.main.persistence
- glassfish-oracle-jdbc-driver-packages
+ org.glassfish.main.ha
+ ha-file-store
${project.version}
- org.glassfish.main.persistence
- jpa-container
+ org.glassfish.main.loadbalancer
+ load-balancer-admin
${project.version}
- org.glassfish.main.persistence
- persistence-common
- ${project.version}
+ org.glassfish.shoal
+ shoal-cache
-
-
-
- jakarta.servlet
- jakarta.servlet-api
+ org.glassfish.external
+ schema2beans-osgi
- org.glassfish.main.web
- gf-web-connector
+ org.glassfish.main.extras
+ jakartaee-frag
${project.version}
+ zip
- org.glassfish.main.web
- jsf-connector
+ org.glassfish.main.extras
+ appserv-rt-frag
${project.version}
+ zip
- org.glassfish.main.web
- jspcaching-connector
+ org.glassfish.main.extras
+ glassfish-embedded-shell-frag
${project.version}
+ zip
+
+
+ org.glassfish.metro
+ webservices-api-osgi
+
+
+ org.glassfish.main.extras
+ glassfish-embedded-shell
+
+
- org.glassfish.main.web
- jstl-connector
+ org.glassfish.main.extras
+ glassfish-embedded-static-shell-frag
${project.version}
+ zip
+
+
+ com.fasterxml.woodstox
+ woodstox-core
+
+
+ org.glassfish.main.extras
+ glassfish-embedded-static-shell
+
+
- org.glassfish.main.web
- jersey-ejb-component-provider
+ org.glassfish.main.admin
+ backup
${project.version}
- org.glassfish.main.web
- jersey-mvc-connector
+ org.glassfish.main.loadbalancer
+ gf-load-balancer-connector
${project.version}
- org.glassfish.main.common
- stats77
+ org.glassfish.main.libpam4j
+ libpam4j
${project.version}
- org.glassfish.main.web
- web-cli
+ org.glassfish.main.resourcebase.resources
+ nucleus-resources
${project.version}
- org.glassfish.main.web
- web-core
+ org.glassfish.main.resources
+ resources-connector
${project.version}
- org.glassfish.main.web
- web-embed-api
- ${project.version}
+ jakarta.resource
+ jakarta.resource-api
- org.glassfish.main.web
- web-glue
- ${project.version}
+ jakarta.authentication
+ jakarta.authentication-api
- org.glassfish.main.web
- web-gui-plugin-common
- ${project.version}
+ jakarta.authorization
+ jakarta.authorization-api
- org.glassfish.main.web
- web-ha
+ org.glassfish.main.transaction
+ transaction-internal-api
${project.version}
- org.glassfish.main.web
- web-naming
- ${project.version}
+ jakarta.mail
+ jakarta.mail-api
- org.glassfish.main.web
- web-sse
- ${project.version}
-
-
- org.glassfish.main.web
- war-util
- ${project.version}
-
-
-
-
- org.glassfish.mojarra
- mojarra
-
-
-
-
-
- jakarta.servlet.jsp
- jakarta.servlet.jsp-api
-
-
- jakarta.servlet.jsp.jstl
- jakarta.servlet.jsp.jstl-api
-
-
- org.glassfish.wasp
- wasp
-
-
-
-
-
- jakarta.el
- jakarta.el-api
-
-
- org.glassfish.expressly
- expressly
-
-
-
-
-
- jakarta.websocket
- jakarta.websocket-api
-
-
- jakarta.websocket
- jakarta.websocket-client-api
-
-
- org.glassfish.tyrus
- tyrus-core
-
-
- org.glassfish.tyrus
- tyrus-server
-
-
- org.glassfish.tyrus
- tyrus-spi
-
-
- org.glassfish.tyrus
- tyrus-client
-
-
- org.glassfish.tyrus
- tyrus-container-servlet
-
-
- org.glassfish.tyrus
- tyrus-container-grizzly-client
-
-
- org.glassfish.tyrus
- tyrus-container-glassfish-cdi
-
-
- jakarta.enterprise
- jakarta.enterprise.cdi-api
-
-
-
-
- org.glassfish.tyrus
- tyrus-container-glassfish-ejb
-
-
-
-
-
- jakarta.security.enterprise
- jakarta.security.enterprise-api
-
-
- jakarta.authentication
- jakarta.authentication-api
-
-
- jakarta.authorization
- jakarta.authorization-api
-
-
- org.glassfish.soteria
- soteria
-
-
- org.glassfish.exousia
- exousia
-
-
- com.nimbusds
- nimbus-jose-jwt
-
-
- org.glassfish.epicyro
- epicyro
-
-
- org.glassfish.main.security
- websecurity
- ${project.version}
-
-
- org.glassfish.annotations
- logging-annotation-processor
-
-
-
-
- org.glassfish.main.security
- security-ee
- ${project.version}
+ org.eclipse.angus
+ angus-mail
- org.glassfish.main.security
- security
- ${project.version}
+ jakarta.activation
+ jakarta.activation-api
- org.glassfish.main.security
- security-services
- ${project.version}
+ org.eclipse.angus
+ angus-activation
- org.glassfish.main.security
- ssl-impl
- ${project.version}
+ jakarta.validation
+ jakarta.validation-api
-
-
-
- jakarta.mail
- jakarta.mail-api
+ jakarta.servlet
+ jakarta.servlet-api
- jakarta.activation
- jakarta.activation-api
+ jakarta.persistence
+ jakarta.persistence-api
- org.eclipse.angus
- angus-mail
+ jakarta.ejb
+ jakarta.ejb-api
- org.eclipse.angus
- angus-activation
+ jakarta.interceptor
+ jakarta.interceptor-api
-
-
-
- jakarta.resource
- jakarta.resource-api
+ jakarta.transaction
+ jakarta.transaction-api
+
org.glassfish.main.connectors
descriptors
@@ -741,42 +718,91 @@
${project.version}
- org.glassfish.main.resources
- resources-connector
+ org.glassfish.main.connectors
+ work-management
${project.version}
+
- org.glassfish.main.connectors
- work-management
+ org.glassfish.main.persistence
+ gf-jpa-connector
${project.version}
- org.glassfish.main.connectors
- connectors-internal-api
+ org.glassfish.main.persistence
+ glassfish-oracle-jdbc-driver-packages
${project.version}
-
-
-
- jakarta.annotation
- jakarta.annotation-api
+ org.glassfish.main.persistence
+ jpa-container
+ ${project.version}
+
+ org.eclipse.persistence
+ org.eclipse.persistence.asm
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.core
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.jpa
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.jpa.jpql
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.jpa.modelgen.processor
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.moxy
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.dbws
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.oracle
-
-
+
+
+ org.eclipse.persistence
+ org.eclipse.persistence.json
+
+
+
- jakarta.ejb
- jakarta.ejb-api
+ org.glassfish.main.persistence
+ persistence-common
+ ${project.version}
+
- org.glassfish.corba
- glassfish-corba-omgapi
+ org.glassfish.main.transaction
+ jta
+ ${project.version}
+
+
+
+ org.glassfish.main.transaction
+ jts
+ ${project.version}
+
org.glassfish.corba
glassfish-corba-internal-api
+
+ org.glassfish.corba
+ glassfish-corba-omgapi
+
org.glassfish.pfl
pfl-basic
@@ -797,17 +823,15 @@
org.glassfish.pfl
pfl-dynamic
+
- org.glassfish.gmbal
- gmbal-api-only
-
-
- org.glassfish.gmbal
- gmbal
+ org.glassfish.main.ejb
+ ejb-client
+ ${project.version}
- org.glassfish.main.orb
- orb-connector
+ org.glassfish.main.ejb
+ ejb-container
${project.version}
@@ -815,534 +839,457 @@
glassfish-corba-orb
- org.glassfish.main.orb
- orb-enabler
+ org.glassfish.corba
+ rmic
org.glassfish.main.ejb
- ejb-client
+ gf-ejb-connector
${project.version}
- org.glassfish.main.ejb
- gf-ejb-connector
+ org.glassfish.main.core
+ jakartaee-kernel
${project.version}
+
- org.glassfish.main.ejb
- ejb-internal-api
- ${project.version}
+ org.glassfish.mojarra
+ mojarra
+
- org.glassfish.main.ejb
- ejb-container
+ org.glassfish.main.web
+ gf-web-connector
${project.version}
-
-
- org.glassfish.corba
- glassfish-corba-orb
-
-
- org.glassfish.corba
- rmic
-
-
-
-
-
- jakarta.xml.bind
- jakarta.xml.bind-api
+ org.glassfish.main.web
+ jsf-connector
+ ${project.version}
- org.eclipse
- yasson
+ org.glassfish.main.web
+ jspcaching-connector
+ ${project.version}
-
-
-
- org.glassfish.main.grizzly
- nucleus-grizzly-all
+ org.glassfish.main.web
+ jstl-connector
${project.version}
-
- org.glassfish.main.grizzly
- glassfish-grizzly-extra-all
+ org.glassfish.main.web
+ jersey-ejb-component-provider
${project.version}
-
-
-
- org.glassfish.main.jdbc
- jdbc-admin
+ org.glassfish.main.web
+ jersey-mvc-connector
${project.version}
-
-
- org.glassfish.main.cluster
- cluster-admin
-
-
- org.glassfish.main.jdbc
- jdbc-runtime
+ org.glassfish.main.common
+ stats77
${project.version}
- org.glassfish.main.jdbc.jdbc-ra.jdbc-ra-distribution
- jdbc-ra
+ org.glassfish.main.web
+ web-cli
${project.version}
- zip
-
-
- org.glassfish.main.jdbc.jdbc-ra.jdbc-core
- jdbc-core
-
-
- org.glassfish.main.jdbc.jdbc-ra.jdbc40
- jdbc40
-
-
- org.glassfish.main.jdbc
- templates
-
-
-
-
- org.glassfish.external
- derby
- zip
+ org.glassfish.main.web
+ web-core
+ ${project.version}
-
-
- org.glassfish.shoal
- shoal-gms-api
+ org.glassfish.main.web
+ web-embed-api
+ ${project.version}
- org.glassfish.shoal
- shoal-gms-impl
+ org.glassfish.main.web
+ web-glue
+ ${project.version}
-
-
-
- org.glassfish.main
- glassfish-jul-extension
+ org.glassfish.main.web
+ web-gui-plugin-common
+ ${project.version}
-
- net.java.dev.jna
- jna
+ org.glassfish.main.web
+ web-ha
+ ${project.version}
-
-
-
-
-
- org.glassfish.main.core
- kernel
+ org.glassfish.main.web
+ web-naming
${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
- org.glassfish.main.core
- jakartaee-kernel
+ org.glassfish.main.web
+ web-sse
${project.version}
- org.glassfish.main.core
- glassfish
+ org.glassfish.main.web
+ war-util
${project.version}
+
+
- org.glassfish.main.core
- glassfish-osgi-bootstrap
- ${project.version}
+ jakarta.servlet.jsp
+ jakarta.servlet.jsp-api
- org.glassfish.main.core
- api-exporter
- ${project.version}
+ jakarta.servlet.jsp.jstl
+ jakarta.servlet.jsp.jstl-api
-
- org.glassfish.main.core
- logging
- ${project.version}
+
+ org.glassfish.wasp
+ wasp
-
+
- org.glassfish.main.admin
- admin-cli
- ${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
- com.github.mwiede
- jsch
-
-
- org.glassfish.main.cluster
- cluster-common
-
-
+ jakarta.el
+ jakarta.el-api
- org.glassfish.main.admin
- admin-util
- ${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
+ org.glassfish.expressly
+ expressly
+
+
- org.glassfish.main.admin
- config-api
- ${project.version}
+ jakarta.websocket
+ jakarta.websocket-api
- org.glassfish.main.admin
- launcher
- ${project.version}
+ jakarta.websocket
+ jakarta.websocket-client-api
- org.glassfish.main.admin
- server-mgmt
- ${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
- org.glassfish.annotations
- logging-annotation-processor
-
-
+ org.glassfish.tyrus
+ tyrus-core
- org.glassfish.main.admin
- monitoring-core
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-server
- org.glassfish.main.admin
- backup
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-spi
- org.glassfish.main.admin
- gf-restadmin-connector
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-client
- org.glassfish.main.admin
- rest-client
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-container-servlet
- org.glassfish.main.admin
- rest-service
- ${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
- org.glassfish.main.admin
- appserver-cli
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-container-glassfish-cdi
- org.glassfish.main.admin
- cli-optional
- ${project.version}
-
-
- org.glassfish.main.admin
- admin-core
- ${project.version}
+ org.glassfish.tyrus
+ tyrus-container-glassfish-ejb
-
- org.glassfish.main.common
- glassfish-api
+ org.glassfish.main.security
+ websecurity
${project.version}
- com.sun.xml.bind
- jaxb-osgi
+ org.glassfish.annotations
+ logging-annotation-processor
- org.glassfish.main.common
- simple-glassfish-api
- ${project.version}
+ org.glassfish.soteria
+ soteria
- org.glassfish.main.common
- internal-api
- ${project.version}
+ org.glassfish.exousia
+ exousia
- org.glassfish.main.common
- common-util
- ${project.version}
+ com.nimbusds
+ nimbus-jose-jwt
- org.glassfish.main.common
- glassfish-jdk-extensions
- ${project.version}
+ org.glassfish.epicyro
+ epicyro
- org.glassfish.main.common
- scattered-archive-api
- ${project.version}
+ jakarta.security.enterprise
+ jakarta.security.enterprise-api
+
+
+
+
+ jakarta.cdi
+ jakarta.cdi-api
- org.glassfish.main.common
- amx-jakartaee
+ jakarta.cdi
+ jakarta.cdi-lang-model-api
+
+
+ jakarta.interceptor
+ jakarta.interceptor-api
+
+
+ org.glassfish.main.web
+ cdi-api-fragment
${project.version}
-
-
- org.glassfish.main.common
- amx-core
-
-
- org.glassfish.main.common
- annotation-framework
+ org.glassfish.main.web
+ gf-weld-connector
${project.version}
+
+
+ org.jboss.weld
+ weld-osgi-bundle
- org.glassfish.annotations
- logging-annotation-processor
+ org.jboss.jdeparser
+ jdeparser
+
+
+ org.jboss.logging
+ jboss-logging-processor
- org.glassfish.main.common
- container-common
- ${project.version}
+ org.jboss.classfilewriter
+ jboss-classfilewriter
- org.glassfish.main.common
- glassfish-naming
+ org.glassfish.main.web
+ weld-integration
${project.version}
-
-
- org.glassfish.main.deployment
- deployment-admin
+ org.glassfish.main.web
+ weld-integration-fragment
${project.version}
+
- org.glassfish.main.deployment
- deployment-autodeploy
+ org.glassfish.main.jdbc
+ jdbc-admin
${project.version}
+
+
+ org.glassfish.main.cluster
+ cluster-admin
+
+
- org.glassfish.main.deployment
- deployment-common
+ org.glassfish.main.jdbc
+ jdbc-runtime
${project.version}
- org.glassfish.main.deployment
- nucleus-dtds
+ org.glassfish.main.jdbc.jdbc-ra.jdbc-ra-distribution
+ jdbc-ra
${project.version}
zip
-
-
- org.glassfish.main.deployment
- dol
- ${project.version}
- org.glassfish.annotations
- logging-annotation-processor
+ org.glassfish.main.jdbc.jdbc-ra.jdbc-core
+ jdbc-core
+
+
+ org.glassfish.main.jdbc.jdbc-ra.jdbc40
+ jdbc40
+
+
+ org.glassfish.main.jdbc
+ templates
+
- org.glassfish.main.deployment
- deployment-jakartaee-core
- ${project.version}
+ org.glassfish.jersey.media
+ jersey-media-moxy
- org.glassfish.main.deployment
- appserver-dtds
- ${project.version}
- zip
+ org.glassfish.jersey.ext.cdi
+ jersey-cdi1x
- org.glassfish.main.deployment
- appserver-schemas
- ${project.version}
- zip
+ org.glassfish.jersey.ext.cdi
+ jersey-cdi1x-servlet
- org.glassfish.main.deployment
- nucleus-schemas
- ${project.version}
- zip
+ org.glassfish.jersey.ext.cdi
+ jersey-cdi1x-transaction
-
- org.glassfish.external
- management-api
+ org.glassfish.jersey.containers
+ jersey-container-servlet
- org.glassfish.main.flashlight
- flashlight-framework
- ${project.version}
+ org.glassfish.jersey.media
+ jersey-media-json-processing
- org.glassfish.main.flashlight
- flashlight-agent
- ${project.version}
+ org.glassfish.jersey.ext
+ jersey-mvc
- org.glassfish.main.flashlight
- flashlight-extra-jdk-packages
- ${project.version}
+ org.glassfish.jersey.ext
+ jersey-mvc-jsp
-
- org.jvnet.mimepull
- mimepull
+ org.glassfish.jersey.core
+ jersey-server
- org.glassfish.main.hk2
- config-types
- ${project.version}
-
-
- com.sun.xml.bind
- jaxb-osgi
-
-
+ org.glassfish.jersey.core
+ jersey-client
-
- org.glassfish.main.cluster
- gms-bootstrap
- ${project.version}
+ org.glassfish.jersey.containers
+ jersey-container-grizzly2-http
-
-
- org.glassfish.ha
- ha-api
+ org.glassfish.jersey.media
+ jersey-media-jaxb
- org.glassfish.main.ha
- ha-file-store
- ${project.version}
+ org.glassfish.jersey.media
+ jersey-media-json-jettison
- org.glassfish.main.loadbalancer
- load-balancer-admin
- ${project.version}
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
- org.glassfish.shoal
- shoal-cache
+ org.glassfish.jersey.media
+ jersey-media-sse
- org.glassfish.external
- schema2beans
+ org.glassfish.jersey.media
+ jersey-media-multipart
- org.glassfish.main.extras
- jakartaee-frag
- ${project.version}
- zip
+ org.glassfish.jersey.ext
+ jersey-bean-validation
- org.glassfish.main.extras
- appserv-rt-frag
- ${project.version}
- zip
+ org.glassfish.jersey.ext
+ jersey-entity-filtering
- org.glassfish.main.extras
- glassfish-embedded-shell-frag
- ${project.version}
- zip
+ org.glassfish.jersey.core
+ jersey-common
+
+
+ org.glassfish.jersey.inject
+ jersey-hk2
+
+
+ jakarta.ws.rs
+ jakarta.ws.rs-api
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-binding
+
+
+ com.fasterxml.jackson.core
+ jackson-core
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+
+
+ com.fasterxml.jackson.core
+ jackson-annotations
+
+
+ com.fasterxml.jackson.module
+ jackson-module-jakarta-xmlbind-annotations
- org.glassfish.metro
- webservices-api-osgi
-
-
- org.glassfish.main.extras
- glassfish-embedded-shell
+ *
+ *
- org.glassfish.main.extras
- glassfish-embedded-static-shell-frag
- ${project.version}
+ org.codehaus.jettison
+ jettison
+
+
+
+ jakarta.json
+ jakarta.json-api
+
+
+ org.eclipse.parsson
+ parsson
+
+
+ org.eclipse.parsson
+ parsson-media
+
+
+ jakarta.json.bind
+ jakarta.json.bind-api
+
+
+
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+
+
+ org.eclipse
+ yasson
+
+
+
+ org.glassfish.external
+ derby
zip
-
-
- com.fasterxml.woodstox
- woodstox-core
-
-
- org.glassfish.main.extras
- glassfish-embedded-static-shell
-
-
+
- org.glassfish.main.loadbalancer
- gf-load-balancer-connector
- ${project.version}
+ org.glassfish.shoal
+ shoal-gms-api
- org.glassfish.main.libpam4j
- libpam4j
- ${project.version}
+ org.glassfish.shoal
+ shoal-gms-impl
- org.glassfish.main.resourcebase.resources
- nucleus-resources
- ${project.version}
+ org.glassfish.main
+ glassfish-jul-extension
- com.fasterxml
- classmate
+ net.java.dev.jna
+ jna
-
diff --git a/appserver/featuresets/glassfish/pom.xml b/appserver/featuresets/glassfish/pom.xml
index e97dc95f05d..d4b0d9aee3c 100644
--- a/appserver/featuresets/glassfish/pom.xml
+++ b/appserver/featuresets/glassfish/pom.xml
@@ -281,7 +281,7 @@
org.glassfish.external
- dbschema
+ dbschema-osgi
*
@@ -383,7 +383,7 @@
org.glassfish.external
- ant
+ ant-osgi
*
diff --git a/appserver/featuresets/web/pom.xml b/appserver/featuresets/web/pom.xml
index f243e4d45dd..ed7b91ddedc 100644
--- a/appserver/featuresets/web/pom.xml
+++ b/appserver/featuresets/web/pom.xml
@@ -516,7 +516,7 @@
org.glassfish.external
- schema2beans
+ schema2beans-osgi
*
diff --git a/appserver/itest-tools/src/main/java/org/glassfish/main/itest/tools/HttpClient10.java b/appserver/itest-tools/src/main/java/org/glassfish/main/itest/tools/HttpClient10.java
index f53c8331bbc..c18d3827312 100644
--- a/appserver/itest-tools/src/main/java/org/glassfish/main/itest/tools/HttpClient10.java
+++ b/appserver/itest-tools/src/main/java/org/glassfish/main/itest/tools/HttpClient10.java
@@ -90,7 +90,7 @@ public HttpResponse send(String method, String content) throws Exception {
public static class HttpResponse {
/**
- * Example: HTTP/1.0 403 Forbidden
+ * Example: HTTP/1.0 403 Forbidden
*/
public final String responseLine;
/**
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/common/DataSourceObjectBuilder.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/common/DataSourceObjectBuilder.java
index b850c97d87c..672c3c19853 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/common/DataSourceObjectBuilder.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/common/DataSourceObjectBuilder.java
@@ -17,6 +17,7 @@
package com.sun.gjc.common;
+import com.sun.appserv.jdbc.DataSource;
import com.sun.enterprise.util.i18n.StringManager;
import com.sun.gjc.util.MethodExecutor;
import com.sun.logging.LogDomains;
@@ -64,9 +65,7 @@
* the specification.
*
* @author Binod P.G
- * @version 1.0, 02/07/23
- * @see com.sun.gjc.common.DataSourceSpec
- * @see com.sun.gjc.util.MethodExcecutor
+ * @see DataSourceSpec
*/
public class DataSourceObjectBuilder implements Serializable {
@@ -81,7 +80,7 @@ public class DataSourceObjectBuilder implements Serializable {
/**
* Construct a DataSource Object from the spec.
*
- * @param spec DataSourceSpec object.
+ * @param spec {@link DataSourceSpec} object.
*/
public DataSourceObjectBuilder(DataSourceSpec spec) {
this.spec = spec;
@@ -167,7 +166,7 @@ public Object constructDataSourceObject() throws ResourceException {
* to a set of methodName and parameters. Prepare a hashtable containing these
* details and return.
*
- * @param spec DataSourceSpec object.
+ * @param spec {@link DataSourceSpec} object.
* @return Hashtable containing method names and parameters,
* @throws ResourceException If delimiter is not provided and property string is
* not null.
@@ -256,11 +255,10 @@ public Map> parseDriverProperties(String values, String esc
}
/**
- * Creates a Datasource object according to the spec.
+ * Creates a {@link DataSource} object according to the spec.
*
* @return Initial DataSource Object instance.
- * @throws ResourceException If class name is wrong or classpath is
- * not set properly.
+ * @throws ResourceException If class name is wrong or classpath is not set properly.
*/
private Object getDataSourceObject() throws ResourceException {
String className = spec.getDetail(CLASSNAME);
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ManagedConnectionMetaDataImpl.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ManagedConnectionMetaDataImpl.java
index aa13c569de8..4b1d694bdf2 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ManagedConnectionMetaDataImpl.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ManagedConnectionMetaDataImpl.java
@@ -46,7 +46,7 @@ public class ManagedConnectionMetaDataImpl implements ManagedConnectionMetaData
* Constructor for ManagedConnectionMetaDataImpl
*
* @param managedConnection ManagedConnection
- * @throws ResourceException if getting the DatabaseMetaData object
+ * @throws ResourceException if getting the DatabaseMetaData object
* fails
*/
public ManagedConnectionMetaDataImpl(ManagedConnectionImpl managedConnection) throws ResourceException {
@@ -64,7 +64,7 @@ public ManagedConnectionMetaDataImpl(ManagedConnectionImpl managedConnection) th
* ManagedConnection.
*
* @return Product name of the EIS instance
- * @throws ResourceException
+ * @throws ResourceException
*/
public String getEISProductName() throws ResourceException {
try {
@@ -80,7 +80,7 @@ public String getEISProductName() throws ResourceException {
* ManagedConnection.
*
* @return Product version of the EIS instance
- * @throws ResourceException
+ * @throws ResourceException
*/
public String getEISProductVersion() throws ResourceException {
try {
@@ -96,7 +96,7 @@ public String getEISProductVersion() throws ResourceException {
* instance can support across client processes.
*
* @return Maximum limit for number of active concurrent connections
- * @throws ResourceException
+ * @throws ResourceException
*/
public int getMaxConnections() throws ResourceException {
try {
@@ -113,7 +113,7 @@ public int getMaxConnections() throws ResourceException {
* context, a connection to the EIS instance has been established.
*
* @return name of the user
- * @throws ResourceException
+ * @throws ResourceException
*/
public String getUserName() throws ResourceException {
PasswordCredential passwordCredential = managedConnection.getPasswordCredential();
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ResourceAdapterImpl.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ResourceAdapterImpl.java
index 62f2f54e868..1d324f6dc24 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ResourceAdapterImpl.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/ResourceAdapterImpl.java
@@ -82,7 +82,7 @@ public static ResourceAdapterImpl getInstance() {
*
* @param mef MessageEndpointFactory
* @param as ActivationSpec
- * @throws NotSupportedException
+ * @throws NotSupportedException
*
*/
public void endpointActivation(MessageEndpointFactory mef, ActivationSpec as) throws NotSupportedException {
@@ -104,7 +104,7 @@ public void endpointDeactivation(MessageEndpointFactory mef, ActivationSpec as)
* NotSupportedException
*
* @param specs ActivationSpec array
- * @throws NotSupportedException
+ * @throws NotSupportedException
*
*/
public XAResource[] getXAResources(ActivationSpec[] specs) throws NotSupportedException {
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/base/AbstractDataSource.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/base/AbstractDataSource.java
index d24eb6055a9..58c532cd7cb 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/base/AbstractDataSource.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/spi/base/AbstractDataSource.java
@@ -145,7 +145,7 @@ public Connection getConnection(String user, String pwd) throws SQLException {
*
* @param con Connection obtained from Datasource.getConnection()
* @return java.sql.Connection implementation of the driver.
- * @throws java.sql.SQLException If connection cannot be obtained.
+ * @throws java.sql.SQLException If connection cannot be obtained.
*/
@Override
public Connection getConnection(Connection con) throws SQLException {
@@ -165,7 +165,7 @@ public Connection getConnection(Connection con) throws SQLException {
* this meethod does not fit in the connector contract per se.
*
* @return java.sql.Connection
- * @throws java.sql.SQLException If connection cannot be obtained
+ * @throws java.sql.SQLException If connection cannot be obtained
*/
@Override
public Connection getNonTxConnection() throws SQLException {
@@ -191,7 +191,7 @@ public Connection getNonTxConnection() throws SQLException {
* @param user User name for authenticating the connection
* @param password Password for authenticating the connection
* @return java.sql.Connection
- * @throws java.sql.SQLException If connection cannot be obtained
+ * @throws java.sql.SQLException If connection cannot be obtained
*/
@Override
public Connection getNonTxConnection(String user, String password) throws SQLException {
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/MethodExecutor.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/MethodExecutor.java
index e1b464c0a57..fa000875aa1 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/MethodExecutor.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/MethodExecutor.java
@@ -40,7 +40,6 @@
* Execute the methods based on the parameters.
*
* @author Binod P.G
- * @version 1.0, 02/07/23
*/
public class MethodExecutor implements Serializable {
@@ -55,10 +54,9 @@ public class MethodExecutor implements Serializable {
* Exceute a simple set Method.
*
* @param value Value to be set.
- * @param method Method object.
+ * @param method {@link Method} object.
* @param obj Object on which the method to be executed.
- * @throws ResourceException, in case of the mismatch of parameter
- * values or a security violation.
+ * @throws ResourceException in case of the mismatch of parameter values or a security violation.
*/
public void runJavaBeanMethod(String value, Method method, Object obj) throws ResourceException {
if (value == null || value.trim().equals("")) {
@@ -90,11 +88,10 @@ public void runJavaBeanMethod(String value, Method method, Object obj) throws Re
/**
* Executes the method.
*
- * @param method Method object.
+ * @param method {@link Method} object.
* @param obj Object on which the method to be executed.
* @param values Parameter values for executing the method.
- * @throws ResourceException, in case of the mismatch of parameter
- * values or a security violation.
+ * @throws ResourceException in case of the mismatch of parameter values or a security violation.
*/
public void runMethod(Method method, Object obj, List values) throws ResourceException {
Class>[] parameters = method.getParameterTypes();
@@ -134,8 +131,7 @@ public void runMethod(Method method, Object obj, List values) throws Res
* @param type Class name to which the conversion is required.
* @param parameter String value to be converted.
* @return Converted value.
- * @throws ResourceException, in case of the mismatch of parameter
- * values or a security violation.
+ * @throws ResourceException in case of the mismatch of parameter values or a security violation.
*/
private Object convertType(Class> type, String parameter) throws ResourceException {
try {
@@ -182,8 +178,9 @@ private Object convertType(Class> type, String parameter) throws ResourceExcep
if (typeName.equals("java.util.Properties")) {
Properties p = stringToProperties(parameter);
- if (p != null)
+ if (p != null) {
return p;
+ }
}
return parameter;
@@ -221,8 +218,9 @@ public Object invokeMethod(Object object, String methodName, Class>[] valueTyp
}
private Properties stringToProperties(String parameter) {
- if (parameter == null)
+ if (parameter == null) {
return null;
+ }
String s = parameter.trim();
if (!((s.startsWith("(") && s.endsWith(")")))) {
return null; // not a "( .... )" syntax
diff --git a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/SecurityUtils.java b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/SecurityUtils.java
index 038c512b035..7cf89ae84c6 100644
--- a/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/SecurityUtils.java
+++ b/appserver/jdbc/jdbc-ra/jdbc-core/src/main/java/com/sun/gjc/util/SecurityUtils.java
@@ -58,8 +58,8 @@ public class SecurityUtils {
* @param subject Subject
* @param connectionRequestInfo ConnectionRequestInfo
* @return PasswordCredential
- * @throws ResourceException generic exception if operation fails
- * @throws SecurityException if access to the Subject
+ * @throws ResourceException generic exception if operation fails
+ * @throws SecurityException if access to the Subject
* instance is denied
*/
public static PasswordCredential getPasswordCredential(final ManagedConnectionFactory managedConnectionFactory, final Subject subject,
diff --git a/appserver/load-balancer/admin/pom.xml b/appserver/load-balancer/admin/pom.xml
index b021c7ab969..e00a0c7ce60 100644
--- a/appserver/load-balancer/admin/pom.xml
+++ b/appserver/load-balancer/admin/pom.xml
@@ -77,21 +77,9 @@
glassfish-api
${project.version}
-
- org.glassfish.main.core
- kernel
- ${project.version}
- test
-
-
- org.glassfish.main
- test-utils
- ${project.version}
- test
-
org.glassfish.external
- schema2beans
+ schema2beans-osgi
org.glassfish.main.security
@@ -108,6 +96,19 @@
gf-load-balancer-connector
${project.version}
+
+
+ org.glassfish.main.core
+ kernel
+ ${project.version}
+ test
+
+
+ org.glassfish.main
+ test-utils
+ ${project.version}
+ test
+
diff --git a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPHealthCheckerCommand.java b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPHealthCheckerCommand.java
index 1e428871792..a3aa0b2ad32 100644
--- a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPHealthCheckerCommand.java
+++ b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPHealthCheckerCommand.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 2010, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -27,10 +28,9 @@
import jakarta.inject.Inject;
import java.beans.PropertyVetoException;
+import java.lang.System.Logger;
import java.util.ArrayList;
import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
import org.glassfish.api.ActionReport;
import org.glassfish.api.Param;
@@ -52,6 +52,10 @@
import org.jvnet.hk2.config.SingleConfigCode;
import org.jvnet.hk2.config.TransactionFailure;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.INFO;
+import static java.lang.System.Logger.Level.WARNING;
+
/**
* This is a remote command that creates health-checker config for cluster or
* server.
@@ -78,6 +82,7 @@
})
})
public final class CreateHTTPHealthCheckerCommand implements AdminCommand {
+ private static final Logger LOG = System.getLogger(CreateHTTPHealthCheckerCommand.class.getName());
@Param(optional=true, defaultValue="10")
String timeout;
@@ -100,9 +105,6 @@ public final class CreateHTTPHealthCheckerCommand implements AdminCommand {
@Inject
Target tgt;
- @Inject
- Logger logger;
-
private ActionReport report;
final private static LocalStringManagerImpl localStrings =
@@ -117,22 +119,28 @@ public void execute(AdminCommandContext context) {
LbConfigs lbconfigs = domain.getExtensionByType(LbConfigs.class);
if (lbconfigs == null) {
- String msg = localStrings.getLocalString("NoLbConfigsElement",
- "Empty lb-configs");
+ String msg = localStrings.getLocalString("NoLbConfigsElement", "Empty lb-configs");
+ report.setActionExitCode(ActionReport.ExitCode.FAILURE);
+ report.setMessage(msg);
+ return;
+ }
+
+ if (config == null) {
+ String msg = localStrings.getLocalString("InvalidLbConfigName", "Invalid LB configuration.");
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setMessage(msg);
return;
}
+
if (config != null) {
LbConfig lbConfig = lbconfigs.getLbConfig(config);
- createHealthCheckerInternal(url,interval,timeout,lbConfig,
- config ,target);
+ createHealthCheckerInternal(url, interval, timeout, lbConfig, target);
} else {
List lbConfigs = lbconfigs.getLbConfig();
if (lbConfigs.size() == 0) {
String msg = localStrings.getLocalString("NoLbConfigsElement", "No LB configs defined");
- logger.warning(msg);
+ LOG.log(WARNING, msg);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setMessage(msg);
return;
@@ -144,18 +152,16 @@ public void execute(AdminCommandContext context) {
if ( (match == null) || (match.size() == 0) ) {
String msg = localStrings.getLocalString("UnassociatedTarget", "No LB config references target {0}", target);
- logger.warning(msg);
+ LOG.log(WARNING, msg);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setMessage(msg);
return;
}
for (LbConfig lc:match){
- createHealthCheckerInternal(url,interval,timeout,
- lc, lc.getName(), target);
+ createHealthCheckerInternal(url, interval, timeout, lc, target);
}
}
-
}
/**
@@ -183,25 +189,11 @@ public void execute(AdminCommandContext context) {
*
* @throws CommandException If the operation is failed
*/
- private void createHealthCheckerInternal(String url, String interval,
- String timeout, LbConfig lbConfig, String lbConfigName, String target)
- {
- // invalid lb config name
- if (lbConfigName == null) {
- String msg = localStrings.getLocalString("InvalidLbConfigName", "Invalid LB configuration.");
- report.setActionExitCode(ActionReport.ExitCode.FAILURE);
- report.setMessage(msg);
- return;
- }
-
- lbConfigName = lbConfig.getName();
- // print diagnostics msg
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("[LB-ADMIN] createHealthChecker called - URL "
- + url + ", Interval " + interval + ", Time out "
- + timeout + ", LB Config " + lbConfigName
- + ", Target " + target);
- }
+ private void createHealthCheckerInternal(String url, String interval, String timeout, LbConfig lbConfig,
+ String target) {
+ String lbConfigName = lbConfig.getName();
+ LOG.log(DEBUG, () -> "createHealthChecker called - URL " + url + ", Interval " + interval
+ + " s, Time out " + timeout + " s, LB Config " + lbConfigName + ", Target " + target);
// null target
if (target == null) {
@@ -235,8 +227,7 @@ private void createHealthCheckerInternal(String url, String interval,
report.setFailureCause(ex);
return;
}
- logger.info(localStrings.getLocalString("http_lb_admin.HealthCheckerCreated",
- "Health checker created for target {0}", target));
+ LOG.log(INFO, "Health checker created for target {0}", target);
} else {
String msg = localStrings.getLocalString("HealthCheckerExists",
"Health checker server/cluster [{0}] already exists.", target);
@@ -268,8 +259,7 @@ private void createHealthCheckerInternal(String url, String interval,
report.setFailureCause(ex);
return;
}
- logger.info(localStrings.getLocalString("http_lb_admin.HealthCheckerCreated",
- "Health checker created for target {0}", target));
+ LOG.log(INFO, "Health checker created for target {0}", target);
} else {
String msg = localStrings.getLocalString("HealthCheckerExists",
"Health checker server/cluster [{0}] already exists.", target);
@@ -338,7 +328,7 @@ private List matchLbConfigToTarget(List lbConfigs,
// bad target
if (target == null) {
String msg = localStrings.getLocalString("Nulltarget", "Null target");
- logger.warning(msg);
+ LOG.log(WARNING, msg);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setMessage(msg);
return null;
diff --git a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPLBRefCommand.java b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPLBRefCommand.java
index 8836c82c5f2..c6d8a99289c 100644
--- a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPLBRefCommand.java
+++ b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/CreateHTTPLBRefCommand.java
@@ -29,7 +29,6 @@
import java.beans.PropertyVetoException;
import java.util.List;
-import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.api.ActionReport;
@@ -56,6 +55,8 @@
import org.jvnet.hk2.config.SingleConfigCode;
import org.jvnet.hk2.config.TransactionFailure;
+import static java.util.logging.Level.FINE;
+
/**
*
* This is a remote command that supports the create-http-lb-ref CLI command.
@@ -233,6 +234,7 @@ public void execute(AdminCommandContext context) {
// create lb ref
createLBRef(lbconfigs, target, config);
if (report.getActionExitCode() != ActionReport.ExitCode.SUCCESS) {
+
return;
}
@@ -288,9 +290,7 @@ public void execute(AdminCommandContext context) {
}
public void createLBRef(LbConfigs lbconfigs, String target, String configName) {
- if (logger.isLoggable(Level.FINE)) {
- logger.fine("[LB-ADMIN] createLBRef called for target " + target);
- }
+ logger.log(FINE, "createLBRef(target=" + target + ", configName=" + configName + ")");
// target is a cluster
if (tgt.isCluster(target)) {
@@ -314,6 +314,8 @@ public void createLBRef(LbConfigs lbconfigs, String target, String configName) {
}
private void addServerToLBConfig(final LbConfigs lbconfigs, final String configName, final String serverName) {
+ logger.log(FINE,
+ () -> "addServerToLBConfig(lbconfigs, configName=" + configName + ", serverName=" + serverName + ")");
LbConfig lbConfig = lbconfigs.getLbConfig(configName);
ServerRef sRef = lbConfig.getRefByRef(ServerRef.class, serverName);
diff --git a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/LocalStrings.properties b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/LocalStrings.properties
index 6962b726611..7bd217eb885 100644
--- a/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/LocalStrings.properties
+++ b/appserver/load-balancer/admin/src/main/java/org/glassfish/loadbalancer/admin/cli/LocalStrings.properties
@@ -115,7 +115,6 @@ ServerEnabled=Server [{0}] is already enabled.
ClusterPrefix=Cluster:
ServerPrefix=Server:
-http_lb_admin.HealthCheckerCreated=EEADM00210:Health checker created for {0}.
http_lb_admin.HealthCheckerDeleted=EEADM0211:Health checker deleted for {0}.
http_lb_admin.AddServerToConfig=EEADM0212:Added server {0} to load balancer {1}.
http_lb_admin.AddClusterToConfig=EEADM0213:Added cluster {0} to load balancer {1}.
diff --git a/appserver/load-balancer/gf-load-balancer-connector/pom.xml b/appserver/load-balancer/gf-load-balancer-connector/pom.xml
index 7eb8270cc14..f9603944016 100644
--- a/appserver/load-balancer/gf-load-balancer-connector/pom.xml
+++ b/appserver/load-balancer/gf-load-balancer-connector/pom.xml
@@ -67,15 +67,4 @@
${project.version}
-
-
-
-
- src/main/java
-
- **/*.properties
-
-
-
-
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LbConfig.java b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LbConfig.java
index 163e884d203..9cc234c7799 100644
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LbConfig.java
+++ b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LbConfig.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2023, 2025 Contributors to the Eclipse Foundation
+ * Copyright (c) 2023, 2026 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -22,7 +22,6 @@
import com.sun.enterprise.config.serverbeans.Ref;
import com.sun.enterprise.config.serverbeans.ServerRef;
import com.sun.enterprise.util.LocalStringManagerImpl;
-import com.sun.logging.LogDomains;
import jakarta.inject.Inject;
import jakarta.validation.Payload;
@@ -31,12 +30,12 @@
import jakarta.validation.constraints.Pattern;
import java.beans.PropertyVetoException;
+import java.lang.System.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Properties;
-import java.util.logging.Logger;
import org.glassfish.api.Param;
import org.glassfish.api.admin.AdminCommandContext;
@@ -58,14 +57,17 @@
import org.jvnet.hk2.config.types.Property;
import org.jvnet.hk2.config.types.PropertyBag;
-import static java.util.logging.Level.SEVERE;
+import static java.lang.System.Logger.Level.ERROR;
+import static java.lang.System.Logger.Level.INFO;
import static org.glassfish.config.support.Constants.NAME_REGEX;
/**
*
*/
@Configured
-@RefConstraint(message = "{ref.invalid}", payload = RefValidator.class)
+@RefConstraint(
+ message = "lb-config can contain references to either server-ref or cluster-ref but not both.",
+ payload = RefValidator.class)
public interface LbConfig extends ConfigBeanProxy, PropertyBag, Payload {
String LAST_APPLIED_PROPERTY = "last-applied";
@@ -80,7 +82,13 @@ public interface LbConfig extends ConfigBeanProxy, PropertyBag, Payload {
* @return possible object is {@link String}
*/
@Attribute(key = true)
- @Pattern(regexp = NAME_REGEX, message = "{lbconfig.invalid.name}", payload = LbConfig.class)
+ @Pattern(
+ regexp = NAME_REGEX,
+ message = """
+ Invalid lb-config name. The name must start with a letter, number or underscore and may contain only
+ letters, numbers, and these characters: hyphen, period, underscore, hash and semicolon."
+ """,
+ payload = LbConfig.class)
@NotNull
String getName();
@@ -295,10 +303,10 @@ private boolean setInternalProperty(String propertyName) {
propertyProxy.setValue(String.valueOf((new Date()).getTime()));
}
transaction.commit();
- } catch (Exception ex) {
+ } catch (Exception e) {
transaction.rollback();
- Logger logger = LogDomains.getLogger(LbConfig.class, LogDomains.ADMIN_LOGGER, false);
- logger.log(SEVERE, "Unable to set property " + propertyName + " in lbconfig with name " + getName(), ex);
+ System.getLogger(LbConfig.class.getName()).log(ERROR,
+ () -> "Unable to set property '" + propertyName + "' in lbconfig with name '" + getName() + "'", e);
return false;
}
return true;
@@ -307,6 +315,7 @@ private boolean setInternalProperty(String propertyName) {
@Service
@PerLookup
class Decorator implements CreationDecorator {
+ private static final Logger LOG = System.getLogger(Decorator.class.getName());
@Param (name = "name", optional = true)
String config_name;
@@ -347,12 +356,9 @@ class Decorator implements CreationDecorator {
*/
@Override
public void decorate(AdminCommandContext context, final LbConfig instance) throws TransactionFailure, PropertyVetoException {
- Logger logger = LogDomains.getLogger(LbConfig.class, LogDomains.ADMIN_LOGGER);
- LocalStringManagerImpl localStrings = new LocalStringManagerImpl(LbConfig.class);
-
if (config_name == null && target == null) {
- String msg = localStrings.getLocalString("RequiredTargetOrConfig", "Neither LB config name nor target specified");
- throw new TransactionFailure(msg);
+ throw new TransactionFailure(
+ "Either option --target or operand config_name is required for this command.");
}
// generate lb config name if not specified
@@ -371,14 +377,13 @@ public void decorate(AdminCommandContext context, final LbConfig instance) throw
transaction.commit();
} catch (TransactionFailure | RetryableException ex) {
transaction.rollback();
- String msg = localStrings.getLocalString("LbConfigsCreationFailed", "Creation of parent element lb-configs failed");
- throw new TransactionFailure(msg, ex);
+ throw new TransactionFailure("Creation of parent element lb-configs failed.", ex);
}
}
if (lbconfigs.getLbConfig(config_name) != null) {
- String msg = localStrings.getLocalString("LbConfigExists", config_name);
- throw new TransactionFailure(msg);
+ throw new TransactionFailure("Load balancer configuration '" + config_name
+ + "' contains server refs or clusters refs. It must be empty in order to be removed.");
}
instance.setName(config_name);
@@ -399,8 +404,8 @@ public void decorate(AdminCommandContext context, final LbConfig instance) throw
sRef.setRef(target);
instance.getClusterRefOrServerRef().add(sRef);
} else {
- String msg = localStrings.getLocalString("InvalidTarget", target);
- throw new TransactionFailure(msg);
+ throw new TransactionFailure(
+ "Invalid argument. Target '" + target + "' is not a cluster or stand alone server instance.");
}
}
@@ -413,8 +418,7 @@ public void decorate(AdminCommandContext context, final LbConfig instance) throw
instance.getProperty().add(newprop);
}
}
- logger.info(localStrings.getLocalString("http_lb_admin.LbConfigCreated",
- "Load balancer configuration {0} created.", config_name));
+ LOG.log(INFO, () -> "Load balancer configuration '" + config_name + "' created.");
}
}
@@ -427,18 +431,16 @@ class DeleteDecorator implements DeletionDecorator {
@Override
public void decorate(AdminCommandContext context, LbConfigs parent, LbConfig child) throws TransactionFailure {
- Logger logger = LogDomains.getLogger(LbConfig.class, LogDomains.ADMIN_LOGGER);
- LocalStringManagerImpl localStrings = new LocalStringManagerImpl(LbConfig.class);
String lbConfigName = child.getName();
LbConfig lbConfig = domain.getExtensionByType(LbConfigs.class).getLbConfig(lbConfigName);
-
//Ensure there are no refs
- if ( (lbConfig.getClusterRefOrServerRef().size() != 0 ) ) {
- String msg = localStrings.getLocalString("LbConfigNotEmpty", lbConfigName);
- throw new TransactionFailure(msg);
+ if (!lbConfig.getClusterRefOrServerRef().isEmpty()) {
+ throw new TransactionFailure(
+ new LocalStringManagerImpl(LbConfig.class).getLocalString("LbConfigNotEmpty", lbConfigName));
}
- logger.info(localStrings.getLocalString("http_lb_admin.LbConfigDeleted", lbConfigName));
+ System.getLogger(DeleteDecorator.class.getName()).log(INFO,
+ () -> "Load balancer configuration '" + lbConfigName + "' deleted.");
}
}
}
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LoadBalancer.java b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LoadBalancer.java
index 644177866a7..aede957ddd7 100644
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LoadBalancer.java
+++ b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LoadBalancer.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -45,13 +46,6 @@
import org.jvnet.hk2.config.TransactionFailure;
import org.jvnet.hk2.config.types.Property;
import org.jvnet.hk2.config.types.PropertyBag;
-/**
- *
- */
-
-/* @XmlType(name = "", propOrder = {
- "property"
-}) */
@Configured
@HasNoDefaultConfiguration
@@ -189,7 +183,7 @@ public void decorate(AdminCommandContext context, LoadBalancers parent, LoadBala
if (!lb.getName().equals(lbName) &&
lb.getLbConfigName().equals(lbConfigName)) {
String msg = localStrings.getLocalString("LbConfigIsInUse", lbConfigName);
- report.setMessage(msg);
+ report.setMessage("LB configuration '" + lbConfigName + "' is in use by another load balancer.");
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
throw new TransactionFailure(msg);
}
@@ -204,12 +198,8 @@ public void decorate(AdminCommandContext context, LoadBalancers parent, LoadBala
configList.remove(lbConfig);
}
} catch (TransactionFailure ex) {
- logger.log(Level.WARNING,
- localStrings.getLocalString("DeleteLbConfigFailed",
- "Unable to remove lb config {0}", lbConfigName), ex);
- String msg = ex.getMessage() != null ? ex.getMessage()
- : localStrings.getLocalString("DeleteLbConfigFailed",
- "Unable to remove lb config {0}", lbConfigName);
+ String msg = "Unable to remove lb config " + lbConfigName;
+ logger.log(Level.WARNING, msg, ex);
report.setMessage(msg);
report.setActionExitCode(ActionReport.ExitCode.FAILURE);
report.setFailureCause(ex);
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LocalStrings.properties b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LocalStrings.properties
deleted file mode 100644
index 57a03762399..00000000000
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/LocalStrings.properties
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved.
-#
-# This program and the accompanying materials are made available under the
-# terms of the Eclipse Public License v. 2.0, which is available at
-# http://www.eclipse.org/legal/epl-2.0.
-#
-# This Source Code may also be made available under the following Secondary
-# Licenses when the conditions for such availability set forth in the
-# Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
-# version 2 with the GNU Classpath Exception, which is available at
-# https://www.gnu.org/software/classpath/license.html.
-#
-# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
-#
-
-LbConfigIsInUse=LB configuration [{0}] is in use by another load balancer.
-DeleteLbConfigFailed=Unable to remove lb config {0}.
-RequiredTargetOrConfig=CLI251: Either option --target or operand config_name is required for this command.
-LbConfigExists=Load balancer configuration [{0}] already exists.
-InvalidTarget=Invalid argument. Target [{0}] is not a cluster or stand alone server instance.
-LbConfigNotEmpty=Load balancer configuration [{0}] contains server refs or clusters refs. It must be empty in order to be removed.
-LbConfigsCreationFailed=Creation of parent element lb-configs failed
-
-create.http.lb.config.command.usagetext=create-http-lb-config\n\t[--responsetimeout ]\n\t[--monitor ]\n\t[--httpsrouting ]\n\t[--property (name=value)[:name=value]*]\n\t[--routecookie ]\n\t[--reloadinterval ]\n\t[-?|--help[=]] --target | name
-
-http_lb_admin.LbConfigCreated=EEADM0202:Load balancer configuration {0} created.
-http_lb_admin.LbConfigDeleted=EEADM0203:Load balancer configuration {0} deleted.
-
-lbconfig.invalid.name=Invalid lb-config name. The name must start with a letter, number or underscore and may contain only letters, numbers, and these characters: hyphen, period, underscore, hash and semicolon.
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/LocalStrings.properties b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/LocalStrings.properties
deleted file mode 100644
index 9081dba9541..00000000000
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/LocalStrings.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright (c) 2011, 2018 Oracle and/or its affiliates. All rights reserved.
-#
-# This program and the accompanying materials are made available under the
-# terms of the Eclipse Public License v. 2.0, which is available at
-# http://www.eclipse.org/legal/epl-2.0.
-#
-# This Source Code may also be made available under the following Secondary
-# Licenses when the conditions for such availability set forth in the
-# Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
-# version 2 with the GNU Classpath Exception, which is available at
-# https://www.gnu.org/software/classpath/license.html.
-#
-# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
-#
-
-ref.invalid=lb-config can contain references to either server-ref or cluster-ref but not both.
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefConstraint.java b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefConstraint.java
index f5bf8157ec8..f692880205b 100644
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefConstraint.java
+++ b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefConstraint.java
@@ -33,7 +33,7 @@
@Documented
@Constraint(validatedBy = RefValidator.class)
public @interface RefConstraint {
- String message() default "{ref.invalid}";
+ String message() default "lb-config can contain references to either server-ref or cluster-ref but not both.";
Class>[] groups() default {};
Class extends Payload>[] payload() default {};
}
diff --git a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefValidator.java b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefValidator.java
index 3f9b5423015..5547bc46eaf 100644
--- a/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefValidator.java
+++ b/appserver/load-balancer/gf-load-balancer-connector/src/main/java/org/glassfish/loadbalancer/config/customvalidators/RefValidator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 2011, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -41,15 +42,12 @@ public void initialize(final RefConstraint constraint) {
@Override
public boolean isValid(final LbConfig bean,
final ConstraintValidatorContext constraintValidatorContext) {
- if (bean == null) return true;
-
+ if (bean == null) {
+ return true;
+ }
List sRefs = bean.getRefs(ServerRef.class);
List cRefs = bean.getRefs(ClusterRef.class);
-
- if (sRefs.size() > 0 && cRefs.size() > 0) {
- return false;
- }
- return true;
+ return sRefs.isEmpty() || cRefs.isEmpty();
}
}
diff --git a/appserver/persistence/cmp/ejb-mapping/pom.xml b/appserver/persistence/cmp/ejb-mapping/pom.xml
index aa0b9915ad5..398780b319b 100644
--- a/appserver/persistence/cmp/ejb-mapping/pom.xml
+++ b/appserver/persistence/cmp/ejb-mapping/pom.xml
@@ -57,7 +57,7 @@
org.glassfish.external
- schema2beans
+ schema2beans-osgi
diff --git a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/AbstractNameMapper.java b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/AbstractNameMapper.java
index 31aaac67b1d..9d8b2272b91 100644
--- a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/AbstractNameMapper.java
+++ b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/AbstractNameMapper.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * AbstractNameMapper.java
- *
- * Created on October 28, 2004, 2:51 PM
- */
-
package com.sun.jdo.api.persistence.mapping.ejb;
import java.util.ArrayList;
@@ -34,7 +29,7 @@
* also has methods for translation of field names. The basic entry point
* is ejb name or persistence-capable class name.
*
- * @author Rochelle Raccah
+ * @author Rochelle Raccah 2004
*/
abstract public class AbstractNameMapper {
public static final int USER_DEFINED_KEY_CLASS = 1;
@@ -42,14 +37,14 @@ abstract public class AbstractNameMapper {
public static final int UNKNOWN_KEY_CLASS = 3;
/** Defines key field name for unknown primary key */
- public static final String GENERATED_KEY_FIELD_NAME = "generatedPKField"; // NOI18N
+ public static final String GENERATED_KEY_FIELD_NAME = "generatedPKField";
/** Defines version field name prefix for version consistency */
public static final String GENERATED_VERSION_FIELD_PREFIX =
- "thisVersionFieldWasGeneratedByTheNameMapper"; // NOI18N
+ "thisVersionFieldWasGeneratedByTheNameMapper";
protected static final String GENERATED_CMR_FIELD_PREFIX =
- "thisRelationshipFieldWasGeneratedByTheNameMapper"; // NOI18N
+ "thisRelationshipFieldWasGeneratedByTheNameMapper";
- abstract protected Map getGeneratedFieldsMap();
+ abstract protected Map, List> getGeneratedFieldsMap();
abstract protected Map getInverseFieldsMap();
@@ -95,7 +90,7 @@ public String getKeyClassForPersistenceKeyClass(String className) {
* key class
*/
public String getEjbNameForPersistenceKeyClass(String className) {
- if (className.toUpperCase().endsWith("OID")) { // NOI18N
+ if (className.toUpperCase().endsWith("OID")) {
return getEjbNameForPersistenceClass(
className.substring(0, className.length() - 4));
}
@@ -284,16 +279,17 @@ public boolean isGeneratedEjbRelationship(String name, String fieldName) {
* @param name the name of the ejb
* @return a List of generated relationship names
*/
- public List getGeneratedRelationshipsForEjbName(String name) {
- Map generatedFieldsMap = getGeneratedFieldsMap();
- Iterator iterator = generatedFieldsMap.keySet().iterator();
- List returnList = new ArrayList();
+ public List getGeneratedRelationshipsForEjbName(String name) {
+ Map, List> generatedFieldsMap = getGeneratedFieldsMap();
+ Iterator> iterator = generatedFieldsMap.keySet().iterator();
+ List returnList = new ArrayList<>();
while (iterator.hasNext()) {
- List nextField = (List)iterator.next();
+ List nextField = iterator.next();
- if (nextField.get(0).equals(name))
+ if (nextField.get(0).equals(name)) {
returnList.add(nextField.get(1));
+ }
}
return returnList;
@@ -324,7 +320,7 @@ public String[] getGeneratedFieldForEjbField(String name,
*/
public String[] getEjbFieldForGeneratedField(String name, String fieldName)
{
- List field = (List)getGeneratedFieldsMap().get(
+ List field = getGeneratedFieldsMap().get(
Arrays.asList(new String[]{name, fieldName}));
return ((field != null) ?
diff --git a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/LogHelperMappingConversion.java b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/LogHelperMappingConversion.java
deleted file mode 100644
index 4a029f868f3..00000000000
--- a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/LogHelperMappingConversion.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v. 2.0, which is available at
- * http://www.eclipse.org/legal/epl-2.0.
- *
- * This Source Code may also be made available under the following Secondary
- * Licenses when the conditions for such availability set forth in the
- * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
- * version 2 with the GNU Classpath Exception, which is available at
- * https://www.gnu.org/software/classpath/license.html.
- *
- * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
- */
-
-/*
- * LogHelperMappingConversion.java
- *
- * Created on June 9, 2004
- */
-
-
-package com.sun.jdo.api.persistence.mapping.ejb;
-
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
-/**
- *
- * @author Jie Leng
- */
-class LogHelperMappingConversion {
-
- /** The component name for this component */
- private static final String componentName = "mapping.conversion"; // NOI18N
-
- /** The class loader for this component */
- private static final ClassLoader loader =
- LogHelperMappingConversion.class.getClassLoader();
-
- /** The bundle name for this component */
- private static final String bundleName =
- "com.sun.jdo.api.persistence.mapping.ejb.Bundle"; // NOI18N
-
- /**
- * @return The logger for the mapping generator component.
- */
- static Logger getLogger() {
- return LogHelper.getLogger(componentName, bundleName, loader);
- }
-}
diff --git a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingFile.java b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingFile.java
index 00e63b5aca7..c1c2dc68c90 100644
--- a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingFile.java
+++ b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingFile.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingFile.java
- *
- * Created on February 1, 2002, 9:47 PM
- */
-
package com.sun.jdo.api.persistence.mapping.ejb;
import com.sun.jdo.api.persistence.mapping.ejb.beans.CheckVersionOfAccessedInstances;
@@ -48,14 +43,13 @@
import com.sun.jdo.api.persistence.model.mapping.impl.MappingFieldElementImpl;
import com.sun.jdo.api.persistence.model.mapping.impl.MappingRelationshipElementImpl;
import com.sun.jdo.spi.persistence.utility.StringHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.lang.System.Logger;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -73,45 +67,44 @@
import org.netbeans.modules.dbschema.UniqueKeyElement;
import org.netbeans.modules.schema2beans.Schema2BeansException;
-/** This class supports the conversion between the iAS mapping file
+import static com.sun.jdo.api.persistence.mapping.ejb.ConversionHelper.MANY;
+import static com.sun.jdo.api.persistence.mapping.ejb.ConversionHelper.ONE;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.TRACE;
+import static java.lang.System.Logger.Level.WARNING;
+
+/**
+ * This class supports the conversion between the iAS mapping file
* format and the object used to represent that mapping to support
* the iAS EJBC process and iAS CMP run-time.
*
- * @author vbk
- * @version 1.0
+ * @author vbk 2002
*/
public class MappingFile {
- private static final String JAVA_TYPE_SET = "java.util.Set"; //NOI18N
- private static final String JAVA_TYPE_COLLECTION = "java.util.Collection"; //NOI18N
- private static final List types = new ArrayList();
+ private static final String JAVA_TYPE_SET = "java.util.Set";
+ private static final String JAVA_TYPE_COLLECTION = "java.util.Collection";
+ private static final List TYPES = new ArrayList<>();
/** Definitive location for a mapping file in an ejb-jar file. */
public static final String DEFAULT_LOCATION_IN_EJB_JAR;
- /** The logger */
- private static final Logger logger =
- LogHelperMappingConversion.getLogger();
-
/**
* I18N message handler
*/
- private final static ResourceBundle messages = I18NHelper.loadBundle(
- MappingFile.class);
+ private final static ResourceBundle messages = I18NHelper.loadBundle(MappingFile.class);
+ private static final Logger LOG = System.getLogger(MappingFile.class.getName(), messages);
static {
- types.add(JAVA_TYPE_SET);
- types.add(JAVA_TYPE_COLLECTION);
-
- DEFAULT_LOCATION_IN_EJB_JAR = new StringBuffer(I18NHelper.getMessage(
- messages, "CONST_IAS_MAPPING_FILE_LOC")). //NOI18N
- append(File.separator).
- append(I18NHelper.getMessage(
- messages, "CONST_IAS_MAPPING_FILE")).toString(); //NOI18N
+ TYPES.add(JAVA_TYPE_SET);
+ TYPES.add(JAVA_TYPE_COLLECTION);
+
+ DEFAULT_LOCATION_IN_EJB_JAR = I18NHelper.getMessage(messages, "CONST_IAS_MAPPING_FILE_LOC") + File.separator
+ + I18NHelper.getMessage(messages, "CONST_IAS_MAPPING_FILE");
}
- private Map inverseRelationships = null;
- private Map namedGroups = null;
+ private Map inverseRelationships;
+ private Map namedGroups;
private int groupCount = MappingFieldElement.GROUP_INDEPENDENT;
private ClassLoader classLoader = null;
@@ -125,16 +118,15 @@ public class MappingFile {
*/
private ConversionHelper helper = null;
- private HashMap loadedSchema = new HashMap();
+ private HashMap loadedSchema = new HashMap<>();
/** Creates new MappingFile */
- public MappingFile() {
+ public MappingFile() {
classLoader = null;
}
/** Creates new MappingFile */
- public MappingFile(ClassLoader cl) {
- this();
+ public MappingFile(ClassLoader cl) {
classLoader = cl;
}
@@ -150,17 +142,16 @@ public MappingFile(ClassLoader cl) {
* @throws ModelException
* @throws ConversionException
*/
- public Map intoMappingClasses(SunCmpMappings content,
- ConversionHelper helper)
+ public Map intoMappingClasses(SunCmpMappings content, ConversionHelper helper)
throws DBException, ModelException, ConversionException {
- Map mces = new java.util.HashMap();
+ Map mces = new HashMap<>();
this.helper = helper;
boolean ensureValidation = helper.ensureValidation();
for (int i = 0; i < content.sizeSunCmpMapping(); i++) {
SunCmpMapping beanSet = content.getSunCmpMapping(i);
- inverseRelationships = new HashMap();
- namedGroups = new HashMap();
+ inverseRelationships = new HashMap<>();
+ namedGroups = new HashMap<>();
String schema = beanSet.getSchema();
if (helper.generateFields()) {
@@ -175,18 +166,11 @@ public Map intoMappingClasses(SunCmpMappings content,
MappingClassElement aTpMapping = null;
if (ensureValidation) {
aTpMapping = mapFieldsOfBean(beanMapping, schema);
- }
- else {
+ } else {
try {
aTpMapping = mapFieldsOfBean(beanMapping, schema);
- }
- catch (ConversionException t) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_CONV_EXC", //NOI18N
- t.toString()));
+ } catch (ConversionException t) {
+ LOG.log(DEBUG, "MESSAGE_CONV_EXC", t);
}
}
@@ -208,18 +192,15 @@ public Map intoMappingClasses(SunCmpMappings content,
* @throws ModelException
* @throws ConversionException
*/
- public Map intoMappingClasses(InputStream content, ConversionHelper helper)
+ public Map intoMappingClasses(InputStream content, ConversionHelper helper)
throws DBException, ModelException, ConversionException {
SunCmpMappings foo = null;
try {
foo = SunCmpMappings.createGraph(content);
- }
- catch (Schema2BeansException t) {
+ } catch (Schema2BeansException t) {
if (helper.ensureValidation()) {
throw new ConversionException(
- I18NHelper.getMessage(messages,
- "XML_ERROR_IN_MAPPING_FILE", //NOI18N
- DEFAULT_LOCATION_IN_EJB_JAR));
+ I18NHelper.getMessage(messages, "XML_ERROR_IN_MAPPING_FILE", DEFAULT_LOCATION_IN_EJB_JAR));
}
foo = SunCmpMappings.createGraph();
}
@@ -238,9 +219,8 @@ public Map intoMappingClasses(InputStream content, ConversionHelper helper)
* sending the data out on dest.
* @throws Schema2BeansException
*/
- public void fromMappingClasses(OutputStream dest, Map mappingClasses,
- ConversionHelper helper)
- throws IOException, Schema2BeansException {
+ public void fromMappingClasses(OutputStream dest, Map mappingClasses,
+ ConversionHelper helper) throws IOException, Schema2BeansException {
SunCmpMappings tmp = fromMappingClasses(mappingClasses, helper);
tmp.write(dest);
}
@@ -253,87 +233,68 @@ public void fromMappingClasses(OutputStream dest, Map mappingClasses,
* generation.
* @return The SunCmpMapping object that is equivelent to the
* collection of MappingClassElements.
- * throws Schema2BeansException
+ * @throws Schema2BeansException
*/
- public SunCmpMappings fromMappingClasses(Map mappingClasses,
- ConversionHelper helper) throws Schema2BeansException {
- Iterator keyIter = mappingClasses.keySet().iterator();
- Map mapOfMapping = new java.util.HashMap();
+ public SunCmpMappings fromMappingClasses(Map mappingClasses, ConversionHelper helper)
+ throws Schema2BeansException {
+ Iterator keyIter = mappingClasses.keySet().iterator();
+ Map mapOfMapping = new HashMap<>();
while (keyIter.hasNext()) {
- String ejbName = (String) keyIter.next();
- MappingClassElement mce = (MappingClassElement)
- mappingClasses.get(ejbName);
+ String ejbName = keyIter.next();
+ MappingClassElement mce = mappingClasses.get(ejbName);
EntityMapping beanMapping = new EntityMapping();
- if (null != mce) {
+ if (mce != null) {
setConsistency(mce, beanMapping);
String schemaName = mce.getDatabaseRoot();
- SunCmpMapping aMapping = (SunCmpMapping) mapOfMapping.get(
- schemaName);
+ SunCmpMapping aMapping = mapOfMapping.get(schemaName);
if (null == aMapping) {
aMapping = new SunCmpMapping();
aMapping.setSchema(schemaName);
mapOfMapping.put(schemaName, aMapping);
}
- List tables = mce.getTables();
- MappingTableElement primary = null;
- if (tables.size() > 0) {
- primary = (MappingTableElement) tables.get(0);
+ List tables = mce.getTables();
+ final MappingTableElement primary;
+ if (tables.isEmpty()) {
+ primary = null;
+ } else {
+ primary = tables.get(0);
beanMapping.setTableName(primary.getName());
}
beanMapping.setEjbName(ejbName);
- if (null != primary) {
- List refKeys = primary.getReferencingKeys();
+ if (primary != null) {
+ List refKeys = primary.getReferencingKeys();
for (int i = 0; refKeys != null && i < refKeys.size(); i++) {
SecondaryTable sT = new SecondaryTable();
- MappingReferenceKeyElement mrke =
- (MappingReferenceKeyElement) refKeys.get(i);
+ MappingReferenceKeyElement mrke = refKeys.get(i);
MappingTableElement mte = mrke.getTable();
- if (null != mte) {
+ if (mte != null) {
sT.setTableName(mte.getName());
- List cpnames = mrke.getColumnPairNames();
+ List cpnames = mrke.getColumnPairNames();
boolean hasPairs = false;
- for (int j = 0; cpnames != null &&
- j < cpnames.size(); j++) {
- List token =
- StringHelper.separatedListToArray((String)cpnames.get(j),";"); //NOI18N
+ for (int j = 0; cpnames != null && j < cpnames.size(); j++) {
+ List token = StringHelper.separatedListToArray(cpnames.get(j), ";");
ColumnPair cp = new ColumnPair();
- Iterator iter = token.iterator();
+ Iterator iter = token.iterator();
while (iter.hasNext()) {
- String columnName = (String)iter.next();
+ String columnName = iter.next();
cp.addColumnName(columnName);
}
sT.addColumnPair(cp);
hasPairs = true;
}
- if (hasPairs)
+ if (hasPairs) {
beanMapping.addSecondaryTable(sT);
- else
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "WARN_ILLEGAL_PAIR", //NOI18N
- new Object [] {ejbName, mte.getName(), cpnames}));
- }
- else {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "WARN_MISSING_TABLE", //NOI18N
- new Object [] {ejbName, primary.getName()}));
+ } else {
+ LOG.log(DEBUG, "WARN_ILLEGAL_PAIR", ejbName, mte.getName(), cpnames);
+ }
+ } else {
+ LOG.log(DEBUG, "WARN_MISSING_TABLE", ejbName, primary.getName());
}
}
- }
- else {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "WARN_NO_PRIMARY", //NOI18N
- ejbName));
+ } else {
+ LOG.log(DEBUG, "WARN_NO_PRIMARY", ejbName);
}
// transform the field mappings
@@ -346,8 +307,9 @@ public SunCmpMappings fromMappingClasses(Map mappingClasses,
pfields = pce.getFields();
}
int len = 0;
- if (null != pfields)
+ if (pfields != null) {
len = pfields.length;
+ }
for (int i = 0; i < len; i++) {
PersistenceFieldElement pfield = pfields[i];
String fieldName = pfield.getName();
@@ -355,29 +317,29 @@ public SunCmpMappings fromMappingClasses(Map mappingClasses,
continue;
}
if (pfield instanceof RelationshipElement) {
- MappingRelationshipElement mre =
- (MappingRelationshipElement) mce.getField(fieldName);
+ MappingRelationshipElement mre = (MappingRelationshipElement) mce.getField(fieldName);
MappingFieldElement mfe = mre;
CmrFieldMapping cfm = new CmrFieldMapping();
cfm.setCmrFieldName(fieldName);
- List cols = null;
- if (null != mfe) {
+ List cols = null;
+ if (mfe != null) {
cols = mfe.getColumns();
int fgVal = mfe.getFetchGroup();
setFetchedWith(cfm, fgVal);
}
for (int j = 0; null != cols && j < cols.size(); j++) {
- String cpstring = (String) cols.get(j);
+ String cpstring = cols.get(j);
int slen = cpstring.indexOf(';');
ColumnPair cp = new ColumnPair();
cp.addColumnName(cpstring.substring(0,slen));
cp.addColumnName(cpstring.substring(slen+1));
cfm.addColumnPair(cp);
}
- if (null != mre)
+ if (mre != null) {
cols = mre.getAssociatedColumns();
+ }
for (int j = 0; null != cols && j < cols.size(); j++) {
- String cpstring = (String) cols.get(j);
+ String cpstring = cols.get(j);
int slen = cpstring.indexOf(';');
ColumnPair cp = new ColumnPair();
cp.addColumnName(cpstring.substring(0,slen));
@@ -385,17 +347,16 @@ public SunCmpMappings fromMappingClasses(Map mappingClasses,
cfm.addColumnPair(cp);
}
beanMapping.addCmrFieldMapping(cfm);
- }
- else {
+ } else {
MappingFieldElement mfe = mce.getField(fieldName);
CmpFieldMapping cfm = new CmpFieldMapping();
cfm.setFieldName(fieldName);
- List cols = null;
- if (null != mfe) {
+ List cols = null;
+ if (mfe != null) {
cols = mfe.getColumns();
for (int j = 0; null != cols &&
j < cols.size(); j++) {
- cfm.addColumnName((String)cols.get(j));
+ cfm.addColumnName(cols.get(j));
}
int fgVal = mfe.getFetchGroup();
setFetchedWith(cfm,fgVal);
@@ -408,9 +369,9 @@ public SunCmpMappings fromMappingClasses(Map mappingClasses,
}
SunCmpMappings retVal = null;
retVal = new SunCmpMappings();
- Iterator mapOfMappingIter = mapOfMapping.values().iterator();
+ Iterator mapOfMappingIter = mapOfMapping.values().iterator();
while (mapOfMappingIter.hasNext()) {
- SunCmpMapping aVal = (SunCmpMapping) mapOfMappingIter.next();
+ SunCmpMapping aVal = mapOfMappingIter.next();
retVal.addSunCmpMapping(aVal);
}
return retVal;
@@ -424,7 +385,7 @@ public SunCmpMappings fromMappingClasses(Map mappingClasses,
private void setFetchedWith(HasFetchedWith cfm, int fgVal) {
FetchedWith fw = new FetchedWith();
if (fgVal <= MappingFieldElement.GROUP_INDEPENDENT) {
- String key = "IndependentFetchGroup"+fgVal; //NOI18N
+ String key = "IndependentFetchGroup"+fgVal;
fw.setNamedGroup(key);
}
else if (fgVal == MappingFieldElement.GROUP_DEFAULT) {
@@ -460,77 +421,49 @@ else if (fgVal == MappingFieldElement.GROUP_NONE) {
* @throws ModelException
* @throws ConversionException
*/
- private MappingClassElement mapFieldsOfBean(EntityMapping mapping,
- String schemaArg)
+ private MappingClassElement mapFieldsOfBean(EntityMapping mapping, String schemaArg)
throws DBException, ModelException, ConversionException {
-
String beanName = mapping.getEjbName();
- MappingClassElement mce = null;
- List tablesOfBean = new ArrayList();
- Map knownTables = new HashMap();
+ List tablesOfBean = new ArrayList<>();
+ Map knownTables = new HashMap<>();
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_START_BEAN", //NOI18N
- beanName));
+ LOG.log(DEBUG, "MESSAGE_START_BEAN", beanName);
String jdoClassName = helper.getMappedClassName(beanName);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_JDOCLASS_NAME", //NOI18N
- beanName, jdoClassName));
+ LOG.log(DEBUG, "MESSAGE_JDOCLASS_NAME", beanName, jdoClassName);
- if (null == jdoClassName) {
- throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_INVALID_CLASS", //NOI18N
- beanName));
+ if (jdoClassName == null) {
+ throw new ConversionException(I18NHelper.getMessage(messages, "ERR_INVALID_CLASS", beanName));
}
// create the mapping class element and its children
- PersistenceClassElementImpl persistElImpl =
- new PersistenceClassElementImpl(jdoClassName);
- persistElImpl.setKeyClass(jdoClassName+".Oid"); //NOI18N
- mce = new MappingClassElementImpl(
- new PersistenceClassElement(persistElImpl));
-
- SchemaElement schema = null;
-
- // Assign the schema
- if (!StringHelper.isEmpty(schemaArg))
- schema = setDatabaseRoot(mce, schemaArg,
- helper.ensureValidation());
+ final PersistenceClassElementImpl persistElImpl = new PersistenceClassElementImpl(jdoClassName);
+ persistElImpl.setKeyClass(jdoClassName + ".Oid");
+ MappingClassElement mce = new MappingClassElementImpl(new PersistenceClassElement(persistElImpl));
+ final SchemaElement schema;
+ if (StringHelper.isEmpty(schemaArg)) {
+ schema = null;
+ } else {
+ schema = setDatabaseRoot(mce, schemaArg, helper.ensureValidation());
+ }
+ LOG.log(TRACE, () -> "schema=" + schema);
// Map the table information
// Ensure the bean is mapped to a primary table.
if (!StringHelper.isEmpty(mapping.getTableName())) {
-
- mapPrimaryTable(mapping, mce,
- schema, knownTables, tablesOfBean);
- mapSecondaryTables(mapping, mce,
- schema, knownTables, tablesOfBean);
+ mapPrimaryTable(mapping, mce, schema, knownTables, tablesOfBean);
+ mapSecondaryTables(mapping, mce, schema, knownTables, tablesOfBean);
}
- ColumnElement candidatePK = null;
+ ColumnElement candidatePK = mapNonRelationshipFields(mapping, mce, beanName, schema, knownTables);
// map the simple fields.
- candidatePK = mapNonRelationshipFields(mapping, mce,
- beanName, schema, knownTables);
-
- createMappingForUnknownPKClass(mapping, mce,
- beanName, candidatePK);
+ createMappingForUnknownPKClass(mapping, mce, beanName, candidatePK);
- createMappingForConsistency(mapping, mce,
- beanName, knownTables);
+ createMappingForConsistency(mapping, mce, beanName, knownTables);
// map the relationship fields.
- mapRelationshipFields(mapping, mce,
- beanName, schema, knownTables, tablesOfBean);
+ mapRelationshipFields(mapping, mce, beanName, schema, knownTables, tablesOfBean);
// map any unmapped fields.
mapUnmappedFields(mce, beanName);
@@ -557,7 +490,7 @@ private void createMappingForUnknownPKClass(EntityMapping mapping,
if (helper.generateFields()
&& helper.applyDefaultUnknownPKClassStrategy(beanName)) {
- if (null != candidatePK) {
+ if (candidatePK != null) {
String fieldName = helper.getGeneratedPKFieldName();
// Fix later. Since mapping and persistence classes in the
@@ -565,19 +498,13 @@ private void createMappingForUnknownPKClass(EntityMapping mapping,
// put pce in a map at pce creation time for persistence
// class look up later to avoid a cast
// to MappingClassElementImpl.
- PersistenceFieldElement pfe = createPersistenceField(mce,
- fieldName);
+ PersistenceFieldElement pfe = createPersistenceField(mce, fieldName);
pfe.setKey(true);
createMappingField(mce, fieldName, candidatePK);
- }
- else {
+ } else {
// There is no column which meets primary key criteria.
// Report error.
- throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "WARN_NO_PKCOLUMN", //NOI18N
- primaryTableName));
+ throw new ConversionException(I18NHelper.getMessage(messages, "WARN_NO_PKCOLUMN", primaryTableName));
}
}
}
@@ -597,11 +524,11 @@ private void createMappingForUnknownPKClass(EntityMapping mapping,
private void createMappingForConsistency(EntityMapping mapping,
MappingClassElement mce,
String beanName,
- Map knownTables)
+ Map knownTables)
throws ModelException, DBException, ConversionException {
// load the consistency information
- List versionColumns = loadConsistency(mapping, mce);
+ List versionColumns = loadConsistency(mapping, mce);
// If the consistency level is version consistency, the version field
// is always created, independent of the ConversionHelper's value for
@@ -616,12 +543,11 @@ private void createMappingForConsistency(EntityMapping mapping,
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "ERR_INVALID_VERSION_COLUMNS")); //NOI18N
+ "ERR_INVALID_VERSION_COLUMNS"));
}
- String versionColumn = (String)versionColumns.get(0);
+ String versionColumn = versionColumns.get(0);
- String sourceTableName = getTableName(versionColumn,
- primaryTableName);
+ String sourceTableName = getTableName(versionColumn, primaryTableName);
// we do not support version column from secondary table
// in 8.1 release
@@ -629,33 +555,29 @@ private void createMappingForConsistency(EntityMapping mapping,
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "WARN_VERSION_COLUMN_INVALID_TABLE", //NOI18N
+ "WARN_VERSION_COLUMN_INVALID_TABLE",
primaryTableName, beanName, versionColumn));
}
- TableElement sourceTableEl = (TableElement) knownTables.get(
- sourceTableName);
+ TableElement sourceTableEl = knownTables.get(sourceTableName);
String versionColumnName = getColumnName(versionColumn);
- ColumnElement versionCol = getColumnElement(sourceTableEl,
- DBIdentifier.create(versionColumnName), helper);
+ ColumnElement versionCol = getColumnElement(sourceTableEl, DBIdentifier.create(versionColumnName), helper);
- if (null != versionCol) {
+ if (versionCol != null) {
// Since 8.1 release only support one version column per bean,
// use prefix as the version field name
String fieldName = helper.getGeneratedVersionFieldNamePrefix();
createPersistenceField(mce, fieldName);
- MappingFieldElement mfe = createMappingField(mce, fieldName,
- versionCol);
+ MappingFieldElement mfe = createMappingField(mce, fieldName, versionCol);
mfe.setVersion(true);
- }
- else {
+ } else {
// There is no version column.
// Report error.
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "WARN_VERSION_COLUMN_MISSING", //NOI18N
+ "WARN_VERSION_COLUMN_MISSING",
primaryTableName, beanName));
}
}
@@ -679,7 +601,7 @@ private ColumnElement mapNonRelationshipFields(EntityMapping mapping,
MappingClassElement mce,
String beanName,
SchemaElement schema,
- Map knownTables)
+ Map knownTables)
throws DBException, ModelException, ConversionException {
CmpFieldMapping [] mapOfFields = mapping.getCmpFieldMapping();
@@ -687,9 +609,7 @@ private ColumnElement mapNonRelationshipFields(EntityMapping mapping,
ColumnElement candidatePK = null;
// get candidate column only used for unknown primary key
- if (helper.generateFields()
- && helper.applyDefaultUnknownPKClassStrategy(beanName)) {
-
+ if (helper.generateFields() && helper.applyDefaultUnknownPKClassStrategy(beanName)) {
candidatePK = getCandidatePK(schema, primaryTableName);
}
@@ -697,46 +617,27 @@ private ColumnElement mapNonRelationshipFields(EntityMapping mapping,
CmpFieldMapping mapForOneField = mapOfFields[i];
String fieldName = mapForOneField.getFieldName();
- if (!validateField(mce, beanName, fieldName,
- helper.ensureValidation())) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "WARN_INVALID_FIELD", //NOI18N
- beanName, fieldName));
-
+ if (!validateField(mce, beanName, fieldName, helper.ensureValidation())) {
+ LOG.log(DEBUG, "WARN_INVALID_FIELD", beanName, fieldName);
continue;
}
String columnNames[] = mapForOneField.getColumnName();
- MappingFieldElement mfe = createUnmappedField(mce, beanName,
- fieldName);
+ MappingFieldElement mfe = createUnmappedField(mce, beanName, fieldName);
boolean fieldMappedToABlob = false;
for (int j = 0; j < columnNames.length; j++) {
- String sourceTableName = getTableName(columnNames[j],
- primaryTableName);
+ String sourceTableName = getTableName(columnNames[j], primaryTableName);
if (null == sourceTableName) {
- throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_UNDEFINED_TABLE")); //NOI18N
+ throw new ConversionException(I18NHelper.getMessage(messages, "ERR_UNDEFINED_TABLE"));
}
String sourceColumnName = getColumnName(columnNames[j]);
// get the table element
- TableElement sourceTableEl = getTableElement(sourceTableName,
- knownTables, schema);
- ColumnElement aCol = getColumnElement(sourceTableEl,
- DBIdentifier.create(sourceColumnName), helper);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_ADD_COLUMN", //NOI18N
- new Object [] {aCol, fieldName}));
+ TableElement sourceTableEl = getTableElement(sourceTableName, knownTables, schema);
+ ColumnElement aCol = getColumnElement(sourceTableEl, DBIdentifier.create(sourceColumnName), helper);
+ LOG.log(DEBUG, "MESSAGE_ADD_COLUMN", aCol, fieldName);
// If candidatePK is mapped to a field, then it can not
// treated as a primary key for unknown primary key
@@ -779,40 +680,32 @@ private void mapRelationshipFields(EntityMapping mapping,
MappingClassElement mce,
String beanName,
SchemaElement schema,
- Map knownTables,
- List tablesOfBean)
+ Map knownTables,
+ List tablesOfBean)
throws ModelException, DBException, ConversionException {
String primaryTableName = mapping.getTableName();
CmrFieldMapping mapOfRelations[] = mapping.getCmrFieldMapping();
PersistenceClassElement pce = ((MappingClassElementImpl)mce).getPersistenceElement();
- for (int i = 0; mapOfRelations != null && i < mapOfRelations.length;
- i++) {
+ for (int i = 0; mapOfRelations != null && i < mapOfRelations.length; i++) {
CmrFieldMapping aRelation = mapOfRelations[i];
String fieldName = aRelation.getCmrFieldName();
if (!validateField(mce, beanName, fieldName, helper.ensureValidation())) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "WARN_INVALID_CMRFIELD", //NOI18N
- beanName, fieldName));
+ LOG.log(DEBUG, "WARN_INVALID_CMRFIELD", beanName, fieldName);
continue;
}
- RelationshipElement rel = new RelationshipElement(
- new RelationshipElementImpl(fieldName), pce);
- MappingRelationshipElement mre =
- new MappingRelationshipElementImpl(fieldName, mce);
+ RelationshipElement rel = new RelationshipElement(new RelationshipElementImpl(fieldName), pce);
+ MappingRelationshipElement mre = new MappingRelationshipElementImpl(fieldName, mce);
// Register the inverse RelationshipElement
registerInverseRelationshipElement(rel, beanName, fieldName);
final ColumnPair pairs[] = aRelation.getColumnPair();
- final String relationId = mapping.getEjbName() + "_Relationship_" + i; //NOI18N
- Collection primaryTableColumns = convertToColumnPairElements(
+ final String relationId = mapping.getEjbName() + "_Relationship_" + i;
+ List primaryTableColumns = convertToColumnPairElements(
pairs,
primaryTableName, schema, knownTables, tablesOfBean,
relationId,
@@ -870,25 +763,29 @@ private void setConsistency(MappingClassElement mce,
c.setLockWhenModified(true);
c.setCheckAllAtCommit(true);
}
- if (MappingClassElement.LOCK_WHEN_MODIFIED_CONSISTENCY == consistency)
+ if (MappingClassElement.LOCK_WHEN_MODIFIED_CONSISTENCY == consistency) {
c.setLockWhenModified(true);
- if (MappingClassElement.CHECK_ALL_AT_COMMIT_CONSISTENCY == consistency)
+ }
+ if (MappingClassElement.CHECK_ALL_AT_COMMIT_CONSISTENCY == consistency) {
c.setCheckAllAtCommit(true);
- if (MappingClassElement.LOCK_WHEN_LOADED_CONSISTENCY == consistency)
+ }
+ if (MappingClassElement.LOCK_WHEN_LOADED_CONSISTENCY == consistency) {
c.setLockWhenLoaded(true);
- if (MappingClassElement.CHECK_MODIFIED_AT_COMMIT_CONSISTENCY == consistency)
+ }
+ if (MappingClassElement.CHECK_MODIFIED_AT_COMMIT_CONSISTENCY == consistency) {
c.setCheckModifiedAtCommit(true);
+ }
if (MappingClassElement.VERSION_CONSISTENCY == consistency) {
CheckVersionOfAccessedInstances versionIns =
new CheckVersionOfAccessedInstances();
- Iterator iter = mce.getVersionFields().iterator();
+ Iterator iter = mce.getVersionFields().iterator();
while (iter.hasNext()) {
- List columnNames = ((MappingFieldElement)iter.next()).
- getColumns();
+ List columnNames = iter.next().getColumns();
// vesion field only allow to map to one column
- if (columnNames != null && columnNames.size() > 0)
- versionIns.addColumnName((String)columnNames.get(0));
+ if (columnNames != null && columnNames.size() > 0) {
+ versionIns.addColumnName(columnNames.get(0));
+ }
}
c.setCheckVersionOfAccessedInstances(versionIns);
}
@@ -905,7 +802,7 @@ private void setConsistency(MappingClassElement mce,
* @throws ModelException
* @throws ConversionException
*/
- private List loadConsistency(EntityMapping mapping, MappingClassElement mce)
+ private List loadConsistency(EntityMapping mapping, MappingClassElement mce)
throws ModelException, ConversionException {
Consistency c = mapping.getConsistency();
if (null == c) {
@@ -913,39 +810,32 @@ private List loadConsistency(EntityMapping mapping, MappingClassElement mce)
}
else {
CheckVersionOfAccessedInstances versionIns =
- (CheckVersionOfAccessedInstances)
c.getCheckVersionOfAccessedInstances();
- if (c.isCheckModifiedAtCommit())
- mce.setConsistencyLevel(
- MappingClassElement.CHECK_MODIFIED_AT_COMMIT_CONSISTENCY);
- else if(c.isLockWhenLoaded())
- mce.setConsistencyLevel(
- MappingClassElement.LOCK_WHEN_LOADED_CONSISTENCY);
- else if(c.isCheckAllAtCommit())
- mce.setConsistencyLevel(
- MappingClassElement.CHECK_ALL_AT_COMMIT_CONSISTENCY);
- else if(c.isLockWhenModified())
- mce.setConsistencyLevel(
- MappingClassElement.LOCK_WHEN_MODIFIED_CONSISTENCY);
- else if(c.isLockWhenModified() && c.isCheckAllAtCommit())
- mce.setConsistencyLevel(MappingClassElement.
- LOCK_WHEN_MODIFIED_CHECK_ALL_AT_COMMIT_CONSISTENCY);
- else if(c.isNone())
+ if (c.isCheckModifiedAtCommit()) {
+ mce.setConsistencyLevel(MappingClassElement.CHECK_MODIFIED_AT_COMMIT_CONSISTENCY);
+ } else if (c.isLockWhenLoaded()) {
+ mce.setConsistencyLevel(MappingClassElement.LOCK_WHEN_LOADED_CONSISTENCY);
+ } else if (c.isCheckAllAtCommit()) {
+ mce.setConsistencyLevel(MappingClassElement.CHECK_ALL_AT_COMMIT_CONSISTENCY);
+ } else if (c.isLockWhenModified()) {
+ mce.setConsistencyLevel(MappingClassElement.LOCK_WHEN_MODIFIED_CONSISTENCY);
+ } else if (c.isLockWhenModified() && c.isCheckAllAtCommit()) {
+ mce.setConsistencyLevel(MappingClassElement.LOCK_WHEN_MODIFIED_CHECK_ALL_AT_COMMIT_CONSISTENCY);
+ } else if (c.isNone()) {
mce.setConsistencyLevel(MappingClassElement.NONE_CONSISTENCY);
- else if (versionIns != null) {
+ } else if (versionIns != null) {
mce.setConsistencyLevel(MappingClassElement.VERSION_CONSISTENCY);
- List versionColumns = new ArrayList();
+ List versionColumns = new ArrayList<>();
for (int i = 0; i < versionIns.sizeColumnName(); i++) {
versionColumns.add(versionIns.getColumnName(i));
}
return versionColumns;
- }
- else {
+ } else {
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "ERR_INVALID_CONSISTENCY_VALUE", mce)); //NOI18N
+ "ERR_INVALID_CONSISTENCY_VALUE", mce));
}
}
return null;
@@ -967,14 +857,12 @@ else if (versionIns != null) {
private void mapPrimaryTable(EntityMapping mapping,
MappingClassElement mce,
SchemaElement schema,
- Map knownTables,
- List tablesOfBean)
+ Map knownTables,
+ List tablesOfBean)
throws DBException, ModelException, ConversionException {
String primaryTableName = mapping.getTableName();
- TableElement primTabEl = getTableElement(primaryTableName, knownTables, schema);
-
- mce.addTable(primTabEl);
+ mce.addTable(getTableElement(primaryTableName, knownTables, schema));
tablesOfBean.add(primaryTableName);
}
@@ -986,33 +874,25 @@ private void mapPrimaryTable(EntityMapping mapping,
* @throws DBException
* @throws ConversionException
*/
- private ColumnElement getCandidatePK(SchemaElement schema,
- String primaryTableName)
+ private ColumnElement getCandidatePK(SchemaElement schema, String primaryTableName)
throws DBException, ConversionException {
- ColumnElement candidatePK = null;
- TableElement primTabEl = getTableElement(schema,
- DBIdentifier.create(primaryTableName), helper);
+ TableElement primTabEl = getTableElement(schema, DBIdentifier.create(primaryTableName));
// Check if the candidatePK is really satisfying primary key
// criteria. It will be used only for unknown primary key.
UniqueKeyElement uke = primTabEl.getPrimaryKey();
-
- if (null != uke) {
+ ColumnElement candidatePK = null;
+ if (uke != null) {
ColumnElement cols[] = uke.getColumns();
if (null != cols && 1 == cols.length) {
candidatePK = cols[0];
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_CANDIDATE_PK", //NOI18N
- candidatePK.getName()));
-
+ DBIdentifier name = candidatePK.getName();
+ LOG.log(DEBUG, "MESSAGE_CANDIDATE_PK", name);
Integer pre = candidatePK.getPrecision();
- if (null != candidatePK && !candidatePK.isNumericType()) {
+ if (!candidatePK.isNumericType()) {
candidatePK = null;
}
- if (null != candidatePK && (null != pre) && pre.intValue() < MINIMUM_PRECISION) {
+ if (candidatePK != null && (null != pre) && pre.intValue() < MINIMUM_PRECISION) {
candidatePK = null;
}
}
@@ -1040,16 +920,16 @@ private ColumnElement getCandidatePK(SchemaElement schema,
* @throws ModelException
* @throws ConversionException
*/
- private Collection convertToColumnPairElements(ColumnPair pairs[],
+ private List convertToColumnPairElements(ColumnPair pairs[],
String primaryTableName,
SchemaElement schema,
- Map knownTables,
- List tablesOfBean,
+ Map knownTables,
+ List tablesOfBean,
String relationId,
MappingRelationshipElement mre)
throws DBException, ModelException, ConversionException {
- Collection primaryTableColumns = new ArrayList();
+ List primaryTableColumns = new ArrayList<>();
boolean isJoin = false;
for (int i = 0; null != pairs && i < pairs.length; i++) {
@@ -1057,17 +937,14 @@ private Collection convertToColumnPairElements(ColumnPair pairs[],
ColumnPairElement cpe = new ColumnPairElement();
boolean localSet = false;
- cpe.setName(DBIdentifier.create(relationId + "_ColumnPair_" + i)); //NOI18N
+ cpe.setName(DBIdentifier.create(relationId + "_ColumnPair_" + i));
for (int j = 0; j < 2; j++) {
String columnName = pair.getColumnName(j);
- String sourceTableName = getTableName(columnName,
- primaryTableName);
+ String sourceTableName = getTableName(columnName, primaryTableName);
String sourceColumnName = getColumnName(columnName);
- TableElement sourceTableEl = getTableElement(sourceTableName,
- knownTables, schema);
- ColumnElement ce = getColumnElement(sourceTableEl,
- DBIdentifier.create(sourceColumnName), helper);
+ TableElement sourceTableEl = getTableElement(sourceTableName, knownTables, schema);
+ ColumnElement ce = getColumnElement(sourceTableEl, DBIdentifier.create(sourceColumnName), helper);
ce.toString();
// tablesOfBean stores the primary table and the secondary
@@ -1082,8 +959,7 @@ private Collection convertToColumnPairElements(ColumnPair pairs[],
// Remember local columns for lower bound determination.
primaryTableColumns.add(ce);
- }
- else {
+ } else {
// join table
isJoin = true;
@@ -1093,8 +969,7 @@ private Collection convertToColumnPairElements(ColumnPair pairs[],
if (cpe.getLocalColumn() == null) {
cpe.setLocalColumn(ce);
- }
- else {
+ } else {
cpe.setReferencedColumn(ce);
}
}
@@ -1102,12 +977,10 @@ private Collection convertToColumnPairElements(ColumnPair pairs[],
if (localSet) {
if (!isJoin) {
mre.addColumn(cpe);
- }
- else {
+ } else {
mre.addLocalColumn(cpe);
}
- }
- else if (isJoin) {
+ } else if (isJoin) {
mre.addAssociatedColumn(cpe);
}
}
@@ -1121,7 +994,6 @@ else if (isJoin) {
* be set to 1. To set the lower bound, we have to determine the
* dependent side of the relationship. We set the lower bound to 1
* based on the following rules:
- *
*
* If the non-nullable column is not part of the primary key.
* If the local side has got a foreign key.
@@ -1130,11 +1002,11 @@ else if (isJoin) {
*
*
* @param rel JDO relationship information being constructed.
- * @param primaryTableColumns Collection of all columns from the
- * current cmr definition that are part of the primary table.
+ * @param primaryTableColumns Collection of all columns from the
+ * current cmr definition that are part of the primary table.
* @param primaryTableName Name of the bean's primary table.
* @param knownTables A Map which contains primary and secondary tables
- * for beans in the set. Keys: table names Values: TableElement objects
+ * for beans in the set. Keys: table names Values: TableElement objects
* @param schema dbschema information for all beans.
* @param beanName Bean name.
* @param fieldName Relationship field name.
@@ -1143,22 +1015,17 @@ else if (isJoin) {
* @throws ConversionException
*/
private void setLowerBound(RelationshipElement rel,
- Collection primaryTableColumns,
+ List primaryTableColumns,
String primaryTableName,
SchemaElement schema,
- Map knownTables,
+ Map knownTables,
String beanName,
String fieldName)
throws ModelException, DBException,
ConversionException {
rel.setLowerBound(0);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_NULL", //NOI18N
- beanName, fieldName));
+ LOG.log(DEBUG, "MESSAGE_LWB_NULL", beanName, fieldName);
if (1 == rel.getUpperBound() && null != primaryTableName) {
@@ -1167,10 +1034,10 @@ private void setLowerBound(RelationshipElement rel,
knownTables, schema);
UniqueKeyElement pk = primaryTable.getPrimaryKey();
ForeignKeyElement fks[] = primaryTable.getForeignKeys();
- Iterator iter = primaryTableColumns.iterator();
+ Iterator iter = primaryTableColumns.iterator();
while (iter.hasNext() && 0 == rel.getLowerBound()) {
- ColumnElement ce = (ColumnElement) iter.next();
+ ColumnElement ce = iter.next();
if (!ce.isNullable()) {
isPartOfPrimaryKey |= isPartOfPrimaryKey(ce, pk);
@@ -1179,59 +1046,31 @@ private void setLowerBound(RelationshipElement rel,
// If the non-nullable column is not part of the primary key,
// this is the dependent side.
rel.setLowerBound(1);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_NOPK", //NOI18N
- beanName, fieldName));
- }
- // Check the foreign key constraint
- else if (isPartOfForeignKey(ce, fks)) {
+ LOG.log(DEBUG, "MESSAGE_LWB_NOPK", beanName, fieldName);
+ } else if (isPartOfForeignKey(ce, fks)) {
+ // Check the foreign key constraint
// If the non-nullable column is part of the foreign key,
// this is the dependent side.
rel.setLowerBound(1);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_FK", //NOI18N
- beanName, fieldName));
+ LOG.log(DEBUG, "MESSAGE_LWB_FK", beanName, fieldName);
}
}
}
- if (0 == rel.getLowerBound() && isPartOfPrimaryKey) {
+ if (rel.getLowerBound() == 0 && isPartOfPrimaryKey) {
// The lower bound is still unset and all local columns
// are part of the primary key.
if (primaryTableColumns.size() < pk.getColumns().length) {
// The local columns are a real subset of the primary key.
// ==> This must be the dependent side.
rel.setLowerBound(1);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_PKSUBSET", //NOI18N
- beanName, fieldName));
- }
- else if (isCascadeDelete(beanName, fieldName)) {
+ LOG.log(DEBUG, "MESSAGE_LWB_PKSUBSET", beanName, fieldName);
+ } else if (isCascadeDelete(beanName, fieldName)) {
// This relationship side is marked as dependent side by the user.
rel.setLowerBound(1);
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_CASCADE", //NOI18N
- beanName, fieldName));
- }
- else {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_LWB_NODEPENDENT", //NOI18N
- beanName, fieldName));
+ LOG.log(DEBUG, "MESSAGE_LWB_CASCADE", beanName, fieldName);
+ } else {
+ LOG.log(DEBUG, "MESSAGE_LWB_NODEPENDENT", beanName, fieldName);
}
}
}
@@ -1251,20 +1090,16 @@ else if (isCascadeDelete(beanName, fieldName)) {
* @exception DBException
* @exception ConversionException
*/
- private TableElement getTableElement(String tableName,
- Map knownTables,
- SchemaElement schema)
+ private TableElement getTableElement(String tableName, Map knownTables, SchemaElement schema)
throws DBException, ConversionException {
-
- TableElement te = (TableElement) knownTables.get(tableName);
-
- if (null == te) {
- te = getTableElement(schema, DBIdentifier.create(tableName),
- helper);
- knownTables.put(tableName, te);
+ final TableElement te = knownTables.get(tableName);
+ if (te != null) {
+ return te;
}
-
- return te;
+ final TableElement tableElement = getTableElement(schema, DBIdentifier.create(tableName));
+ LOG.log(DEBUG, () -> "Registering " + tableElement);
+ knownTables.put(tableName, tableElement);
+ return tableElement;
}
/**
@@ -1355,8 +1190,8 @@ private RelationshipElement registerInverseRelationshipElement(
RelationshipElement rel, String beanName, String fieldName)
throws ModelException {
- String key = beanName + "." + fieldName; //NOI18N
- RelationshipElement inverse = (RelationshipElement) inverseRelationships.get(key);
+ String key = beanName + "." + fieldName;
+ RelationshipElement inverse = inverseRelationships.get(key);
if (null == inverse) {
final String beanInField = helper.getRelationshipFieldContent(
@@ -1365,7 +1200,7 @@ private RelationshipElement registerInverseRelationshipElement(
fieldName);
if (null != beanInField && null != inverseField) {
- key = beanInField + "." + inverseField; //NOI18N
+ key = beanInField + "." + inverseField;
inverseRelationships.put(key, rel);
}
}
@@ -1389,35 +1224,25 @@ private RelationshipElement registerInverseRelationshipElement(
* @throws ModelException
* @throws ConversionException
*/
- private void setUpperBound(RelationshipElement rel,
- String beanName, String fieldName)
+ private void setUpperBound(RelationshipElement rel, String beanName, String fieldName)
throws ModelException, ConversionException {
- String beanInField = helper.getRelationshipFieldContent(beanName,
- fieldName);
+ String beanInField = helper.getRelationshipFieldContent(beanName, fieldName);
String classInJdoField = helper.getMappedClassName(beanInField);
String multiplicity = helper.getMultiplicity(beanName, fieldName);
// Set the upper bound.
- if (multiplicity.equals(helper.MANY)) {
+ if (multiplicity.equals(MANY)) {
rel.setUpperBound(Integer.MAX_VALUE);
rel.setElementClass(classInJdoField);
- String collectionClass = helper.getRelationshipFieldType(beanName,
- fieldName);
- if (types.contains(collectionClass)) {
+ String collectionClass = helper.getRelationshipFieldType(beanName, fieldName);
+ if (TYPES.contains(collectionClass)) {
rel.setCollectionClass(collectionClass);
- }
- else {
+ } else {
rel.setCollectionClass(null);
- if (logger.isLoggable(Logger.WARNING))
- logger.warning(
- I18NHelper.getMessage(
- messages,
- "WARN_INVALID_RELATIONSHIP_FIELDTYPE", //NOI18N
- beanName, fieldName, collectionClass));
+ LOG.log(WARNING, "WARN_INVALID_RELATIONSHIP_FIELDTYPE", beanName, fieldName, collectionClass);
}
- }
- else if (multiplicity.equals(helper.ONE)) {
+ } else if (multiplicity.equals(ONE)) {
rel.setUpperBound(1);
// Fix later. This code should be removed because in one side
// setElementClass should not be called.
@@ -1426,13 +1251,9 @@ else if (multiplicity.equals(helper.ONE)) {
// in the plugin which depends on the element class being set
// for a one side relationship.
rel.setElementClass(classInJdoField);
- }
- else {
+ } else {
throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_BAD_MULTIPLICTY", //NOI18N
- multiplicity, rel.getName()));
+ I18NHelper.getMessage(messages, "ERR_BAD_MULTIPLICTY", multiplicity, rel.getName()));
}
}
@@ -1454,40 +1275,33 @@ private void setCascadeDeleteAction(RelationshipElement rel,
throws ModelException {
if (helper.relatedObjectsAreDeleted(beanName, fieldName)) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine(
- I18NHelper.getMessage(
- messages,
- "MESSAGE_REL_OBJ_DEL", //NOI18N
- beanName, fieldName));
+ LOG.log(DEBUG, "MESSAGE_REL_OBJ_DEL", beanName, fieldName);
rel.setDeleteAction(RelationshipElement.CASCADE_ACTION);
}
}
- private SchemaElement setDatabaseRoot(MappingClassElement foo,
- String schemaElementValue, boolean strict)
+
+ private SchemaElement setDatabaseRoot(MappingClassElement mappingClassElement, String schemaElementValue, boolean strict)
throws ModelException, DBException, ConversionException {
+ LOG.log(DEBUG, () -> "Setting the database root: mappingClassElement=" + mappingClassElement
+ + ", schemaElementValue=" + schemaElementValue + ", strict=" + strict);
SchemaElement bar = null;
if (null != classLoader) {
- if (loadedSchema.get(schemaElementValue) == null) {
+ if (!loadedSchema.containsKey(schemaElementValue)) {
SchemaElement.removeFromCache(schemaElementValue);
loadedSchema.put(schemaElementValue, schemaElementValue);
}
- bar = SchemaElement.forName(schemaElementValue,classLoader);
- }
- else
+ bar = SchemaElement.forName(schemaElementValue, classLoader);
+ } else {
bar = SchemaElement.forName(schemaElementValue);
+ }
if (strict) {
if (bar == null) {
// Prepare for a schema related error
- throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_CANNOT_FIND_SCHEMA", //NOI18N
- new Object [] {schemaElementValue, classLoader}));
+ throw new ConversionException(I18NHelper.getMessage(messages, "ERR_CANNOT_FIND_SCHEMA",
+ new Object[] {schemaElementValue, classLoader}));
}
- }
- else {
+ } else {
if (null == bar) {
// conjure up a schema element and set its name...
// need to create a dummy for invalid mappings because the
@@ -1499,23 +1313,26 @@ private SchemaElement setDatabaseRoot(MappingClassElement foo,
bar.setName(n);
}
}
- foo.setDatabaseRoot(bar);
+ mappingClassElement.setDatabaseRoot(bar);
return bar;
}
+
private String getTableName(String columnName, String defaultName) {
String retVal = defaultName;
int len = columnName.lastIndexOf('.');
- if (len > 0)
+ if (len > 0) {
retVal = columnName.substring(0,len);
+ }
return retVal;
}
private String getColumnName(String columnName) {
String retVal = columnName;
int len = columnName.lastIndexOf('.');
- if (len > 0)
+ if (len > 0) {
retVal = columnName.substring(len+1);
+ }
return retVal;
}
@@ -1535,106 +1352,92 @@ private String getColumnName(String columnName) {
private void mapSecondaryTables(EntityMapping mapping,
MappingClassElement mce,
SchemaElement schema,
- Map knownTables,
- List tablesOfBean)
+ Map knownTables,
+ List tablesOfBean)
throws ModelException, DBException, ConversionException {
SecondaryTable [] tableList = mapping.getSecondaryTable();
- List tl = mce.getTables();
+ List tl = mce.getTables();
if (null != tl && tl.size() > 0 && null != tl.get(0)) {
- MappingTableElement primary = (MappingTableElement) tl.get(0);
+ MappingTableElement primary = tl.get(0);
for (int i = 0; null != tableList && i < tableList.length; i++) {
String tn = tableList[i].getTableName();
- if (StringHelper.isEmpty(tn))
+ if (StringHelper.isEmpty(tn)) {
continue;
- TableElement te = getTableElement(schema,
- DBIdentifier.create(tn.trim()), helper);
+ }
+ TableElement te = getTableElement(schema, DBIdentifier.create(tn.trim()));
ColumnPair pairs[] = tableList[i].getColumnPair();
int len = 0;
- if (null != pairs)
+ if (null != pairs) {
len = pairs.length;
+ }
if (0 == len) {
- if (logger.isLoggable(Logger.WARNING))
- logger.warning(
- I18NHelper.getMessage(
- messages,
- "WARN_NO_PAIRS", //NOI18N
- new Object [] {mce, tn}));
+ LOG.log(WARNING, "WARN_NO_PAIRS", mce, tn);
continue;
}
MappingReferenceKeyElement mrke = mce.addSecondaryTable(
primary,te);
for (int j = 0; null != pairs && j < pairs.length; j++) {
ColumnPairElement cpe = new ColumnPairElement();
- DBIdentifier dbId = DBIdentifier.create("SecondaryTable"+j); //NOI18N
+ DBIdentifier dbId = DBIdentifier.create("SecondaryTable"+j);
cpe.setName(dbId);
ColumnPair pair = pairs[j];
for (int k = 0; k < 2; k++) {
String nameOne = pair.getColumnName(k);
- String sourceTableName = getTableName(
- nameOne.trim(),
- primary.getName().toString());
+ String sourceTableName = getTableName(nameOne.trim(), primary.getName().toString());
String sourceColumnName = getColumnName(nameOne);
dbId = DBIdentifier.create(sourceTableName);
- TableElement sourceTableEl = getTableElement(schema,
- dbId, helper);
+ TableElement sourceTableEl = getTableElement(schema, dbId);
dbId = DBIdentifier.create(sourceColumnName);
- ColumnElement ce = getColumnElement(sourceTableEl,
- dbId, helper);
- if (k == 0)
+ ColumnElement ce = getColumnElement(sourceTableEl, dbId, helper);
+ if (k == 0) {
cpe.setLocalColumn(ce);
- else
+ } else {
cpe.setReferencedColumn(ce);
+ }
}
mrke.addColumnPair(cpe);
}
knownTables.put(tn,te);
tablesOfBean.add(tn);
}
+ } else {
+ throw new ConversionException(I18NHelper.getMessage(messages, "WARN_NOT_MAPPED_TO_PRIMARY", mce.getName()));
}
- else
- throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "WARN_NOT_MAPPED_TO_PRIMARY", //NOI18N
- mce.getName()));
}
private boolean validateField(MappingClassElement mce, String beanName,
String fieldName, boolean throwEx) throws ConversionException {
MappingFieldElement mfe = mce.getField(fieldName);
- if (null != mfe) {
- if (throwEx)
+ if (mfe != null) {
+ if (throwEx) {
throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_FIELD_MAPPED_TWICE", //NOI18N
- beanName, fieldName));
- else
+ I18NHelper.getMessage(messages, "ERR_FIELD_MAPPED_TWICE", beanName, fieldName));
+ } else {
return false;
+ }
}
- if (!helper.hasField(beanName,fieldName)) {
- if (throwEx)
+ if (!helper.hasField(beanName, fieldName)) {
+ if (throwEx) {
throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_INVALID_FIELD", //NOI18N
- beanName, fieldName));
- else
+ I18NHelper.getMessage(messages, "ERR_INVALID_FIELD", beanName, fieldName));
+ } else {
return false;
+ }
}
return true;
}
// loop through the mappings to create a hash from bean name to em objects
- private Map getBean2EntityMappingMap(SunCmpMapping beanSet) {
- Map retVal = new HashMap();
- EntityMapping [] entityMappingsInSet = beanSet.getEntityMapping();
+ private Map getBean2EntityMappingMap(SunCmpMapping beanSet) {
+ Map retVal = new HashMap<>();
+ EntityMapping[] entityMappingsInSet = beanSet.getEntityMapping();
int len = 0;
- if (null != entityMappingsInSet)
+ if (entityMappingsInSet != null) {
len = entityMappingsInSet.length;
+ }
for (int k = 0; k < len; k++) {
EntityMapping anEntityMapping = entityMappingsInSet[k];
String beanName = anEntityMapping.getEjbName();
@@ -1651,54 +1454,44 @@ private boolean completeCmrMappings(SunCmpMapping beanSet)
throws ConversionException {
// loop through the mappings to create a hash from bean name to em objects
- Map beanName2EntityMapping = getBean2EntityMappingMap(beanSet);
- Iterator emIter = beanName2EntityMapping.values().iterator();
+ Map beanName2EntityMapping = getBean2EntityMappingMap(beanSet);
+ Iterator emIter = beanName2EntityMapping.values().iterator();
boolean retVal = false;
- String errorMsg = I18NHelper.getMessage(
- messages,
- "ERR_BAD_CONVERSION_HELPER"); //NOI18N
+ String errorMsg = I18NHelper.getMessage(messages, "ERR_BAD_CONVERSION_HELPER");
while (emIter.hasNext()) {
- EntityMapping anEM = (EntityMapping) emIter.next();
+ EntityMapping anEM = emIter.next();
String beanName = anEM.getEjbName();
String pt = anEM.getTableName();
CmrFieldMapping[] cmrsInEM = anEM.getCmrFieldMapping();
int len = 0;
- if (null != cmrsInEM && !StringHelper.isEmpty(beanName))
+ if (null != cmrsInEM && !StringHelper.isEmpty(beanName)) {
len = cmrsInEM.length;
+ }
for (int i = 0; i < len; i++) {
String fieldName = cmrsInEM[i].getCmrFieldName();
if (!helper.hasField(beanName, fieldName)) {
- throw new ConversionException(I18NHelper.getMessage(
- messages,
- "WARN_INVALID_CMRFIELD", //NOI18N
- beanName, fieldName));
+ throw new ConversionException(
+ I18NHelper.getMessage(messages, "WARN_INVALID_CMRFIELD", beanName, fieldName));
}
fieldName.trim().charAt(0);
- String otherField = helper.getInverseFieldName(beanName,
- fieldName);
+ String otherField = helper.getInverseFieldName(beanName, fieldName);
if (otherField == null) {
throw new ConversionException(errorMsg);
}
- String otherBean = helper.getRelationshipFieldContent(beanName,
- fieldName);
+ String otherBean = helper.getRelationshipFieldContent(beanName, fieldName);
if (otherBean == null) {
throw new ConversionException(errorMsg);
}
- if (helper.isGeneratedRelationship(otherBean,otherField)) {
+ if (helper.isGeneratedRelationship(otherBean, otherField)) {
retVal = true;
- String otherBeanName = helper.getRelationshipFieldContent(
- beanName, fieldName);
+ String otherBeanName = helper.getRelationshipFieldContent(beanName, fieldName);
otherBeanName.trim().charAt(0);
- EntityMapping otherEM =
- (EntityMapping) beanName2EntityMapping.get(
- otherBeanName);
+ EntityMapping otherEM = beanName2EntityMapping.get(otherBeanName);
CmrFieldMapping inverseMapping = new CmrFieldMapping();
inverseMapping.setCmrFieldName(otherField);
- inverseMapping.setColumnPair(
- reverseCPArray(cmrsInEM[i].getColumnPair(), pt,
- beanName, fieldName));
+ inverseMapping.setColumnPair(reverseCPArray(cmrsInEM[i].getColumnPair(), pt, beanName, fieldName));
otherEM.addCmrFieldMapping(inverseMapping);
}
}
@@ -1712,18 +1505,13 @@ private ColumnPair[] reverseCPArray(ColumnPair[] cpa, String primeTable,
int len = (cpa == null) ? 0 : cpa.length;
if (len == 0) {
throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_COLUMN_PAIR_MISSING", //NOI18N
- beanName, fieldName));
+ I18NHelper.getMessage(messages, "ERR_COLUMN_PAIR_MISSING", beanName, fieldName));
}
- ColumnPair [] retVal = new ColumnPair[len];
+ ColumnPair[] retVal = new ColumnPair[len];
for (int index = 0; index < len; index++) {
retVal[index] = new ColumnPair();
- retVal[index].addColumnName(
- qualify(primeTable,cpa[index].getColumnName(1)));
- retVal[index].addColumnName(
- qualify(primeTable,cpa[index].getColumnName(0)));
+ retVal[index].addColumnName(qualify(primeTable, cpa[index].getColumnName(1)));
+ retVal[index].addColumnName(qualify(primeTable, cpa[index].getColumnName(0)));
}
return retVal;
}
@@ -1731,49 +1519,44 @@ private ColumnPair[] reverseCPArray(ColumnPair[] cpa, String primeTable,
private String qualify(String tn, String cn) {
int tmp = cn.indexOf('.');
String retVal = cn;
- if (-1 == tmp)
+ if (-1 == tmp) {
retVal = tn + "." + cn; // NOI18N
+ }
return retVal;
}
- private TableElement getTableElement(SchemaElement schema,
- DBIdentifier dbId, ConversionHelper helper)
- throws DBException, ConversionException {
-
- TableElement retVal = ((schema != null) ?
- schema.getTable(dbId) : null);
- if (null == retVal && !helper.ensureValidation()) {
+ private TableElement getTableElement(SchemaElement schema, DBIdentifier dbId)
+ throws DBException, ConversionException {
+ TableElement table = schema == null ? null : schema.getTable(dbId);
+ if (table == null && !helper.ensureValidation()) {
// Need to create a dummy for invalid mappings because
// the mapping model setter methods don't accept
// strings even though that is what they store.
// Create the table and add it to the knownTables list
// for later
- retVal = new TableElement();
- retVal.setName(dbId);
- retVal.setDeclaringSchema(schema);
+ table = new TableElement();
+ table.setName(dbId);
+ table.setDeclaringSchema(schema);
org.netbeans.modules.dbschema.UniqueKeyElement tkey =
new org.netbeans.modules.dbschema.UniqueKeyElement();
ColumnElement fakeKeyCol = new ColumnElement();
- fakeKeyCol.setName(DBIdentifier.create(retVal.getName().getName()+ "."+"fookeyng")); //NOI18N
+ fakeKeyCol.setName(DBIdentifier.create(table.getName().getName()+ "."+"fookeyng"));
// Type numeric=2
fakeKeyCol.setType(2);
- fakeKeyCol.setPrecision(new Integer(MINIMUM_PRECISION));
+ fakeKeyCol.setPrecision(MINIMUM_PRECISION);
tkey.setPrimaryKey(true);
tkey.addColumn(fakeKeyCol);
- retVal.addColumn(fakeKeyCol);
- retVal.addKey(tkey);
+ table.addColumn(fakeKeyCol);
+ table.addKey(tkey);
}
- if (retVal == null) {
+ if (table == null) {
throw new ConversionException(
- I18NHelper.getMessage(
- messages,
- "ERR_INVALID_TABLE", //NOI18N
- new Object [] {dbId.getName(), schema}));
+ I18NHelper.getMessage(messages, "ERR_INVALID_TABLE", new Object[] {dbId.getName(), schema}));
}
- return retVal;
+ return table;
}
private ColumnElement getColumnElement(TableElement sourceTableEl,
@@ -1791,27 +1574,21 @@ private ColumnElement getColumnElement(TableElement sourceTableEl,
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "ERR_INVALID_COLUMN", //NOI18N
+ "ERR_INVALID_COLUMN",
new Object [] {sourceColumnName, sourceTableEl}));
}
return aCol;
}
private MappingFieldElement createUnmappedField(MappingClassElement mce,
- String beanName, String fieldName)
- throws ModelException {
-
- PersistenceClassElement pce = ((MappingClassElementImpl)mce).
- getPersistenceElement();
- PersistenceFieldElementImpl pfei =
- new PersistenceFieldElementImpl(fieldName);
- PersistenceFieldElement pfe =
- new PersistenceFieldElement(pfei, pce);
+ String beanName, String fieldName) throws ModelException {
+ PersistenceClassElement pce = ((MappingClassElementImpl) mce).getPersistenceElement();
+ PersistenceFieldElementImpl pfei = new PersistenceFieldElementImpl(fieldName);
+ PersistenceFieldElement pfe = new PersistenceFieldElement(pfei, pce);
- pfe.setKey(helper.isKey(beanName,fieldName,false));
+ pfe.setKey(helper.isKey(beanName, fieldName, false));
pce.addField(pfe);
- MappingFieldElement mfe = new MappingFieldElementImpl(fieldName, mce);
- return mfe;
+ return new MappingFieldElementImpl(fieldName, mce);
}
/**
@@ -1850,56 +1627,55 @@ private void setFetchGroup(FetchedWith fw, MappingFieldElement mfe,
throw new ConversionException(
I18NHelper.getMessage(
messages,
- "ERR_INVALID_FG_LEVEL", //NOI18N
- beanName, mfe.getName(), ""+level)); //NOI18N
+ "ERR_INVALID_FG_LEVEL",
+ beanName, mfe.getName(), ""+level));
}
mfe.setFetchGroup(level+1);
}
String ig = fw.getNamedGroup();
if (null != ig) {
- Integer fgval = (Integer) namedGroups.get(ig);
+ Integer fgval = namedGroups.get(ig);
if (null == fgval) {
- fgval = new Integer(groupCount--);
- namedGroups.put(ig,fgval);
+ fgval = Integer.valueOf(groupCount--);
+ namedGroups.put(ig, fgval);
}
mfe.setFetchGroup(fgval.intValue());
}
- if (fw.isNone())
+ if (fw.isNone()) {
mfe.setFetchGroup(MappingFieldElement.GROUP_NONE);
- if (fw.isDefault())
+ }
+ if (fw.isDefault()) {
mfe.setFetchGroup(MappingFieldElement.GROUP_DEFAULT);
- }
- else {
- if (mfe instanceof MappingRelationshipElement)
+ }
+ } else {
+ if (mfe instanceof MappingRelationshipElement) {
mfe.setFetchGroup(MappingFieldElement.GROUP_NONE);
- else {
- if (fieldMappedToABlob)
+ } else {
+ if (fieldMappedToABlob) {
mfe.setFetchGroup(MappingFieldElement.GROUP_NONE);
- else
+ } else {
mfe.setFetchGroup(MappingFieldElement.GROUP_DEFAULT);
+ }
}
}
}
private PersistenceFieldElement createPersistenceField(
MappingClassElement mce, String fieldName) throws ModelException {
- PersistenceClassElement pce =
- ((MappingClassElementImpl)mce).getPersistenceElement();
- PersistenceFieldElementImpl pfei =
- new PersistenceFieldElementImpl(fieldName);
- PersistenceFieldElement pfe =
- new PersistenceFieldElement(pfei, pce);
+ PersistenceClassElement pce = ((MappingClassElementImpl) mce).getPersistenceElement();
+ PersistenceFieldElementImpl pfei = new PersistenceFieldElementImpl(fieldName);
+ PersistenceFieldElement pfe = new PersistenceFieldElement(pfei, pce);
pce.addField(pfe);
return pfe;
}
- private MappingFieldElement createMappingField(MappingClassElement mce,
- String fieldName, ColumnElement col) throws ModelException {
- MappingFieldElement mfe =
- new MappingFieldElementImpl(fieldName, mce);
+ private MappingFieldElement createMappingField(MappingClassElement mce, String fieldName, ColumnElement col)
+ throws ModelException {
+ MappingFieldElement mfe = new MappingFieldElementImpl(fieldName, mce);
mce.addField(mfe);
- if (col != null)
+ if (col != null) {
mfe.addColumn(col);
+ }
return mfe;
}
}
diff --git a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingGenerator.java b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingGenerator.java
index 4bc12b43d17..7b69b719b12 100644
--- a/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingGenerator.java
+++ b/appserver/persistence/cmp/ejb-mapping/src/main/java/com/sun/jdo/api/persistence/mapping/ejb/MappingGenerator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingGenerator.java
- *
- * Created on Aug 18, 2003
- */
-
package com.sun.jdo.api.persistence.mapping.ejb;
import com.sun.jdo.api.persistence.mapping.ejb.beans.CmpFieldMapping;
@@ -35,6 +30,7 @@
import com.sun.jdo.api.persistence.model.mapping.MappingClassElement;
import com.sun.jdo.api.persistence.model.mapping.MappingFieldElement;
import com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator;
+import com.sun.jdo.spi.persistence.generator.database.DatabaseGenerator.NameTuple;
import com.sun.jdo.spi.persistence.generator.database.MappingPolicy;
import com.sun.jdo.spi.persistence.utility.JavaTypeHelper;
import com.sun.jdo.spi.persistence.utility.StringHelper;
@@ -63,15 +59,15 @@
* classes based on ejb-jar.xml, bean classes and policy by invoking the
* database generation backend.
*
- * @author Jie Leng
+ * @author Jie Leng 2003
*/
public class MappingGenerator {
// Since "_JDOState" is defined as private in IASEjbCMPEntityDescriptor,
// redefined here for passing it in DatabaseGenerator.
- private static final String CLASS_SUFFIX = "_JDOState"; // NOI18N
+ private static final String CLASS_SUFFIX = "_JDOState";
- private static final String FAKE_NAME = "fakename"; // NOI18N
+ private static final String FAKE_NAME = "fakename";
private final EJBInfoHelper infoHelper;
private final Model model;
@@ -85,7 +81,7 @@ public class MappingGenerator {
private boolean skipGeneratedFields = false;
//hold strong reference to mapping class elements
- private List strongRefs = new ArrayList();
+ private List strongRefs = new ArrayList<>();
/**
* Constructor
@@ -145,9 +141,9 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
// sun-cmp-mappings.xml does not exist, use DatabaseGenerator
// to generate sun-cmp-mappings.xml, *.dbschema
- List pcClasses = new ArrayList();
+ List pcClasses = new ArrayList<>();
sunCmpMappings = getPartialSunCmpMappings(pcClasses,
- (uniqueTableNames != null)? uniqueTableNames.booleanValue() : false);
+ uniqueTableNames == null ? false : uniqueTableNames.booleanValue());
// load real jdo model and fake mapping model in memory
ddHelper.setEnsureValidation(false);
@@ -155,6 +151,7 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
// create fake schema for partial mapping
SchemaElement fakeSchema = new SchemaElement(new SchemaElementImpl());
fakeSchema.setName(DBIdentifier.create(FAKE_NAME));
+ fakeSchema.setDriver(FAKE_NAME);
// add newly created fake schema to SchemaElement cache
SchemaElement.addToCache(fakeSchema);
@@ -163,11 +160,10 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
// from cache not from disk.
loadMappingClasses(sunCmpMappings, null);
- DatabaseGenerator.Results results = generateSchema(pcClasses,
- dbName, uniqueTableNames, userPolicy);
+ DatabaseGenerator.Results results = generateSchema(pcClasses, dbName, uniqueTableNames, userPolicy);
SchemaElement schema = results.getSchema();
- Set mappingClasses = results.getMappingClasses();
+ Set mappingClasses = results.getMappingClasses();
// remove fake schema from cache since the correct schema is generated.
SchemaElement.removeFromCache(FAKE_NAME);
@@ -187,19 +183,17 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
// Remove generated fields from jdo model and mapping
// model before returning the result.
if (skipGeneratedFields) {
- Iterator iter = mappingClasses.iterator();
+ Iterator iter = mappingClasses.iterator();
while (iter.hasNext()) {
- MappingClassElement mapClassElt = (MappingClassElement)iter.next();
+ MappingClassElement mapClassElt = iter.next();
if (mapClassElt != null) {
String className = mapClassElt.getName();
- String ejbName = nameMapper.getEjbNameForPersistenceClass(
- className);
+ String ejbName = nameMapper.getEjbNameForPersistenceClass(className);
- PersistenceClassElement pce = (PersistenceClassElement)
- model.getPersistenceClass(className);
+ PersistenceClassElement pce = model.getPersistenceClass(className);
PersistenceFieldElement[] allFields = pce.getFields();
if (allFields != null) {
- List generatedFieldList = new ArrayList();
+ List generatedFieldList = new ArrayList<>();
// In order to avoid concurrentmod exception,
// loop through all persistence fields to put generated
@@ -209,11 +203,8 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
PersistenceFieldElement pfe = allFields[i];
if (pfe != null) {
String pFieldName = pfe.getName();
- String ejbFieldName = nameMapper.
- getEjbFieldForPersistenceField(className,
- pFieldName);
- if (nameMapper.isGeneratedField(ejbName,
- ejbFieldName)) {
+ String ejbFieldName = nameMapper.getEjbFieldForPersistenceField(className, pFieldName);
+ if (nameMapper.isGeneratedField(ejbName, ejbFieldName)) {
generatedFieldList.add(pfe);
}
}
@@ -222,12 +213,10 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
// If the field is a version field, don't remove it
// from the model even though it is generated because
// it is needed to hold the version column information.
- Iterator iterator = generatedFieldList.iterator();
+ Iterator iterator = generatedFieldList.iterator();
while (iterator.hasNext()) {
- PersistenceFieldElement pfe =
- (PersistenceFieldElement)iterator.next();
- MappingFieldElement mfe = mapClassElt.
- getField(pfe.getName());
+ PersistenceFieldElement pfe = iterator.next();
+ MappingFieldElement mfe = mapClassElt.getField(pfe.getName());
if (mfe != null && (!mfe.isVersion())) {
model.removeFieldElement(pfe);
mapClassElt.removeField(mfe);
@@ -251,15 +240,11 @@ public DatabaseGenerator.Results generateMappingClasses(String dbName,
* @throws ModelException
* @throws ConversionException
*/
- protected Map loadMappingClasses(SunCmpMappings sunMapping,
- ClassLoader classLoader)
+ protected Map loadMappingClasses(SunCmpMappings sunMapping, ClassLoader classLoader)
throws DBException, ModelException, ConversionException {
MappingFile mapFile = new MappingFile(classLoader);
-
- Map allMappings = mapFile.intoMappingClasses(sunMapping, ddHelper);
-
+ Map allMappings = mapFile.intoMappingClasses(sunMapping, ddHelper);
updateMappingClasses(allMappings.values());
-
return allMappings;
}
@@ -287,11 +272,8 @@ public void cleanup() {
* @throws DBException
* @throws ModelException
*/
- private DatabaseGenerator.Results generateSchema(List pcClasses,
- String dbName, Boolean useUniqueTableNames,
- Properties userPolicy)
- throws IOException, DBException, ModelException {
-
+ private DatabaseGenerator.Results generateSchema(List pcClasses, String dbName,
+ Boolean useUniqueTableNames, Properties userPolicy) throws IOException, DBException, ModelException {
MappingPolicy mappingPolicy = MappingPolicy.getMappingPolicy(dbName);
mappingPolicy.setUserPolicy(userPolicy);
@@ -309,10 +291,10 @@ private DatabaseGenerator.Results generateSchema(List pcClasses,
* Puts mapping classes into model's cache
* @param mappingClasses a collection of mapping classes
*/
- private void updateMappingClasses(Collection mappingClasses) {
- Iterator iter = mappingClasses.iterator();
+ private void updateMappingClasses(Collection mappingClasses) {
+ Iterator iter = mappingClasses.iterator();
while (iter.hasNext()) {
- MappingClassElement mapClassElt = (MappingClassElement)iter.next();
+ MappingClassElement mapClassElt = iter.next();
//put it in the models' cache
model.updateKeyForClass(mapClassElt, null);
//keep a strong ref
@@ -329,7 +311,7 @@ private void updateMappingClasses(Collection mappingClasses) {
* @return a SunCmpMappings object
* @throws Schema2BeansException
*/
- private SunCmpMappings getPartialSunCmpMappings(List pcClasses,
+ private SunCmpMappings getPartialSunCmpMappings(List pcClasses,
boolean useUniqueTableNames) throws Schema2BeansException {
// Create a new name mapper with perisistence class name differing
@@ -590,8 +572,9 @@ else if (isTime(jdbcType)) {
*/
public static boolean hasScale(int jdbcType) {
if (getAttribute(jdbcType).equals(SCALE_ATTRIBUTE)
- || getAttribute(jdbcType).equals(SCALE_PRECISION_ATTRIBUTE))
+ || getAttribute(jdbcType).equals(SCALE_PRECISION_ATTRIBUTE)) {
return true;
+ }
return false;
}
@@ -603,8 +586,9 @@ public static boolean hasScale(int jdbcType) {
* false otherwise
*/
public static boolean hasPrecision(int jdbcType) {
- if (getAttribute(jdbcType).equals(SCALE_PRECISION_ATTRIBUTE))
+ if (getAttribute(jdbcType).equals(SCALE_PRECISION_ATTRIBUTE)) {
return true;
+ }
return false;
}
@@ -615,8 +599,9 @@ public static boolean hasPrecision(int jdbcType) {
* false otherwise
*/
public static boolean hasLength(int jdbcType) {
- if (getAttribute(jdbcType).equals(LENGTH_ATTRIBUTE))
+ if (getAttribute(jdbcType).equals(LENGTH_ATTRIBUTE)) {
return true;
+ }
return false;
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Bundle.properties b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Bundle.properties
index 4a46aa874e1..bbb7b9ac354 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Bundle.properties
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Bundle.properties
@@ -92,11 +92,6 @@ enhancer.destination_directory_already_set=Attempt to set the destination direct
# {0}=dir name
enhancer.destination_directory_not_exist=The destination directory {0} does not exist.
-# Enhancer generator messages
-# {0}=exception string
-CME.generic_exception=Some exception occurred in enhancer generator: {0}
-CME.generic_exception_stack=Some exception occurred in enhancer generator:
-
#Failed to create destination directory.
#{0}=Destination directory
EXC_DestDirCreateFailure=Unable to create destination directory: {0}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/LogHelperEnhancer.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/LogHelperEnhancer.java
deleted file mode 100644
index 962b57471fe..00000000000
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/LogHelperEnhancer.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v. 2.0, which is available at
- * http://www.eclipse.org/legal/epl-2.0.
- *
- * This Source Code may also be made available under the following Secondary
- * Licenses when the conditions for such availability set forth in the
- * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
- * version 2 with the GNU Classpath Exception, which is available at
- * https://www.gnu.org/software/classpath/license.html.
- *
- * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
- */
-
-package com.sun.jdo.api.persistence.enhancer;
-
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
-/**
- *
- * @author Piali Nag
- */
-public class LogHelperEnhancer {
-
- /** The component name for this component
- */
- protected static final String componentName = "enhancer"; // NOI18N
-
- /** The class loader for this component
- */
- protected static final ClassLoader loader =
- LogHelperEnhancer.class.getClassLoader();
-
- /** The bundle name for this component
- */
- protected static final String bundleName =
- "com.sun.jdo.api.persistence.enhancer.Bundle"; // NOI18N
-
- /** Return the logger for the enhancer component
- */
- public static Logger getLogger() {
- return LogHelper.getLogger (componentName, bundleName, loader);
- }
-
-}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Main.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Main.java
index a71b4eb0ee3..c6dd61fa02e 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Main.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/Main.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -41,6 +42,7 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
+import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.zip.ZipInputStream;
@@ -150,19 +152,19 @@ public static void main(String[] argv) {
//@olsen: split: method filter() -> process(), processArgs()
public int process(String[] argv) {
//@olsen: added inplace of disabled feature
- ArrayList cNames = new ArrayList();
+ ArrayList cNames = new ArrayList<>();
//@olsen: split: method filter() -> process(), processArgs()
int res = processArgs(argv, cNames);
if (res != 0) {
//@olsen: added println()
- printMessage ("aborted with errors.");//NOI18N
+ printMessage ("aborted with errors.");
return res;
}
//@olsen: added support for timing statistics
try {
if (this.cmdLineOpts.doTiming) {
- Support.timer.push("Main.process(String[])");//NOI18N
+ Support.timer.push("Main.process(String[])");
}
// Find all of the classes on which we want to operate
@@ -172,7 +174,7 @@ public int process(String[] argv) {
computeClasses(pcNames, paNames, ccNames);
*/
- printMessage ("done.");//NOI18N
+ printMessage ("done.");
return 0;
} finally {
if (this.cmdLineOpts.doTiming) {
@@ -188,214 +190,70 @@ public int process(String[] argv) {
//@olsen: made private
protected int processArgs(String[] argv,
//@olsen: added inplace of disabled feature
- Collection cNames) {
+ Collection cNames) {
argv = preprocess(argv);
-//@olsen: disabled feature
-/*
- ArrayList ccNames = new ArrayList();
- ArrayList pcNames = new ArrayList();
- ArrayList paNames = new ArrayList();
- int classMode = ClassControl.PersistCapable;
-*/
-
-//@olsen: disabled feature
-/*
- String classpath = System.getProperty("java.class.path");
- String sysClasspath = System.getProperty("sun.boot.class.path", "");
-*/
-
- //@olsen: added
Properties jdoMetaDataProperties = null;
for (int i=0; i continue
-
String arg = argv[i];
-//@olsen: disabled feature
-/*
- if (arg.equals("-cc") ||
- arg.equals("-copyclass")) {
- classMode = ClassControl.PersistUnknown;
- continue;
- }
- if (arg.equals("-pa") ||
- arg.equals("-persistaware")) {
- classMode = ClassControl.PersistAware;
- continue;
- }
- if (arg.equals("-pc") ||
- arg.equals("-persistcapable")) {
- classMode = ClassControl.PersistCapable;
- continue;
- }
-*/
- if (arg.equals("-v") ||//NOI18N
- arg.equals("-verbose")) {//NOI18N
+ if (arg.equals("-v") ||
+ arg.equals("-verbose")) {
this.cmdLineOpts.verbose = true;
this.cmdLineOpts.quiet = false;
continue;
}
- if (arg.equals("-q") ||//NOI18N
- arg.equals("-quiet")) {//NOI18N
+ if (arg.equals("-q") ||
+ arg.equals("-quiet")) {
this.cmdLineOpts.quiet = true;
this.cmdLineOpts.verbose = false;
continue;
}
- if (arg.equals("-f") ||//NOI18N
- arg.equals("-force")) {//NOI18N
+ if (arg.equals("-f") ||
+ arg.equals("-force")) {
this.cmdLineOpts.forceWrite = true;
continue;
}
-//@olsen: disabled feature
-/*
- if (arg.equals("-inplace")) {
- env.setUpdateInPlace(true);
- continue;
- }
-*/
-//@lars: disabled feature
-/*
- if (arg.equals("-qf") ||//NOI18N
- arg.equals("-quietfield")) {//NOI18N
- if (argv.length-i < 2) {
- usage();
- printError ("Missing argument to the -quietfield option", null);//NOI18N
- } else {
- String fullFieldName = argv[++i];
- if (fullFieldName.indexOf('.') == -1) {
- printError ("Field name specifications must include " +//NOI18N
- "a fully qualified class name. " +//NOI18N
- fullFieldName + " does not include one.", null);//NOI18N
- } else {
- env.suppressFieldWarnings(fullFieldName);
- }
- }
- continue;
- }
- if (arg.equals("-qc") ||//NOI18N
- arg.equals("-quietclass")) {//NOI18N
- if (argv.length-i < 2) {
- usage();
- env.error("Missing argument to the -quietclass option");//NOI18N
- } else {
- env.suppressClassWarnings(argv[++i]);
- }
- continue;
- }
-*/
- if (arg.equals("-nowrite")) {//NOI18N
+ if (arg.equals("-nowrite")) {
this.cmdLineOpts.noWrite = true;
continue;
}
-//@olsen: disabled feature
-/*
- if (arg.equals("-modifyjava")) {
- env.setModifyJavaClasses(true);
- continue;
- }
-*/
-//@olsen: disabled feature
-/*
- if (arg.equals("-modifyfinals")) {
- env.setAllowFinalModifications(true);
- continue;
- }
-*/
-//@olsen: disabled feature
-/*
- if (arg.equals("-noarrayopt")) {
- env.setNoArrayOptimization(true);
- continue;
- }
-*/
-//@lars: disabled feature
-/*
- if (arg.equals("-nothisopt")) {//NOI18N
- env.setNoThisOptimization(true);
- continue;
- }
- if (arg.equals("-noinitializeropt")) {//NOI18N
- env.setNoInitializerOptimization(true);
- continue;
- }
- if (arg.equals("-noopt")) {//NOI18N
- env.setNoOptimization(true);
- continue;
- }
-*/
- if (arg.equals("-d") ||//NOI18N
- arg.equals("-dest")) {//NOI18N
+ if (arg.equals("-d") ||
+ arg.equals("-dest")) {
if (argv.length-i < 2) {
- printError ("Missing argument to the -dest option", null);//NOI18N
+ printError ("Missing argument to the -dest option", null);
usage();
}
this.cmdLineOpts.destinationDirectory = argv[++i];
continue;
}
-//@olsen: disabled feature
-/*
- if (arg.equals("-classpath") ||
- arg.equals("-cpath")) {
- if (argv.length-i < 2) {
- usage();
- env.error("Missing argument to the -classpath option");
- }
- classpath = argv[++i];
- continue;
- }
- if (arg.equals("-sysclasspath") ||
- arg.equals("-syscpath")) {
- if (argv.length-i < 2) {
- usage();
- env.error("Missing argument to the -sysclasspath option");
- }
- sysClasspath = argv[++i];
- continue;
- }
-*/
-//@olsen: disabled feature
-/*
- if (arg.equals("-tp") ||
- arg.equals("-translatepackage")) {
- if (argv.length-i < 3) {
- usage();
- env.error("Missing arguments to the -translatepackage option");
- }
- env.setPackageTranslation(argv[i+1], argv[i+2]);
- i += 2;
- continue;
- }
-*/
- //@olsen: new command line option for timing statistics
- if (arg.equals("-t") ||//NOI18N
- arg.equals("--doTiming")) {//NOI18N
+ if (arg.equals("-t") ||
+ arg.equals("--doTiming")) {
this.cmdLineOpts.doTiming = true;
-// env.setDoTimingStatistics(true);
continue;
}
//@olsen: new command line option for JDO meta data properties
- if (arg.equals("-jp") ||//NOI18N
- arg.equals("--jdoProperties")) {//NOI18N
+ if (arg.equals("-jp") ||
+ arg.equals("--jdoProperties")) {
if (argv.length-i < 2) {
- printError("Missing argument to the -jp/--jdoProperties option", null);//NOI18N
+ printError("Missing argument to the -jp/--jdoProperties option", null);
usage();
}
try {
jdoMetaDataProperties = new Properties();
jdoMetaDataProperties.load(new FileInputStream(argv[++i]));
} catch (IOException ex) {
- printError("Cannot read JDO meta data properties from file", ex);//NOI18N
+ printError("Cannot read JDO meta data properties from file", ex);
usage();
}
continue;
}
if (arg.length() > 0 && arg.charAt(0) == '-') {
- printError("Unrecognized option:" + arg, null);//NOI18N
+ printError("Unrecognized option:" + arg, null);
usage();
}
if (arg.length() == 0) {
- printMessage ("Empty file name encountered on the command line.");//NOI18N
+ printMessage ("Empty file name encountered on the command line.");
}
//@olsen: added inplace of disabled feature
@@ -421,7 +279,7 @@ else if (classMode == ClassControl.PersistUnknown)
//env.setVerbose(true);
this.cmdLineOpts.quiet = false;
// env.setNoOptimization(true);
-// env.message("forced settings: -noopt");//NOI18N
+// env.message("forced settings: -noopt");
/*
if (env.errorCount() > 0)
@@ -437,18 +295,19 @@ else if (classMode == ClassControl.PersistUnknown)
// The user must specify a destination directory
if (this.cmdLineOpts.destinationDirectory == null) {
- if (argv.length > 0)
- printError("No -dest output directory was specified", null);//NOI18N
+ if (argv.length > 0) {
+ printError("No -dest output directory was specified", null);
+ }
usage();
}
//@olsen: added: initialize JDO meta data
JDOMetaData jdoMetaData;
if (jdoMetaDataProperties != null) {
- printMessage("using JDO meta-data from properties");//NOI18N
+ printMessage("using JDO meta-data from properties");
jdoMetaData = new JDOMetaDataPropertyImpl(jdoMetaDataProperties, this.outMessages);
} else {
- printMessage("using JDO meta-data from Model.Enhancer");//NOI18N
+ printMessage("using JDO meta-data from Model.Enhancer");
jdoMetaData = new JDOMetaDataModelImpl(Model.ENHANCER, this.outMessages);
}
//@olsen: added support for timing statistics
@@ -499,19 +358,20 @@ else if (classMode == ClassControl.PersistUnknown)
* of the @files, if any
*/
private String[] preprocess(String[] args) {
- ArrayList argVec = new ArrayList();
+ ArrayList argVec = new ArrayList<>();
for (int i=0; i 0 && args[i].charAt(0) == '@') {
String filename = null;
if (args[i].length() == 1) {
- if (i+1 < args.length)
+ if (i+1 < args.length) {
filename = args[++i];
+ }
} else {
filename = args[i].substring(1);
}
if (filename == null) {
- printError("missing file name argument to @.", null);//NOI18N
+ printError("missing file name argument to @.", null);
} else {
appendFileContents(filename, argVec);
}
@@ -531,31 +391,34 @@ private String[] preprocess(String[] args) {
* within the file to argVec. This currently has only a very
* primitive notion of words (separated by white space).
*/
- private void appendFileContents(String filename, ArrayList argVec) {
+ private void appendFileContents(String filename, List argVec) {
try {
FileReader inputFile = new FileReader(filename);
try (BufferedReader input = new BufferedReader(inputFile)) {
String s = null;
while ((s = input.readLine()) != null) {
- StringTokenizer parser = new StringTokenizer(s, " \t", false);//NOI18N
+ StringTokenizer parser = new StringTokenizer(s, " \t", false);
while (parser.hasMoreElements()) {
String token = parser.nextToken();
- if (token.length() > 0 && token.charAt(0) == '@')
- printError("The included file \"" +//NOI18N
+ if (token.length() > 0 && token.charAt(0) == '@') {
+ printError("The included file \"" +
filename +
- "\" contains a recursive include. " +//NOI18N
- "Recursive includes are not supported.", null);//NOI18N
- if (token.charAt(0) == '#') break;
+ "\" contains a recursive include. " +
+ "Recursive includes are not supported.", null);
+ }
+ if (token.charAt(0) == '#') {
+ break;
+ }
argVec.add(token);
}
}
}
catch (IOException ex) {
- printError("IO exception reading file " + filename + ".", ex);//NOI18N
+ printError("IO exception reading file " + filename + ".", ex);
}
}
catch (FileNotFoundException ex) {
- printError("file " + filename + " not found.", ex);//NOI18N
+ printError("file " + filename + " not found.", ex);
}
}
@@ -586,37 +449,26 @@ private final ByteCodeEnhancer createEnhancer (JDOMetaData jdometadata)
* @param filenames The filenames.
*********************************************************************/
- private final void enhanceInputFiles (Collection filenames)
- {
-
- for (Iterator names = filenames.iterator(); names.hasNext ();)
- {
- try
- {
- String name = (String) names.next ();
+ private final void enhanceInputFiles(Collection filenames) {
+ for (Iterator names = filenames.iterator(); names.hasNext();) {
+ try {
+ String name = names.next();
- //if we have a class-files
- if (isClassFileName (name))
- {
- enhanceClassFile (openFileInputStream (name));
- }
- else
- {
- //if we have an archive
- if (isZipFileName (name))
- {
- enhanceZipFile (name); //getZipFile (name));
+ // if we have a class-files
+ if (isClassFileName(name)) {
+ enhanceClassFile(openFileInputStream(name));
+ } else {
+ // if we have an archive
+ if (isZipFileName(name)) {
+ enhanceZipFile(name); // getZipFile (name));
}
- //assume that it is a class name
- else
- {
- enhanceClassFile (openClassInputStream (name));
+ // assume that it is a class name
+ else {
+ enhanceClassFile(openClassInputStream(name));
}
}
- }
- catch (Throwable ex)
- {
- printError (null, ex);
+ } catch (Throwable ex) {
+ printError(null, ex);
}
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/OutputStreamWrapper.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/OutputStreamWrapper.java
index 080b1fd5d93..4b91d586ba2 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/OutputStreamWrapper.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/OutputStreamWrapper.java
@@ -36,7 +36,6 @@
* This wrapper is necessary to determine the classname outside the enhancer,
* after the class has been enhanced, since do do not always know the
* classname of an opened input stream.
- *
*/
//#########################################################################
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/AttributeVector.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/AttributeVector.java
index fdaeb822814..0a3be1b7e32 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/AttributeVector.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/AttributeVector.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -34,14 +35,8 @@
public class AttributeVector {
/* Vector of ClassAttribute */
- private ClassAttribute attributes[] = null;
+ private ClassAttribute[] attributes;
- /**
- * Returns the i'th attribute in the array
- */
- private ClassAttribute attrAt(int i) {
- return attributes[i];
- }
/**
* Construct an empty AttributeVector
@@ -52,9 +47,9 @@ public AttributeVector() { }
* Add an element to the vector
*/
public void addElement(ClassAttribute attr) {
- if (attributes == null)
+ if (attributes == null) {
attributes = new ClassAttribute[1];
- else {
+ } else {
ClassAttribute newAttributes[] = new ClassAttribute[attributes.length+1];
System.arraycopy(attributes, 0, newAttributes, 0, attributes.length);
attributes = newAttributes;
@@ -62,8 +57,8 @@ public void addElement(ClassAttribute attr) {
attributes[attributes.length-1] = attr;
}
- public Enumeration elements() {
- class AttributeVectorEnumeration implements Enumeration {
+ public Enumeration elements() {
+ class AttributeVectorEnumeration implements Enumeration {
private ClassAttribute[] attributes;
private int current = 0;
@@ -71,12 +66,15 @@ class AttributeVectorEnumeration implements Enumeration {
attributes = attrs;
}
+ @Override
public boolean hasMoreElements() {
return attributes != null && current < attributes.length;
}
- public Object nextElement() {
- if (!hasMoreElements())
+ @Override
+ public ClassAttribute nextElement() {
+ if (!hasMoreElements()) {
throw new NoSuchElementException();
+ }
return attributes[current++];
}
}
@@ -88,11 +86,12 @@ public Object nextElement() {
* Look for an attribute of a specific name
*/
public ClassAttribute findAttribute(String attrName) {
- Enumeration e = elements();
+ Enumeration e = elements();
while (e.hasMoreElements()) {
- ClassAttribute attr = (ClassAttribute) e.nextElement();
- if (attr.attrName().asString().equals(attrName))
+ ClassAttribute attr = e.nextElement();
+ if (attr.attrName().asString().equals(attrName)) {
return attr;
+ }
}
return null;
}
@@ -133,8 +132,9 @@ void write(DataOutputStream out) throws IOException {
out.writeShort(0);
} else {
out.writeShort(attributes.length);
- for (int i=0; i jdkVersions = convertMajorMinorVersions(jdkMajorMinorVersions);
public static final String supportedVersions = printSupportedVersions();
private int majorVersion = 0;
@@ -67,17 +67,17 @@ final public class ClassFile implements VMConstants {
/* A list of the interfaces which the class implements
* The contents are ConstClass objects
*/
- private Vector classInterfaces = new Vector();
+ private Vector classInterfaces = new Vector<>();
/* A list of the fields which the class contains
* The contents are ClassField objects
*/
- private Vector classFields = new Vector();
+ private Vector classFields = new Vector<>();
/* A list of the methods which the class defines
* The contents are ClassMethod objects
*/
- private Vector classMethods = new Vector();
+ private Vector classMethods = new Vector<>();
/* A list of the attributes associated with the class */
private AttributeVector classAttributes = new AttributeVector();
@@ -170,7 +170,7 @@ public void setSuperName(ConstClass superCl) {
* Return the list of the interfaces which the class implements
* The contents are ConstClass objects
*/
- public Vector interfaces() {
+ public Vector interfaces() {
return classInterfaces;
}
@@ -185,7 +185,7 @@ public void addInterface (ConstClass iface) {
* Return the list of the fields which the class contains
* The contents are ClassField objects
*/
- public Vector fields() {
+ public Vector fields() {
return classFields;
}
@@ -208,7 +208,7 @@ public void addField(ClassField field, int index) {
* Return the list of the methods which the class defines
* The contents are ClassMethod objects
*/
- public Vector methods() {
+ public Vector methods() {
return classMethods;
}
@@ -216,11 +216,12 @@ public Vector methods() {
* Look for a method with the specified name and type signature
*/
public ClassMethod findMethod(String methodName, String methodSig) {
- for (Enumeration e = methods().elements(); e.hasMoreElements();) {
- ClassMethod method = (ClassMethod) e.nextElement();
+ for (Enumeration e = methods().elements(); e.hasMoreElements();) {
+ ClassMethod method = e.nextElement();
if (method.name().asString().equals(methodName) &&
- method.signature().asString().equals(methodSig))
+ method.signature().asString().equals(methodSig)) {
return method;
+ }
}
return null;
}
@@ -236,10 +237,11 @@ public void addMethod(ClassMethod method) {
* Look for a field with the specified name
*/
public ClassField findField(String fieldName) {
- for (Enumeration e = fields().elements(); e.hasMoreElements();) {
- ClassField field = (ClassField) e.nextElement();
- if (field.name().asString().equals(fieldName))
+ for (Enumeration e = fields().elements(); e.hasMoreElements();) {
+ ClassField field = e.nextElement();
+ if (field.name().asString().equals(fieldName)) {
return field;
+ }
}
return null;
}
@@ -257,8 +259,9 @@ public AttributeVector attributes() {
public ClassFile(DataInputStream data) throws ClassFormatError {
try {
int thisMagic = data.readInt();
- if (thisMagic != magic)
- throw new ClassFormatError("Bad magic value for input");//NOI18N
+ if (thisMagic != magic) {
+ throw new ClassFormatError("Bad magic value for input");
+ }
short thisMinorVersion = data.readShort();
short thisMajorVersion = data.readShort();
@@ -269,10 +272,10 @@ public ClassFile(DataInputStream data) throws ClassFormatError {
minorVersion = thisMinorVersion;
majorVersion = thisMajorVersion;
} else {
- throw new ClassFormatError("Bad version number: {" + //NOI18N
- thisMajorVersion + "," + //NOI18N
+ throw new ClassFormatError("Bad version number: {" +
+ thisMajorVersion + "," +
thisMinorVersion +
- "} expected one of: " + //NOI18N
+ "} expected one of: " +
supportedVersions);
}
readConstants(data);
@@ -286,7 +289,7 @@ public ClassFile(DataInputStream data) throws ClassFormatError {
readMethods(data);
classAttributes = AttributeVector.readAttributes(data, constantPool);
} catch (IOException e) {
- ClassFormatError cfe = new ClassFormatError("IOException during reading");//NOI18N
+ ClassFormatError cfe = new ClassFormatError("IOException during reading");
cfe.initCause(e);
throw cfe;
}
@@ -333,7 +336,7 @@ public byte[] getBytes() throws java.io.IOException {
System.getProperty("filter.writeClassToDirectory");
if (writeClassToDirectory != null) {
String filename = writeClassToDirectory + java.io.File.separator +
- thisClassName.asString() + ".class";//NOI18N
+ thisClassName.asString() + ".class";
System.err.println("Writing class to file " + filename);
DataOutputStream stream = new DataOutputStream(
new java.io.FileOutputStream(filename));
@@ -357,28 +360,28 @@ public void print (PrintStream out) {
constantPool.print(out);
out.println();
- out.println("majorVersion = " + Integer.toString(majorVersion));//NOI18N
- out.println("minorVersion = " + Integer.toString(minorVersion));//NOI18N
- out.println("accessFlags = " + Integer.toString(accessFlags));//NOI18N
- out.println("className = " + thisClassName.asString());//NOI18N
- out.println("superClassName = " + superClassName.asString());//NOI18N
- out.print("Interfaces =");//NOI18N
+ out.println("majorVersion = " + Integer.toString(majorVersion));
+ out.println("minorVersion = " + Integer.toString(minorVersion));
+ out.println("accessFlags = " + Integer.toString(accessFlags));
+ out.println("className = " + thisClassName.asString());
+ out.println("superClassName = " + superClassName.asString());
+ out.print("Interfaces =");
for (int i=0; i 0) {
int interfaceIndex = data.readUnsignedShort();
ConstClass ci = null;
- if (interfaceIndex != 0)
+ if (interfaceIndex != 0) {
ci = (ConstClass) constantPool.constantAt(interfaceIndex);
+ }
classInterfaces.addElement(ci);
}
}
@@ -413,10 +417,11 @@ private void readInterfaces(DataInputStream data) throws IOException {
private void writeInterfaces(DataOutputStream data) throws IOException {
data.writeShort(classInterfaces.size());
for (int i=0; i convertMajorMinorVersions(short[][] majorMinor) {
int length = majorMinor.length;
- List result = new ArrayList(length);
+ List result = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
result.add(getVersionInt(majorMinor[i][0], majorMinor[i][1]));
}
@@ -464,22 +471,22 @@ private static boolean isSupportedVersion(short major, short minor) {
}
private static Integer getVersionInt(short major, short minor) {
- return new Integer(major * 65536 + minor);
+ return Integer.valueOf(major * 65536 + minor);
}
public static final String printSupportedVersions() {
- StringBuffer buf = new StringBuffer("{"); //NOI18N
+ StringBuffer buf = new StringBuffer("{");
int length = jdkMajorMinorVersions.length;
for (int i = 0; i < length; i++) {
int major = jdkMajorMinorVersions[i][0];
int minor = jdkMajorMinorVersions[i][1];
- buf.append("{"); //NOI18N
+ buf.append("{");
buf.append(major);
- buf.append(","); //NOI18N
+ buf.append(",");
buf.append(minor);
- buf.append("}"); //NOI18N
+ buf.append("}");
}
- buf.append("}"); //NOI18N
+ buf.append("}");
return buf.toString();
}
@@ -506,8 +513,9 @@ private void sortArray(int start, int end) {
swap(start, (start+end)/2);
int last = start;
for (int i = start+1; i<=end; i++) {
- if (compare(i, start) < 0)
+ if (compare(i, start) < 0) {
swap (++last, i);
+ }
}
swap(start, last);
sortArray(start, last-1);
@@ -524,15 +532,18 @@ class InterfaceArraySorter extends ArraySorter {
}
/* return the size of the array being sorted */
+ @Override
int size() { return theArray.length; }
/* return -1 if o1 < o2, 0 if o1 == o2, 1 if o1 > o2 */
+ @Override
int compare(int o1Index, int o2Index) {
return theArray[o1Index].asString().compareTo(
theArray[o2Index].asString());
}
/* Swap the elements at index o1Index and o2Index */
+ @Override
void swap(int o1Index, int o2Index) {
ConstClass tmp = theArray[o1Index];
theArray[o1Index] = theArray[o2Index];
@@ -548,15 +559,18 @@ class FieldArraySorter extends ArraySorter {
}
/* return the size of the array being sorted */
+ @Override
int size() { return theArray.length; }
/* return -1 if o1 < o2, 0 if o1 == o2, 1 if o1 > o2 */
+ @Override
int compare(int o1Index, int o2Index) {
return theArray[o1Index].name().asString().compareTo(
theArray[o2Index].name().asString());
}
/* Swap the elements at index o1Index and o2Index */
+ @Override
void swap(int o1Index, int o2Index) {
ClassField tmp = theArray[o1Index];
theArray[o1Index] = theArray[o2Index];
@@ -572,9 +586,11 @@ class MethodArraySorter extends ArraySorter {
}
/* return the size of the array being sorted */
+ @Override
int size() { return theArray.length; }
/* return -1 if o1 < o2, 0 if o1 == o2, 1 if o1 > o2 */
+ @Override
int compare(int o1Index, int o2Index) {
int cmp = theArray[o1Index].name().asString().compareTo(
theArray[o2Index].name().asString());
@@ -586,6 +602,7 @@ int compare(int o1Index, int o2Index) {
}
/* Swap the elements at index o1Index and o2Index */
+ @Override
void swap(int o1Index, int o2Index) {
ClassMethod tmp = theArray[o1Index];
theArray[o1Index] = theArray[o2Index];
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ClassMethod.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ClassMethod.java
index 278b2e49ecb..0535a798a30 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ClassMethod.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ClassMethod.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -28,10 +29,10 @@
*/
public class ClassMethod extends ClassMember {
/* The name of the constructor code */
- public final static String intializerName = "";//NOI18N
+ public final static String intializerName = "";
/* The name of the static initializer code */
- public final static String staticIntializerName = "";//NOI18N
+ public final static String staticIntializerName = "";
/* access flag bit mask - see VMConstants */
private int accessFlags;
@@ -51,6 +52,7 @@ public class ClassMethod extends ClassMember {
/**
* Return the access flags for the method - see VMConstants
*/
+ @Override
public int access() {
return accessFlags;
}
@@ -58,6 +60,7 @@ public int access() {
/**
* Update the access flags for the field - see VMConstants
*/
+ @Override
public void setAccess(int newFlags) {
accessFlags = newFlags;
}
@@ -79,6 +82,7 @@ public boolean isNative() {
/**
* Return the name of the method
*/
+ @Override
public ConstUtf8 name() {
return methodName;
}
@@ -93,6 +97,7 @@ public void changeName(ConstUtf8 name) {
/**
* Return the type signature of the method
*/
+ @Override
public ConstUtf8 signature() {
return methodSignature;
}
@@ -107,6 +112,7 @@ public void changeSignature(ConstUtf8 newSig) {
/**
* Return the attributes associated with the method
*/
+ @Override
public AttributeVector attributes() {
return methodAttributes;
}
@@ -135,11 +141,12 @@ int codeSize() {
* Returns the CodeAttribute associated with this method (if any)
*/
public CodeAttribute codeAttribute() {
- Enumeration e = methodAttributes.elements();
+ Enumeration e = methodAttributes.elements();
while (e.hasMoreElements()) {
- ClassAttribute attr = (ClassAttribute) e.nextElement();
- if (attr instanceof CodeAttribute)
+ ClassAttribute attr = e.nextElement();
+ if (attr instanceof CodeAttribute) {
return (CodeAttribute) attr;
+ }
}
return null;
}
@@ -172,10 +179,10 @@ void write(DataOutputStream data) throws IOException {
void print(PrintStream out, int indent) {
ClassPrint.spaces(out, indent);
- out.print("'" + methodName.asString() + "'");//NOI18N
- out.print(" sig = " + methodSignature.asString());//NOI18N
- out.print(" accessFlags = " + Integer.toString(accessFlags));//NOI18N
- out.println(" attributes:");//NOI18N
+ out.print("'" + methodName.asString() + "'");
+ out.print(" sig = " + methodSignature.asString());
+ out.print(" accessFlags = " + Integer.toString(accessFlags));
+ out.println(" attributes:");
methodAttributes.print(out, indent+2);
}
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/CodeEnv.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/CodeEnv.java
index ed03c6d89e6..232129bba75 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/CodeEnv.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/CodeEnv.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -26,7 +27,7 @@ class CodeEnv {
private ConstantPool constantPool;
/* hash table mapping byte code offset to InsnTarget */
- private Hashtable targets = new Hashtable(7);
+ private Hashtable targets = new Hashtable<>(7);
CodeEnv(ConstantPool constantPool) {
this.constantPool = constantPool;
@@ -34,7 +35,7 @@ class CodeEnv {
final InsnTarget getTarget(int offset) {
Integer off = new Integer(offset);
- InsnTarget targ = (InsnTarget)targets.get(off);
+ InsnTarget targ = targets.get(off);
if (targ == null) {
targ = new InsnTarget(offset);
targets.put(off, targ);
@@ -44,7 +45,7 @@ final InsnTarget getTarget(int offset) {
final InsnTarget findTarget(int offset) {
Integer off = new Integer(offset);
- return (InsnTarget)targets.get(off);
+ return targets.get(off);
}
final ConstantPool pool() {
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstDouble.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstDouble.java
index cd9a7f605f2..736dd671648 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstDouble.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstDouble.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -35,6 +36,7 @@ public class ConstDouble extends ConstValue {
/**
* The tag of this constant entry
*/
+ @Override
public int tag () {
return MyTag;
}
@@ -49,6 +51,7 @@ public double value() {
/**
* Return the descriptor string for the constant type.
*/
+ @Override
public String descriptor() {
return "D";//NOI18N
}
@@ -56,6 +59,7 @@ public String descriptor() {
/**
* A printable representation
*/
+ @Override
public String toString () {
return "CONSTANTDouble(" + indexAsString() + "): " + //NOI18N
"doubleValue(" + Double.toString(doubleValue) + ")";//NOI18N
@@ -70,6 +74,7 @@ public String toString () {
doubleValue = f;
}
+ @Override
void formatData (DataOutputStream b) throws IOException {
b.writeDouble(doubleValue);
}
@@ -78,6 +83,8 @@ static ConstDouble read (DataInputStream input) throws IOException {
return new ConstDouble (input.readDouble());
}
- void resolve (ConstantPool p) { }
+ @Override
+ void resolve(ConstantPool p) {
+ }
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstantPool.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstantPool.java
index 7bacf11b012..be18c9a3cc1 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstantPool.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ConstantPool.java
@@ -30,23 +30,23 @@
public class ConstantPool implements VMConstants {
/* The actual pool */
- private Vector pool = new Vector();
+ private Vector pool = new Vector<>();
/* uniqifier tables */
private boolean hashed = false;
- private Hashtable utfTable = new Hashtable(11);
- private Hashtable unicodeTable = new Hashtable(3);
- private Hashtable stringTable = new Hashtable(11);
- private Hashtable classTable = new Hashtable(11);
- private Hashtable intTable = new Hashtable(3);
- private Hashtable floatTable = new Hashtable(3);
- private Hashtable longTable = new Hashtable(3);
- private Hashtable doubleTable = new Hashtable(3);
-
- private Vector methodRefTable = new Vector();
- private Vector fieldRefTable = new Vector();
- private Vector ifaceMethodRefTable = new Vector();
- private Vector nameAndTypeTable = new Vector();
+ private Hashtable utfTable = new Hashtable<>(11);
+ private Hashtable unicodeTable = new Hashtable<>(3);
+ private Hashtable stringTable = new Hashtable<>(11);
+ private Hashtable classTable = new Hashtable<>(11);
+ private Hashtable intTable = new Hashtable<>(3);
+ private Hashtable floatTable = new Hashtable<>(3);
+ private Hashtable longTable = new Hashtable<>(3);
+ private Hashtable doubleTable = new Hashtable<>(3);
+
+ private Vector methodRefTable = new Vector<>();
+ private Vector fieldRefTable = new Vector<>();
+ private Vector ifaceMethodRefTable = new Vector<>();
+ private Vector nameAndTypeTable = new Vector<>();
/* public accessors */
@@ -61,7 +61,7 @@ public int nEntries() {
* Return the constant in the pool at the specified entry index
*/
public ConstBasic constantAt (int index) {
- return (ConstBasic) pool.elementAt(index);
+ return pool.elementAt(index);
}
/**
@@ -205,8 +205,9 @@ public ConstNameAndType addNameAndType (String name, String type) {
for (int i=0; i 0)
+ while (nconstants > 0) {
nconstants -= readConstant(input);
+ }
resolvePool();
}
@@ -286,7 +288,7 @@ void summarize () {
void write (DataOutputStream buff) throws IOException {
buff.writeShort(pool.size());
for (int i=1; i 1)
+ if (slots > 1) {
pool.addElement(null);
+ }
return slots;
}
@@ -428,14 +432,15 @@ private void recordConstant (ConstBasic c) {
}
}
- private ConstBasicMemberRef searchTable(Vector table, String cname,
+ private ConstBasicMemberRef searchTable(Vector table, String cname,
String mname, String sig) {
for (int i=0; i stack) {
for (int idx = 0; idx < stackSig.length(); idx++) {
int tp = 0;
switch(stackSig.charAt(idx)) {
@@ -308,10 +318,12 @@ public static void computeStackTypes(String stackSig, Stack stack) {
break;
case '[':
tp = TC_OBJECT;
- while (stackSig.charAt(idx) == '[' || stackSig.charAt(idx) == ']')
+ while (stackSig.charAt(idx) == '[' || stackSig.charAt(idx) == ']') {
idx++;
- if (stackSig.charAt(idx) != 'L')
+ }
+ if (stackSig.charAt(idx) != 'L') {
break;
+ }
/* fall through */
case 'L':
tp = TC_OBJECT;
@@ -342,10 +354,12 @@ public static int nextSigElement(String stackSig, int idx) {
case 'D':
break;
case '[':
- while (stackSig.charAt(idx) == '[' || stackSig.charAt(idx) == ']')
+ while (stackSig.charAt(idx) == '[' || stackSig.charAt(idx) == ']') {
idx++;
- if (stackSig.charAt(idx) != 'L')
+ }
+ if (stackSig.charAt(idx) != 'L') {
break;
+ }
/* fall through */
case 'L':
idx = stackSig.indexOf(';', idx);
@@ -376,14 +390,16 @@ public static String remapTypes(String sig, Map classTranslations) {
/* An array - skip through the [] pairs, copying to buf if not null */
while ((c = sig.charAt(idx)) == '[' || c == ']') {
idx++;
- if (buf != null)
+ if (buf != null) {
buf.append(c);
+ }
}
/* If the next char isnt 'L', the next char is a simple type and
will be handled by the default 1 char translation */
- if (sig.charAt(idx) != 'L')
+ if (sig.charAt(idx) != 'L') {
break;
+ }
/* fall through to type name translation */
case 'L':
/* This is a type name */
@@ -410,8 +426,9 @@ public static String remapTypes(String sig, Map classTranslations) {
break;
}
- if (buf != null)
+ if (buf != null) {
buf.append(c);
+ }
}
return (buf == null) ? sig : (buf.toString());
}
@@ -425,12 +442,13 @@ public static String remapTypes(String sig, Map classTranslations) {
*/
public static String translateClass(
String cls, Map classTranslations) {
- if (cls.charAt(0) == '[')
+ if (cls.charAt(0) == '[') {
return remapTypes(cls, classTranslations);
- else {
+ } else {
String mapTo = (String) classTranslations.get(cls);
- if (mapTo != null)
+ if (mapTo != null) {
return mapTo;
+ }
return cls;
}
}
@@ -499,14 +517,16 @@ public static String userFieldSig(String vmSig, int idx) {
}
/* If a non-array type, we already have the answer */
- if (arrayDims == 0)
+ if (arrayDims == 0) {
return sigElement;
+ }
/* array types need a little more work */
StringBuffer buf = new StringBuffer(sigElement.length() + 2 * arrayDims);
buf.append(sigElement);
- while (arrayDims-- > 0)
+ while (arrayDims-- > 0) {
buf.append("[]");//NOI18N
+ }
return buf.toString();
}
@@ -517,8 +537,9 @@ public static String userFieldSig(String vmSig, int idx) {
*/
public static String userMethodArgs(String methodSig) {
/* This better be a method signature */
- if (methodSig.charAt(0) != '(')
+ if (methodSig.charAt(0) != '(') {
throw new InsnError("Invalid method signature");//NOI18N
+ }
StringBuffer buf = new StringBuffer();
@@ -527,10 +548,11 @@ public static String userMethodArgs(String methodSig) {
int idx = 1;
boolean firstArg = true;
while (methodSig.charAt(idx) != ')') {
- if (firstArg)
+ if (firstArg) {
firstArg = false;
- else
+ } else {
buf.append(", ");//NOI18N
+ }
buf.append(userFieldSig(methodSig, idx));
idx = nextSigElement(methodSig, idx);
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ExceptionTable.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ExceptionTable.java
index acac48caa1f..1a35a2378e1 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ExceptionTable.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/classfile/ExceptionTable.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -29,7 +30,7 @@
*/
public class ExceptionTable {
/* A variable length list of ExceptionRange objects */
- private Vector theVector = new Vector();
+ private Vector theVector = new Vector<>();
/* public accessors */
@@ -37,7 +38,7 @@ public class ExceptionTable {
* Return an enumeration of the exception handlers
* Each element in the enumeration is an ExceptionRange
*/
- public Enumeration handlers() {
+ public Enumeration handlers() {
return theVector.elements();
}
@@ -64,14 +65,16 @@ static ExceptionTable read(DataInputStream data, CodeEnv env)
void write(DataOutputStream out) throws IOException {
out.writeShort(theVector.size());
- for (int i=0; i exceptionTable;
/* public accessors */
/**
* Return an enumeration of the checked exceptions
*/
- public Enumeration exceptions() {
+ public Enumeration exceptions() {
return exceptionTable.elements();
}
/**
* Constructor
*/
- public ExceptionsAttribute(ConstUtf8 attrName, Vector excTable) {
+ public ExceptionsAttribute(ConstUtf8 attrName, Vector excTable) {
super(attrName);
exceptionTable = excTable;
}
@@ -55,7 +56,7 @@ public ExceptionsAttribute(ConstUtf8 attrName, Vector excTable) {
*/
public ExceptionsAttribute(ConstUtf8 attrName, ConstClass exc) {
super(attrName);
- exceptionTable = new Vector(1);
+ exceptionTable = new Vector<>(1);
exceptionTable.addElement(exc);
}
@@ -65,31 +66,36 @@ static ExceptionsAttribute read(ConstUtf8 attrName,
DataInputStream data, ConstantPool pool)
throws IOException {
int nExcepts = data.readUnsignedShort();
- Vector excTable = new Vector();
+ Vector excTable = new Vector<>();
while (nExcepts-- > 0) {
int excIndex = data.readUnsignedShort();
ConstClass exc_class = null;
- if (excIndex != 0)
+ if (excIndex != 0) {
exc_class = (ConstClass) pool.constantAt(excIndex);
+ }
excTable.addElement(exc_class);
}
return new ExceptionsAttribute(attrName, excTable);
}
+ @Override
void write(DataOutputStream out) throws IOException {
out.writeShort(attrName().getIndex());
out.writeInt(2+2*exceptionTable.size());
out.writeShort(exceptionTable.size());
- for (int i=0; i localTable;
/* public accessors */
@@ -41,7 +42,7 @@ public class LocalVariableTableAttribute extends ClassAttribute {
* Returns an enumeration of the local variables in the table
* Each element is a LocalVariable
*/
- Enumeration variables() {
+ Enumeration variables() {
return localTable.elements();
}
@@ -60,7 +61,7 @@ static LocalVariableTableAttribute read(
ConstUtf8 attrName, DataInputStream data, CodeEnv env)
throws IOException {
int nVars = data.readUnsignedShort();
- Vector lvarTable = new Vector();
+ Vector lvarTable = new Vector<>();
while (nVars-- > 0) {
lvarTable.addElement(LocalVariable.read(data, env));
}
@@ -68,13 +69,15 @@ static LocalVariableTableAttribute read(
return new LocalVariableTableAttribute(attrName, lvarTable);
}
+ @Override
void write(DataOutputStream out) throws IOException {
out.writeShort(attrName().getIndex());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream tmp_out = new DataOutputStream(baos);
tmp_out.writeShort(localTable.size());
- for (int i=0; i typeNameConversion = new HashMap<>();
static {
typeNameConversion.put(int.class.getName(), "Int");
typeNameConversion.put(long.class.getName(), "Long");
@@ -84,23 +84,15 @@ static private boolean isPrimitiveClass(String className) {
static private String getConvertedTypeName(String fieldType) {
- final String name = (String) typeNameConversion.get(fieldType);
+ final String name = typeNameConversion.get(fieldType);
return (name != null ? name : JavaClassWriterHelper.Object_);
}
- static private String getMethodNameGetField(String fieldType) {
- return JavaClassWriterHelper.get_ + getConvertedTypeName(fieldType) + "Field";
- }
-
-
static private String getMethodNameSetField(String fieldType) {
return JavaClassWriterHelper.set_ + getConvertedTypeName(fieldType) + "Field";
}
- // Create bodies of methods.
-
-
static String[] getJDOManagedFieldCountImpl(int fieldcount) {
return new String[] {FIELDNAME_JDO_INHERITED_FIELD_COUNT + " + " + fieldcount + JavaClassWriterHelper.delim_};
}
@@ -231,7 +223,7 @@ static String[] getFieldCheckWriteImpl(String fieldName, String fieldType, int f
static String[] getJDOClearImpl(String className, ExtendedJDOMetaData meta, String[] fieldNames, String[] fieldTypes) {
- final List impl = new ArrayList(20);
+ final List impl = new ArrayList<>(20);
for (int i = 0; i < fieldNames.length; i++) {
String fieldTypeClassPath = fieldTypes[i];
String fieldType = normalizeClassName(fieldTypes[i]);
@@ -265,7 +257,7 @@ static String[] getJDOClearImpl(String className, ExtendedJDOMetaData meta, Stri
static String[] getJDOGetFieldImpl(String fieldNumber, String[] fieldNames, String[] fieldTypes) {
- final List impl = new ArrayList(20);
+ final List impl = new ArrayList<>(20);
impl.add("switch (" + fieldNumber + ") {");
for (int i = 0; i < fieldNames.length; i++) {
String fieldType = normalizeClassName(fieldTypes[i]);
@@ -288,7 +280,7 @@ static String[] getJDOGetFieldImpl(String fieldNumber, String[] fieldNames, Stri
static String[] getJDOSetFieldImpl(String fieldNumber, String objName, String[] fieldNames, String[] fieldTypes) {
- final List impl = new ArrayList(20);
+ final List impl = new ArrayList<>(20);
impl.add("switch (" + fieldNumber + ") {");
for (int i = 0; i < fieldNames.length; i++) {
String fieldType = normalizeClassName(fieldTypes[i]);
@@ -305,7 +297,7 @@ static String[] getJDOSetFieldImpl(String fieldNumber, String objName, String[]
.append(fieldNames[i])
.append(" = ((").append(primClass)
.append(")").append(objName).append(").")
- .append(((String)typeNameConversion.get(fieldType)).toLowerCase())
+ .append(typeNameConversion.get(fieldType).toLowerCase())
.append("Value();").toString());
}
impl.add(" return;");
@@ -319,7 +311,7 @@ static String[] getJDOSetFieldImpl(String fieldNumber, String objName, String[]
// returnType = null means void
private static String[] getJDOStateManagerDelegationImpl(String delegation, String returnType) {
- final List impl = new ArrayList(7);
+ final List impl = new ArrayList<>(7);
impl.add((new StringBuffer("final "))
.append(CLASSNAME_JDO_STATE_MANAGER)
.append(" stateManager = this.")
@@ -337,7 +329,7 @@ private static String[] getJDOStateManagerDelegationImpl(String delegation, Stri
if (returnType != null) {
impl.add((new StringBuffer("return ")).append(returnType)
.append(";").toString());
- };
+ }
String[] strArr = new String[impl.size()];
return (String[])impl.toArray(strArr);
}
@@ -359,7 +351,7 @@ static String[] getJDOStateManagerBooleanDelegationImpl(String delegation) {
static String[] getOidHashCodeImpl(String[] pknames, String[] pktypes, boolean isRoot) {
- final List impl = new ArrayList(3);
+ final List impl = new ArrayList<>(3);
if (isRoot) {
impl.add("int hash = 0;");
} else {
@@ -387,7 +379,7 @@ static String[] getOidHashCodeImpl(String[] pknames, String[] pktypes, boolean i
static String[] getOidEqualsImpl(String oidClassName, String[] pknames, String[] pktypes, String pk,
boolean isRoot) {
- final List impl = new ArrayList(31);
+ final List impl = new ArrayList<>(31);
if (isRoot) {
impl.add("if (" + pk + " == null || !this.getClass().equals("
+ pk + ".getClass())) {");
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/generator/Main.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/generator/Main.java
index e90c3d638b7..233c0853ccf 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/generator/Main.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/generator/Main.java
@@ -1,6 +1,6 @@
/*
- * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
- * Copyright 2021 Contributors to the Eclipse Foundation
+ * Copyright 2021, 2026 Contributors to the Eclipse Foundation
+ * Copyright 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
@@ -17,7 +17,6 @@
package com.sun.jdo.api.persistence.enhancer.generator;
-import com.sun.jdo.api.persistence.enhancer.LogHelperEnhancer;
import com.sun.jdo.api.persistence.enhancer.meta.ExtendedJDOMetaData;
import com.sun.jdo.api.persistence.enhancer.meta.JDOMetaDataPropertyImpl;
import com.sun.jdo.api.persistence.enhancer.util.Assertion;
@@ -26,7 +25,6 @@
import com.sun.jdo.spi.persistence.utility.generator.JavaFileWriter;
import com.sun.jdo.spi.persistence.utility.generator.io.IOJavaClassWriter;
import com.sun.jdo.spi.persistence.utility.generator.io.IOJavaFileWriter;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import java.io.File;
import java.io.FileInputStream;
@@ -34,12 +32,16 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
+import java.lang.System.Logger;
import java.lang.reflect.Modifier;
import java.util.Properties;
import java.util.ResourceBundle;
import org.glassfish.persistence.common.I18NHelper;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.ERROR;
+
/**
*
@@ -57,7 +59,7 @@ public final class Main extends Assertion {
//
/** The logger */
- private static final Logger logger = LogHelperEnhancer.getLogger();
+ private static final Logger LOG = System.getLogger(Main.class.getName());
private static final String dotLine =
"----------------------------------------------------------------------";
/**
@@ -92,7 +94,7 @@ public final class Main extends Assertion {
/**
* I18N message handler
*/
- private final static ResourceBundle messages = I18NHelper.loadBundle("com.sun.jdo.api.persistence.enhancer.Bundle"); // NOI18N
+ private final static ResourceBundle messages = I18NHelper.loadBundle("com.sun.jdo.api.persistence.enhancer.Bundle");
public Main() {
}
@@ -114,8 +116,9 @@ public static final void main(String[] argv) {
gen.opts.processArgs(argv);
gen.init();
gen.generate();
- } catch(Exception ex) {
- gen.printError(null, ex);
+ } catch(Exception e) {
+ LOG.log(ERROR, "Generator failed.", e);
+ System.exit(1);
}
}
@@ -126,7 +129,6 @@ private class CmdLineOptions {
// final Collection inputFileNames = new ArrayList();
String destinationDirectory = null;
String jdoPropertiesFileName = null;
- boolean verbose = false;
/**
* Print a usage message to System.err
@@ -152,12 +154,12 @@ protected int processArgs(String[] argv) {
for (int i = 0; i < argv.length; i++) {
final String arg = argv[i];
if (arg.equals("-v") || arg.equals("--verbose")) {
- verbose = true;
+ // Was not used, we will ignore it for backward compatibility
continue;
}
if (arg.equals("-d") || arg.equals("--dest")) {
if (argv.length - i < 2) {
- printError("Missing argument to the -d/-dest option", null);
+ LOG.log(ERROR, "Missing argument to the -d/-dest option");
usage();
}
destinationDirectory = argv[++i];
@@ -165,18 +167,18 @@ protected int processArgs(String[] argv) {
}
if (arg.equals("-p") || arg.equals("--properties")) {
if (argv.length - i < 2) {
- printError("Missing argument to the -p/--properties option", null);
+ LOG.log(ERROR, "Missing argument to the -p/--properties option");
usage();
}
jdoPropertiesFileName = argv[++i];
continue;
}
if (arg.length() > 0 && arg.charAt(0) == '-') {
- printError("Unrecognized option:" + arg, null);
+ LOG.log(ERROR, "Unrecognized option: " + arg);
usage();
}
if (arg.length() == 0) {
- printMessage("Ignoring empty command line argument.");
+ LOG.log(DEBUG, "Ignoring empty command line argument.");
continue;
}
@@ -185,13 +187,13 @@ protected int processArgs(String[] argv) {
// The user must specify a destination directory
if (jdoPropertiesFileName == null) {
- printError("No destination directory specified", null);
+ LOG.log(ERROR, "No destination directory specified");
usage();
}
// The user must specify a destination directory
if (destinationDirectory == null) {
- printError("No destination directory specified", null);
+ LOG.log(ERROR, "No destination directory specified");
usage();
}
@@ -214,7 +216,7 @@ private void init() throws FileNotFoundException, IOException {
try {
finput.close();
} catch(Exception ex) {
- printError(ex.getMessage(), ex);
+ LOG.log(ERROR, ex.getMessage(), ex);
}
}
}
@@ -248,7 +250,7 @@ private void generate() throws IOException {
// at the beginning of this class.
public File generate(final String className) throws IOException {
affirm(className != null);
- printMessage("generating '" + className + "'...");
+ LOG.log(DEBUG, () -> "generating '" + className + "'...");
//@olsen, 4653156: fixed file name
final String filePath = className.replace('/', File.separatorChar);
@@ -267,7 +269,7 @@ public File generate(final String className) throws IOException {
writer = new IOJavaClassWriter();
generateClass(className);
fWriter.addClass(writer);
- printMessage("DONE generating '" + className + "'...");
+ LOG.log(DEBUG, () -> "DONE generating '" + className + "'...");
//@olsen: moved from finally{} to main block
// by JavaFileWriter, no stale resources remain allocated ever
@@ -358,7 +360,7 @@ private void writeClassMembers(final String className) throws IOException {
// write the fields and with their bean getters/setters
for (int i = 0; i < n; i++) {
- final String fieldName = (String)fieldNames[i];
+ final String fieldName = fieldNames[i];
writeFieldMember(className, fieldName);
}
}
@@ -706,21 +708,4 @@ private void writeOidClass(final String className, final String oidClassName, fi
static private String createMethodName(final String prefix, final String fieldName) {
return (prefix + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1));
}
-
-
- // XXX use common logger later
- private void printMessage(String msg) {
- logger.finest("TP PCClassGen: " + msg); // NOI18N
- }
-
-
- private void printError(String msg, Throwable ex) {
- if (msg != null) {
- String errmsg = msg + (ex != null ? ": " + ex.getMessage() : ""); // NOI18N
- logger.log(Logger.SEVERE, "CME.generic_exception", errmsg); // NOI18N
- }
- if (ex != null) {
- logger.log(Logger.SEVERE, "CME.generic_exception_stack", ex); // NOI18N
- }
- }
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/ClassAction.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/ClassAction.java
index 55942b1f8fd..9a0eedf152c 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/ClassAction.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/ClassAction.java
@@ -93,48 +93,48 @@ final class ClassAction
*/
/* Constants for the class level annotation attribute */
- private static final String AnnotatedAttribute = "com.sun.jdo.api.persistence.enhancer.annotated";//NOI18N
+ private static final String AnnotatedAttribute = "com.sun.jdo.api.persistence.enhancer.annotated";
private static final short AnnotatedVersion = 1;
//@olsen: added method name constants
static private final String jdoGetStateManagerName
- = "jdoGetStateManager";//NOI18N
+ = "jdoGetStateManager";
static private final String jdoSetStateManagerName
- = "jdoSetStateManager";//NOI18N
+ = "jdoSetStateManager";
static private final String jdoGetFlagsName
- = "jdoGetFlags";//NOI18N
+ = "jdoGetFlags";
static private final String jdoSetFlagsName
- = "jdoSetFlags";//NOI18N
+ = "jdoSetFlags";
static private final String jdoMakeDirtyName
- = "jdoMakeDirty";//NOI18N
+ = "jdoMakeDirty";
static private final String jdoIsDirtyName
- = "jdoIsDirty";//NOI18N
+ = "jdoIsDirty";
static private final String jdoIsTransactionalName
- = "jdoIsTransactional";//NOI18N
+ = "jdoIsTransactional";
static private final String jdoIsPersistentName
- = "jdoIsPersistent";//NOI18N
+ = "jdoIsPersistent";
static private final String jdoIsNewName
- = "jdoIsNew";//NOI18N
+ = "jdoIsNew";
static private final String jdoIsDeletedName
- = "jdoIsDeleted";//NOI18N
+ = "jdoIsDeleted";
static private final String jdoGetPersistenceManagerName
- = "jdoGetPersistenceManager";//NOI18N
+ = "jdoGetPersistenceManager";
static private final String jdoGetObjectIdName
- = "jdoGetObjectId";//NOI18N
+ = "jdoGetObjectId";
static private final String jdoConstructorName
- = "";//NOI18N
+ = "";
static private final String jdoNewInstanceName
- = "jdoNewInstance";//NOI18N
+ = "jdoNewInstance";
static private final String jdoClearName
- = "jdoClear";//NOI18N
+ = "jdoClear";
static private final String jdoCopyName
- = "jdoCopy";//NOI18N
+ = "jdoCopy";
static private final String jdoGetFieldName
- = "jdoGetField";//NOI18N
+ = "jdoGetField";
static private final String jdoSetFieldName
- = "jdoSetField";//NOI18N
+ = "jdoSetField";
static private final String jdoCloneName
- = "clone";//NOI18N
+ = "clone";
/* The class to be annotated */
//@olsen: made final
@@ -153,12 +153,12 @@ final class ClassAction
/* Hash table mapping ClassMethod to MethodAction */
//@olsen: made final
//@olsen: subst: Hashtable -> HashMap
- private final Map methodActionTable = new HashMap(11);
+ private final Map methodActionTable = new HashMap<>(11);
/* Vector of FieldAction */
//@olsen: made final
//@olsen: subst: Vector -> ArrayList
- private final List fieldActionTable = new ArrayList();
+ private final List fieldActionTable = new ArrayList<>();
/* What should we generate for this class?
* This is a combination of the GENXXXX constants defined above. */
@@ -186,8 +186,6 @@ interface if no base class does so. */
//@olsen: added fields
private boolean sawImplementsPersistenceCapable = false;
private boolean sawImplementsCloneable = false;
- private boolean sawFieldJDOStateManager = false;
- private boolean sawFieldJDOFlags = false;
private boolean sawMethodJDOGetStateManager = false;
private boolean sawMethodJDOSetStateManager = false;
private boolean sawMethodJDOGetFlags = false;
@@ -205,7 +203,6 @@ interface if no base class does so. */
private boolean sawMethodJDOGetField = false;
private boolean sawMethodJDOSetField = false;
private boolean sawMethodJDOClear = false;
- private boolean sawMethodJDOCopy = false;
private boolean sawMethodJDOClone = false;
/* True if the preDestroyPersistent() method needs to be generated
@@ -258,7 +255,7 @@ public ClassAction(ClassControl control,
//@olsen: dropped argument: boolean filterRequired
public void scan1() {
//@olsen: moved verbose output from ClassControl to ClassAction
- env.message("scanning class " + control.userClassName());//NOI18N
+ env.message("scanning class " + control.userClassName());
//@olsen: added constraints; ensured by ClassControl
affirm(!classFile().isInterface());
@@ -300,11 +297,12 @@ public void scan1() {
//@olsen: subst: augmentInterfaces -> augment
//@olsen: dropped argument: boolean filterRequired
public void augment() {
- if (previouslyAnnotated)
+ if (previouslyAnnotated) {
return;
+ }
if (implementsPersistence) {
- env.message("augmenting class " + control.userClassName());//NOI18N
+ env.message("augmenting class " + control.userClassName());
if (!sawImplementsPersistenceCapable) {
augmentClassInterface(JDOMetaData.JDOPersistenceCapablePath);
@@ -432,16 +430,17 @@ public void retarget(Map classTranslations,
* Perform the annotation operations for this class
*/
public void annotate() {
- if (previouslyAnnotated)
+ if (previouslyAnnotated) {
return;
+ }
//@olsen: moved verbose output from ClassControl to ClassAction
- env.message("annotating class " + control.userClassName());//NOI18N
+ env.message("annotating class " + control.userClassName());
boolean updates = false;
- for (Iterator e = methodActions(); e.hasNext(); ) {
- MethodAction methodAction = (MethodAction)e.next();
+ for (Iterator e = methodActions(); e.hasNext(); ) {
+ MethodAction methodAction = e.next();
if (methodAction.needsAnnotation()) {
methodAction.annotate();
updates = true;
@@ -504,14 +503,14 @@ ClassFile classFile() {
/**
* Return an Enumeration of the FieldActions for the class
*/
- Iterator fieldActions() {
+ Iterator fieldActions() {
return fieldActionTable.iterator();
}
/**
* Return an Enumeration of the MethodActions for the class
*/
- Iterator methodActions() {
+ Iterator methodActions() {
return methodActionTable.values().iterator();
}
@@ -566,61 +565,35 @@ public boolean hasCloneMethod() {
* This works even if scan1 hasn't run yet.
*/
public boolean hasAnnotatedAttribute() {
- if (previouslyAnnotated)
+ if (previouslyAnnotated) {
return true;
+ }
- Enumeration e = classFile().attributes().elements();
+ Enumeration e = classFile().attributes().elements();
while (e.hasMoreElements()) {
- ClassAttribute attr = (ClassAttribute) e.nextElement();
- if (attr.attrName().asString().equals(AnnotatedAttribute))
+ ClassAttribute attr = e.nextElement();
+ if (attr.attrName().asString().equals(AnnotatedAttribute)) {
return true;
+ }
}
return false;
}
- /**
- * Check whether this class has a persistent field of the
- * specified name. This might be called when the FieldActions have
- * not yet been built.
- */
-//@olsen: disabled feature
-/*
- boolean fieldIsPersistent(String fieldName) {
- ClassField field = classFile().findField(fieldName);
- if (field != null) {
- String className = classFile().className().asString();
- String fieldName = field.name().asString();
- //@olsen: disabled feature
- //return FieldAction.fieldIsPersistent(classFile(), field);
- return env.getJDOMetaData().isPersistentField(className, fieldName);
- }
- return false;
- }
-*/
-
- // private methods
-
/**
* Scans the attributes of a ClassFile
*/
private void scanAttributes() {
- Enumeration e = classFile().attributes().elements();
+ Enumeration e = classFile().attributes().elements();
while (e.hasMoreElements()) {
- ClassAttribute attr = (ClassAttribute) e.nextElement();
+ ClassAttribute attr = e.nextElement();
if (attr.attrName().asString().equals(AnnotatedAttribute)) {
previouslyAnnotated = true;
-//@olsen: disabled feature
-/*
- if (!control.isImplicitlyPersistent() && !env.updateInPlace()) {
-*/
- {
- // At some point we may want to consider stripping old
- // annotations and re-annotating, but not yet
- env.message("ignoring previously enhanced class "//NOI18N
- + control.userClassName());
- }
+ // At some point we may want to consider stripping old
+ // annotations and re-annotating, but not yet
+ env.message("ignoring previously enhanced class "
+ + control.userClassName());
break;
}
}
@@ -640,16 +613,16 @@ private void scanAttributes() {
*/
//@olsen: added method
private void scanForImplementsInterfaces() {
- for (Iterator ifc = classFile().interfaces().iterator();
+ for (Iterator ifc = classFile().interfaces().iterator();
ifc.hasNext();) {
- final ConstClass i = (ConstClass)ifc.next();
+ final ConstClass i = ifc.next();
String interfaceNamePath = i.asString();
if (interfaceNamePath.equals(JDOMetaData.JDOPersistenceCapablePath)) {
sawImplementsPersistenceCapable = true;
//@olsen: warn if user-defined 'implements PC' clause
env.warning(
- getI18N("enhancer.class_implements_jdo_pc",//NOI18N
+ getI18N("enhancer.class_implements_jdo_pc",
new Object[]{
userClassName(),
JDOMetaData.JDOPersistenceCapableType
@@ -659,16 +632,6 @@ private void scanForImplementsInterfaces() {
sawImplementsCloneable = true;
}
}
-
-//@olsen: disabled feature
-//@olsen: don't check whether this class implements PC indirectly
-/*
- if (control.implementsPersistenceCapable())
- env.warning(
- getI18N("enhancer.class_implements_pc",
- userClassName(),
- meta.JDOPersistenceCapableType));
-*/
}
/**
@@ -676,9 +639,9 @@ private void scanForImplementsInterfaces() {
* If this is not a persistence capable class, do nothing.
*/
private void scanFields() {
- Enumeration e = classFile().fields().elements();
+ Enumeration e = classFile().fields().elements();
while (e.hasMoreElements()) {
- final ClassField f = (ClassField)e.nextElement();
+ final ClassField f = e.nextElement();
final String fieldName = f.name().asString();
final String fieldSig = f.signature().asString();
@@ -699,25 +662,23 @@ private void scanForJDOFields(String fieldName,
String fieldSig) {
if (fieldName.equals(JDOMetaData.JDOStateManagerFieldName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_field",//NOI18N
+ getI18N("enhancer.class_defines_jdo_field",
userClassName(),
JDOMetaData.JDOStateManagerFieldName));
- sawFieldJDOStateManager = true;
return;
}
if (fieldName.equals(JDOMetaData.JDOFlagsFieldName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_field",//NOI18N
+ getI18N("enhancer.class_defines_jdo_field",
userClassName(),
JDOMetaData.JDOFlagsFieldName));
- sawFieldJDOFlags = true;
return;
}
//@olsen: check whether member starts with the reserved jdo prefix
- if (fieldName.startsWith("jdo")) {//NOI18N
+ if (fieldName.startsWith("jdo")) {
//@olsen: issue a warning only
env.warning(
- getI18N("enhancer.class_has_jdo_like_member",//NOI18N
+ getI18N("enhancer.class_has_jdo_like_member",
userClassName(), fieldName));
return;
}
@@ -730,9 +691,9 @@ private void scanMethods() {
final boolean isPersistent
= (control.persistType() == ClassControl.PersistCapable);
- Enumeration e = classFile().methods().elements();
+ Enumeration e = classFile().methods().elements();
while (e.hasMoreElements()) {
- final ClassMethod m = (ClassMethod)e.nextElement();
+ final ClassMethod m = e.nextElement();
final String methodName = m.name().asString();
final String methodSig = m.signature().asString();
@@ -755,84 +716,84 @@ private void scanForJDOMethods(String methodName,
String methodSig) {
if (methodName.equals(jdoGetStateManagerName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOGetStateManager = true;
return;
}
if (methodName.equals(jdoSetStateManagerName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOSetStateManager = true;
return;
}
if (methodName.equals(jdoGetFlagsName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOGetFlags = true;
return;
}
if (methodName.equals(jdoSetFlagsName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOSetFlags = true;
return;
}
if (methodName.equals(jdoMakeDirtyName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOMakeDirty = true;
return;
}
if (methodName.equals(jdoIsDirtyName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOIsDirty = true;
return;
}
if (methodName.equals(jdoIsTransactionalName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOIsTransactional = true;
return;
}
if (methodName.equals(jdoIsPersistentName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOIsPersistent = true;
return;
}
if (methodName.equals(jdoIsNewName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOIsNew = true;
return;
}
if (methodName.equals(jdoIsDeletedName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOIsDeleted = true;
return;
}
if (methodName.equals(jdoGetPersistenceManagerName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOGetPersistenceManager = true;
return;
}
if (methodName.equals(jdoGetObjectIdName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOGetObjectId = true;
return;
@@ -840,44 +801,43 @@ private void scanForJDOMethods(String methodName,
//^olsen: get signature from method builder
// for jdo constructor, check by name and signature
if (methodName.equals(jdoConstructorName)
- && methodSig.equals("(" + JDOMetaData.JDOStateManagerSig + ")V")) {//NOI18N
+ && methodSig.equals("(" + JDOMetaData.JDOStateManagerSig + ")V")) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOConstructor = true;
return;
}
if (methodName.equals(jdoNewInstanceName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDONewInstance = true;
return;
}
if (methodName.equals(jdoClearName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOClear = true;
return;
}
if (methodName.equals(jdoCopyName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
- sawMethodJDOCopy = true;
return;
}
if (methodName.equals(jdoGetFieldName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOGetField = true;
return;
}
if (methodName.equals(jdoSetFieldName)) {
env.error(
- getI18N("enhancer.class_defines_jdo_method",//NOI18N
+ getI18N("enhancer.class_defines_jdo_method",
userClassName(), methodName));
sawMethodJDOSetField = true;
return;
@@ -885,16 +845,16 @@ private void scanForJDOMethods(String methodName,
//^olsen: get signature from method builder
// for method clone(), check by name and signature
if (methodName.equals(jdoCloneName)
- && methodSig.equals("()Ljava/lang/Object;")) {//NOI18N
+ && methodSig.equals("()Ljava/lang/Object;")) {
// it's OK to have a user-defined clone()
sawMethodJDOClone = true;
return;
}
//@olsen: check whether member starts with the reserved jdo prefix
- if (methodName.startsWith("jdo")) {//NOI18N
+ if (methodName.startsWith("jdo")) {
//@olsen: issue a warning only
env.warning(
- getI18N("enhancer.class_has_jdo_like_member",//NOI18N
+ getI18N("enhancer.class_has_jdo_like_member",
userClassName(), methodName));
return;
}
@@ -955,9 +915,9 @@ private void insertPersistenceCapableFields(String fieldName,
control.noteUpdate();
// create it
- env.message("adding "//NOI18N
+ env.message("adding "
+ control.userClassName() +
- "." + fieldName + " " + printableFieldSig);//NOI18N
+ "." + fieldName + " " + printableFieldSig);
final ClassFile cfile = classFile();
final ConstantPool pool = cfile.pool();
@@ -985,161 +945,69 @@ private void insertPersistenceCapableMethods() {
control.noteUpdate();
- //@olsen: simplified generation of jdo[GS]etStateManager methods
+ // @olsen: simplified generation of jdo[GS]etStateManager methods
affirm(!sawMethodJDOGetStateManager);
- classFile().addMethod(
- methodBuilder.makeJDOGetStateManager(
- this,
- jdoGetStateManagerName));
+ classFile().addMethod(methodBuilder.makeJDOGetStateManager(this, jdoGetStateManagerName));
affirm(!sawMethodJDOSetStateManager);
- classFile().addMethod(
- methodBuilder.makeJDOSetStateManager(
- this,
- jdoSetStateManagerName));
+ classFile().addMethod(methodBuilder.makeJDOSetStateManager(this, jdoSetStateManagerName));
- //@olsen: simplified generation of jdo[GS]etFlags methods
+ // @olsen: simplified generation of jdo[GS]etFlags methods
affirm(!sawMethodJDOGetFlags);
- classFile().addMethod(
- methodBuilder.makeJDOGetFlags(
- this,
- jdoGetFlagsName));
+ classFile().addMethod(methodBuilder.makeJDOGetFlags(this, jdoGetFlagsName));
affirm(!sawMethodJDOSetFlags);
- classFile().addMethod(
- methodBuilder.makeJDOSetFlags(
- this,
- jdoSetFlagsName));
+ classFile().addMethod(methodBuilder.makeJDOSetFlags(this, jdoSetFlagsName));
- //@olsen: add generation of jdoMakeDirty() method
+ // @olsen: add generation of jdoMakeDirty() method
affirm(!sawMethodJDOMakeDirty);
- classFile().addMethod(
- methodBuilder.makeJDOMakeDirtyMethod(
- this,
- jdoMakeDirtyName));
+ classFile().addMethod(methodBuilder.makeJDOMakeDirtyMethod(this, jdoMakeDirtyName));
- //@olsen: add generation of JDO interrogative methods
+ // @olsen: add generation of JDO interrogative methods
affirm(!sawMethodJDOIsDirty);
- classFile().addMethod(
- methodBuilder.makeJDOInterrogativeMethod(
- this,
- jdoIsDirtyName));
+ classFile().addMethod(methodBuilder.makeJDOInterrogativeMethod(this, jdoIsDirtyName));
affirm(!sawMethodJDOIsTransactional);
- classFile().addMethod(
- methodBuilder.makeJDOInterrogativeMethod(
- this,
- jdoIsTransactionalName));
+ classFile().addMethod(methodBuilder.makeJDOInterrogativeMethod(this, jdoIsTransactionalName));
affirm(!sawMethodJDOIsPersistent);
- classFile().addMethod(
- methodBuilder.makeJDOInterrogativeMethod(
- this,
- jdoIsPersistentName));
+ classFile().addMethod(methodBuilder.makeJDOInterrogativeMethod(this, jdoIsPersistentName));
affirm(!sawMethodJDOIsNew);
- classFile().addMethod(
- methodBuilder.makeJDOInterrogativeMethod(
- this,
- jdoIsNewName));
+ classFile().addMethod(methodBuilder.makeJDOInterrogativeMethod(this, jdoIsNewName));
affirm(!sawMethodJDOIsDeleted);
- classFile().addMethod(
- methodBuilder.makeJDOInterrogativeMethod(
- this,
- jdoIsDeletedName));
+ classFile().addMethod(methodBuilder.makeJDOInterrogativeMethod(this, jdoIsDeletedName));
- //@olsen: add generation of jdoGetPersistenceManager method
+ // @olsen: add generation of jdoGetPersistenceManager method
affirm(!sawMethodJDOGetPersistenceManager);
- classFile().addMethod(
- methodBuilder.makeJDOGetPersistenceManagerMethod(
- this,
- jdoGetPersistenceManagerName));
+ classFile().addMethod(methodBuilder.makeJDOGetPersistenceManagerMethod(this, jdoGetPersistenceManagerName));
- //@olsen: add generation of jdoGetObjectId method
+ // @olsen: add generation of jdoGetObjectId method
affirm(!sawMethodJDOGetObjectId);
- classFile().addMethod(
- methodBuilder.makeJDOGetObjectIdMethod(
- this,
- jdoGetObjectIdName));
+ classFile().addMethod(methodBuilder.makeJDOGetObjectIdMethod(this, jdoGetObjectIdName));
- //@olsen: add generation of the JDO constructor
+ // @olsen: add generation of the JDO constructor
affirm(!sawMethodJDOConstructor);
- classFile().addMethod(
- methodBuilder.makeJDOConstructor(
- this,
- jdoConstructorName));
+ classFile().addMethod(methodBuilder.makeJDOConstructor(this, jdoConstructorName));
- //@olsen: add generation of the jdoNewInstance method
+ // @olsen: add generation of the jdoNewInstance method
affirm(!sawMethodJDONewInstance);
- classFile().addMethod(
- methodBuilder.makeJDONewInstanceMethod(
- this,
- jdoNewInstanceName));
+ classFile().addMethod(methodBuilder.makeJDONewInstanceMethod(this, jdoNewInstanceName));
- //@olsen: add generation of the jdoGetField method
+ // @olsen: add generation of the jdoGetField method
affirm(!sawMethodJDOGetField);
- classFile().addMethod(
- methodBuilder.makeJDOGetFieldMethod(
- this,
- jdoGetFieldName));
+ classFile().addMethod(methodBuilder.makeJDOGetFieldMethod(this, jdoGetFieldName));
- //@olsen: add generation of the jdoSetField method
+ // @olsen: add generation of the jdoSetField method
affirm(!sawMethodJDOSetField);
- classFile().addMethod(
- methodBuilder.makeJDOSetFieldMethod(
- this,
- jdoSetFieldName));
+ classFile().addMethod(methodBuilder.makeJDOSetFieldMethod(this, jdoSetFieldName));
- //@olsen: add generation of the jdoClear method
+ // @olsen: add generation of the jdoClear method
affirm(!sawMethodJDOClear);
- classFile().addMethod(
- methodBuilder.makeJDOClearMethod(
- this,
- jdoClearName));
-
- //@lars: removed jdoCopy-method creation
- //@olsen: add generation of the jdoCopy method
- /*
- affirm(!sawMethodJDOCopy);
- classFile().addMethod(
- methodBuilder.makeJDOCopyMethod(
- this,
- jdoCopyName));
- */
-
- //@olsen: generate method clone() if not present
+ classFile().addMethod(methodBuilder.makeJDOClearMethod(this, jdoClearName));
+
+ // @olsen: generate method clone() if not present
if (!sawMethodJDOClone) {
- classFile().addMethod(
- methodBuilder.makeJDOClone(
- this,
- jdoCloneName));
+ classFile().addMethod(methodBuilder.makeJDOClone(this, jdoCloneName));
}
}
- /**
- * Add all the methods required for com.sun.jdo.spi.persistence.support.sqlstore.PersistenceCapableHooks interface.
- */
-//@olsen: disabled feature
-/*
- private void insertPersistenceCapableHooksMethods() {
- if (needsPreDestroyPersistent)
- classFile().addMethod
- (methodBuilder.makeNullMethod(this, "preDestroyPersistent"));
-
- if (needsPostInitializeContents)
- classFile().addMethod
- (methodBuilder.makeNullMethod(this, "postInitializeContents"));
-
- if (needsPreFlushContents)
- classFile().addMethod
- (methodBuilder.makeNullMethod(this, "preFlushContents"));
-
- if (needsPreClearContents)
- classFile().addMethod
- (methodBuilder.makeNullMethod(this, "preClearContents"));
-
- if (needsPreDestroyPersistent || needsPostInitializeContents
- || needsPreFlushContents || needsPreClearContents)
- control.noteUpdate();
- }
-*/
-
/**
* Add the specified interface to list.
*/
@@ -1148,8 +1016,7 @@ private void augmentClassInterface(String interfaceName) {
ClassFile cfile = classFile();
ConstClass iface = cfile.pool().addClass(interfaceName);
//@olsen: moved output to here
- env.message("adding implements "//NOI18N
- + ClassControl.userClassFromVMClass(interfaceName));
+ env.message("adding implements " + ClassControl.userClassFromVMClass(interfaceName));
cfile.addInterface(iface);
}
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/EnhancerControl.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/EnhancerControl.java
index 4b7c5850170..7a0b5fec144 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/EnhancerControl.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/EnhancerControl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -16,51 +17,15 @@
package com.sun.jdo.api.persistence.enhancer.impl;
-//@olsen: added general support
import com.sun.jdo.api.persistence.enhancer.util.Support;
-import java.util.ArrayList;
import java.util.Iterator;
-
-//@olsen: disabled feature
-/*
-import com.sun.jdo.api.persistence.enhancer.classfile.ClassFile;
-*/
-
-//@olsen: disabled feature
-/*
-import com.sun.jdo.api.persistence.enhancer.impl.FieldMap;
-*/
-
-//lars: made the class public to access it from the root package
-//lars: moved from root package into impl-subpackage
-//@olsen: cosmetics
-//@olsen: subst: [iI]Persistent -> [pP]ersistenceCapable
-//@olsen: subst: /* ... */ -> // ...
-//@olsen: moved: class FilterError -> package util
-//@olsen: moved: OSCFP.addClass(ClassControl) -> impl.Environment
-//@olsen: subst: filterEnv.classMap.elements() -> filterEnv.getClasses()
-//@olsen: subst: filterEnv.classMap.get(name) -> filterEnv.getClass(name)
-//@olsen: subst: filterEnv.translations -> filterEnv.translations()
-//@olsen: subst: OSCFP -> Main
-//@olsen: subst: filterEnv -> env
-//@olsen: subst: FilterEnv -> Environment
-//@olsen: dropped parameter 'Environment env', use association instead
-//@olsen: subst: augment -> closeOver
-//@olsen: subst: collectAllClasses -> collectClasses
-//@olsen: subst: Vector -> Collection, List, ArrayList
-//@olsen: subst: Hashtable -> Map, HashMap
-//@olsen: subst: Enumeration,... -> Iterator, hasNext(), next()
-//@olsen: removed: proprietary support for IndexableField
-
+import java.util.List;
/**
* Main is the starting point for the persistent filter tool.
*/
-//@olsen: added local class
-public class EnhancerControl
-//extends Support
-{
+public class EnhancerControl {
/* Central repository for the options selected by
* the user and the current state of the Filter execution */
@@ -73,149 +38,6 @@ public EnhancerControl(Environment env) {
this.env = env;
}
- /**
- * Extend the class map so that persistent classes are closed over
- */
-//@olsen: inlined method
-/*
- //@olsen: moved: Main.closeOverClasses() -> EnhancerControl
- //@olsen: made public
- public void closeOverClasses() {
- ArrayList v = env.collectClasses(ClassControl.PersistCapable);
- for (Iterator e = v.iterator(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
- closeOverClass(cc);
- }
- }
-*/
-
- /**
- * Extend the class map so that all base classes of the specified
- * class are included, if possible. The specified class is assumed
- * to already be on the persistent class list.
- */
-//@olsen: disabled feature
-/*
- //@olsen: moved: Main.closeOverClass(ClassControl startCC) -> EnhancerControl
- //@olsen: made public
- public void closeOverClass(ClassControl startCC) {
- final JDOMetaData jdoMetaData = env.getJDOMetaData();
- String className = startCC.classFile().className().asString();
- String baseClassName = startCC.classFile().superName().asString();
- while (true) {
- //@olsen: added final
- final ClassControl cc = env.findClass(baseClassName);
-
- if (cc == null) {
- // We can't find the class file
- // perhaps a mechanism to only produce the error would be nice
- env.error("Unable to locate class " +
- ClassControl.userClassFromVMClass(baseClassName));
- return;
- }
-
- if (baseClassName.equals("java/lang/Object"))
- //@olsen: subst: break -> return
- return;
-
-//@olsen: disabled feature
-///
- //@olsen: not used
- //String ccPkg = cc.pkg();
- if (baseClassName.startsWith("java/") &&
- !cc.implementsPersistenceCapable() &&
- !env.modifyJavaClasses()) {
- env.error("Sorry, java types can not be made persistent. " +
- "Class " +
- ClassControl.userClassFromVMClass(className) +
- " extends " +
- ClassControl.userClassFromVMClass(baseClassName) +
- ". See the -modifyjava option if you really " +
- "want to do this.");
- return;
- }
-
- if (baseClassName.startsWith("com/ms/com/")) {
- env.error("Sorry, Microsoft COM types can not be made persistent. " +
- "Class " +
- ClassControl.userClassFromVMClass(className) +
- " extends " +
- ClassControl.userClassFromVMClass(baseClassName) +
- ".");
- return;
- }
-///
-
- //cc.setPersistType(ClassControl.PersistCapable);
-
- //@olsen: set persisence type of class by JDO meta-data
- if (jdoMetaData.isPersistenceCapableClass(baseClassName)) {
- //cc.setPersistType(ClassControl.PersistCapable);
- cc.setInitialPersistType(ClassControl.PersistCapable);
-
- //@olsen: impose limitation
- env.error("Sorry, in this release a persistent class cannot have a persistent super-class. " +
- "Persistent class " +
- ClassControl.userClassFromVMClass(className) +
- " (indirectly) extends persistent class " +
- ClassControl.userClassFromVMClass(baseClassName) +
- ".");
- return;
- } else if (baseClassName.startsWith("java/")) {
- //cc.setPersistType(ClassControl.TransientOnly);
- cc.setInitialPersistType(ClassControl.TransientOnly);
-
- // may stop when transient root class found
- return;
- }
-
-//@olsen: disabled feature
-///
- if (cc.persistType() == ClassControl.PersistCapable) {
- // The base class is already on the persistent-capable list
- // so we're all done here
- return;
- }
- if (cc.implementsPersistenceCapable()) {
- // The class already inherits from Persistent. It's probably
- // ok to update if necessary
- env.message("Promoting " + cc.userClassName() +
- " to persistence-capable.");
- cc.setPersistType(ClassControl.PersistCapable);
- cc.setImplicitlyPersistent(true);
- } else if (cc.persistType() == ClassControl.PersistUnknown) {
- if (cc.pkg().equals(startCC.pkg())) {
- // It's ok to make this base class persistent too.
- env.message("Including class " + cc.userClassName() +
- " as a persistence capable class.");
- cc.setPersistType(ClassControl.PersistCapable);
- cc.setImplicitlyPersistent(true);
- } else {
- // Ought to be more clever here as this class may be
- // pulled in through another persistence path later on
- env.error("Class " + cc.userClassName() +
- " must be persistent to allow " +
- startCC.userClassName() +
- " to be persistent.");
- return;
- }
- } else {
- // Ought to be more clever here as this class may be pulled in
- // through another persistence path later on
- env.error("Class " + cc.userClassName() +
- " must be persistent to allow " +
- startCC.userClassName() +
- " to be persistent.");
- return;
- }
-///
-
- // Move on to the next base class
- baseClassName = cc.classFile().superName().asString();
- }
- }
-*/
-
/**
* Dumps a class' signature and byte-code.
*/
@@ -242,15 +64,15 @@ public void modifyClasses() {
if (env.doTimingStatistics()) {
Support.timer.push("EnhancerControl.modifyClasses()");//NOI18N
}
- final ArrayList classes = env.collectClasses();
+ final List classes = env.collectClasses();
if (classes.size() > 1) {
env.messageNL("scanning classes");//NOI18N
}
// First examine the classes, noting the class characteristics
- for (Iterator e = classes.iterator(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
+ for (Iterator e = classes.iterator(); e.hasNext();) {
+ ClassControl cc = e.next();
cc.scan1();
if (false) {
@@ -258,22 +80,17 @@ public void modifyClasses() {
}
}
-//@olsen: disabled feature
-/*
- // Possibly update package names
- retargetClasses();
-*/
-
- if (env.errorCount() > 0)
+ if (env.errorCount() > 0) {
return;
+ }
if (classes.size() > 1) {
env.messageNL("augmenting classes");//NOI18N
}
// Change class inheritance
- for (Iterator e = classes.iterator(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
+ for (Iterator e = classes.iterator(); e.hasNext();) {
+ ClassControl cc = e.next();
//@olsen: subst: augmentInterfaces -> augment
cc.augment();
@@ -282,16 +99,17 @@ public void modifyClasses() {
}
}
- if (env.errorCount() > 0)
+ if (env.errorCount() > 0) {
return;
+ }
if (classes.size() > 1) {
env.messageNL("annotating classes");//NOI18N
}
// Then perform the annotation actions
- for (Iterator e = classes.iterator(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
+ for (Iterator e = classes.iterator(); e.hasNext();) {
+ ClassControl cc = e.next();
cc.annotate();
if (false) {
@@ -304,126 +122,4 @@ public void modifyClasses() {
}
}
}
-
- /**
- * Build a ArrayList of strings which are the names of the
- * persistent classes in this enhancer's run.
- */
-//@olsen: disabled feature
-/*
- private ArrayList computePersistentClasses() {
- ArrayList v = new ArrayList();
- Iterator allClasses = env.getClasses();
- while (allClasses.hasNext()) {
- ClassControl cc = (ClassControl)allClasses.next();
- if (cc.isExplicitlyNamed() && cc.persistCapable())
- v.add(cc.userClassName());
- }
- return v;
- }
-*/
-
- /**
- * For each class in the class map which isn't transient-only,
- * apply package name translations to update class references
- */
-//@olsen: disabled feature
-/*
- //@olsen: moved: Main.retargetClasses() -> EnhancerControl
- private void retargetClasses() {
-
- if (env.translations().size() == 0)
- return;
-
- locateTranslatedClasses();
-
- //@olsen: made classMap local in Environment
- //if (env.classMap.size() > 0) {
- {
- ArrayList translatable = new ArrayList();
- Map classTranslations = new HashMap();
-
- // Compute the full set of class translations
- for (Iterator e = env.getClasses(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
- String pkg = cc.pkg();
- String xlat = (String)env.translations().get(pkg);
- if (xlat != null || cc.annotateable()) {
- translatable.add(cc);
-
- if (xlat != null) {
- String newName;
- if (xlat.length() == 0)
- newName = cc.unpackagedName();
- else
- newName = xlat + "/" + cc.unpackagedName();
- if (!newName.equals(cc.className())) {
- ClassControl existingCC =
- (ClassControl)env.getClass(newName);
-
- if (existingCC != null) {
- env.error("The package translations specified would " +
- "cause " + cc.userClassName() +
- " to be translated to " +
- existingCC.userClassName() +
- " which already exists.");
- } else
- classTranslations.put(cc.className(), newName);
- }
- }
- }
- }
-
- if (env.errorCount() > 0)
- return;
-
- if (classTranslations.size() == 0) {
- env.warning("No package name translations are being applied");
- }
- else {
- env.message();
- env.message("doing package name translations");
-
- for (Iterator e = translatable.iterator(); e.hasNext();) {
- final ClassControl cc = (ClassControl)e.next();
- final String className = cc.className();
- cc.retarget(classTranslations);
-
- //@olsen: use added method
- env.renameClass(className);
-//
- // Add the modified name to the class map if the class
- // name has changed.
- String newClassName = cc.className();
- env.classMap.remove(className);
- env.renamedMap.put(className, cc);
- env.classMap.put(newClassName, cc);
-//
- }
- }
- }
- }
-*/
-
- /**
- * For each package name translation selected, find all classes in the
- * package and add to the class map.
- */
-//@olsen: disabled feature
-/*
- //@olsen: moved: Main.locateTranslatedClasses() -> EnhancerControl
- private void locateTranslatedClasses() {
- // Compute the full set of class translations
- for (Iterator e = env.translations().keySet().iterator();
- e.hasNext();) {
- String pkg = (String)e.next();
-
- for (Enumeration pe = env.classPathOption().classesInPackage(pkg);
- pe.hasMoreElements();) {
- String className = (String)pe.nextElement();
- env.findClass(className);
- }
- }
- }
-*/
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/Environment.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/Environment.java
index 62d127661d2..965c3767263 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/Environment.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/Environment.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -27,6 +28,7 @@
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
+import java.util.List;
//@lars added: field for last error message
@@ -132,46 +134,31 @@ public final class Environment
private File destinationDirectory = null;
/* Hash VM class name to ClassControl */
- private Hashtable classMap = new Hashtable(11);
+ private Hashtable classMap = new Hashtable<>(11);
/* Set of classes that were looked up but not found. */
//@olsen: subst: Hashtable -> HashMap
- private HashMap missingClasses = new HashMap(11);
-
- /* Hash VM class name to ClassControl
- * Entries in this table have been renamed and the class control
- * reflects the updated name */
-//@olsen: inlined method
-/*
- private Hashtable renamedMap = new Hashtable(203);
-*/
-
- /* explicit package name translations
- * Maps string to string */
-//@olsen: disabled feature
-/*
- private Hashtable translations = new Hashtable(11);
-*/
+ private HashMap missingClasses = new HashMap<>(11);
/* Search path to be used for locating classes */
//@olsen: added default initialization
- private ClassPath classPathOption = new ClassPath("");//NOI18N
+ private ClassPath classPathOption = new ClassPath("");
/* Search path to be used for locating annotated classes in output dir */
private ClassPath destClassPath;
/* A set of fully qualified field names (maps name to itself) */
- private Hashtable fieldSuppressions = new Hashtable();
+ private Hashtable fieldSuppressions = new Hashtable<>();
/* A set of fully qualified class names (maps name to itself) */
- private Hashtable classSuppressions = new Hashtable();
+ private Hashtable classSuppressions = new Hashtable<>();
/* The instance providing the JDO meta data. */
//@olsen: added field
private JDOMetaData jdoMetaData;
/* Last error message */
- private String lastErrorMessage = null;
+ private String lastErrorMessage;
// public accessors
@@ -201,7 +188,7 @@ public void warning(String warn) {
//@olsen: redirected output
//System.out.print("Warning: ");
//System.out.println(warn);
- out.println(getI18N("enhancer.warning", warn));//NOI18N
+ out.println(getI18N("enhancer.warning", warn));
}
}
@@ -212,7 +199,7 @@ public void warning(String warn, String classname) {
//@olsen: redirected output
//System.out.print("Warning: ");
//System.out.println(warn);
- out.println(getI18N("enhancer.warning", warn));//NOI18N
+ out.println(getI18N("enhancer.warning", warn));
}
}
@@ -224,7 +211,7 @@ public void warning(String warn, String classname, String fieldname) {
//@olsen: redirected output
//System.out.print("Warning: ");
//System.out.println(warn);
- out.print(getI18N("enhancer.warning", warn));//NOI18N
+ out.print(getI18N("enhancer.warning", warn));
}
}
@@ -232,7 +219,7 @@ public void message(String mess) {
if (verboseOption) {
//@olsen: redirected output
//System.out.println(mess);
- out.println("JDO ENHANCER: " + mess);//NOI18N
+ out.println("JDO ENHANCER: " + mess);
}
}
@@ -241,7 +228,7 @@ public void messageNL(String mess) {
//@olsen: redirected output
//System.out.println(mess);
out.println();
- out.println("JDO ENHANCER: " + mess);//NOI18N
+ out.println("JDO ENHANCER: " + mess);
}
}
@@ -430,7 +417,7 @@ public void addClass(ClassControl cc) {
if (!existCC.source().sameAs(cc.source())) {
//@olsen: support for I18N
- error(getI18N("enhancer.class_already_entered",//NOI18N
+ error(getI18N("enhancer.class_already_entered",
cc.userClassName(),
cc.sourceName(),
existCC.sourceName()));
@@ -442,32 +429,20 @@ public void addClass(ClassControl cc) {
if (cc.persistType() == ClassControl.PersistUnknown ||
existCC.persistType() == ClassControl.PersistCapable ||
(existCC.persistType() == ClassControl.PersistAware &&
- cc.persistType() != ClassControl.PersistCapable))
+ cc.persistType() != ClassControl.PersistCapable)) {
return;
+ }
}
- if (existCC == null && cc.sourceName() != null)
- message("adding class " + cc.userClassName() +//NOI18N
- " from " + cc.sourceName());//NOI18N
+ if (existCC == null && cc.sourceName() != null) {
+ message("adding class " + cc.userClassName() +
+ " from " + cc.sourceName());
+ }
classMap.put(className, cc);
}
- /**
- * Add the modified name to the class map if the class name has changed.
- */
- //@olsen: added method
-//@olsen: disabled feature
-/*
- public void renameClass(String oldClassName) {
- ClassControl cc = (ClassControl)classMap.remove(oldClassName);
- String newClassName = cc.className();
- renamedMap.put(oldClassName, cc);
- classMap.put(newClassName, cc);
- }
-*/
-
/**
* Look for the specified class in the class map. If not there,
* use the class path to find the class. If still not found,
@@ -483,11 +458,11 @@ public boolean canFindClass(String className) {
* class will have been found.
*/
public ClassControl getClass(String className) {
- return (ClassControl)classMap.get(className);
+ return classMap.get(className);
}
//@olsen: added method
- public Iterator getClasses() {
+ public Iterator getClasses() {
return classMap.values().iterator();
}
@@ -497,15 +472,15 @@ public Iterator getClasses() {
* return false.
*/
public ClassControl findClass(String className) {
- ClassControl cc = (ClassControl) classMap.get(className);
+ ClassControl cc = classMap.get(className);
if ((cc == null) && (missingClasses.get(className) == null)) {
// Not already known - try looking up in class path
cc = lookupClass(className);
if (cc != null) {
- message("Reading class " + cc.userClassName() +//NOI18N
- " from " + cc.sourceName());//NOI18N
+ message("Reading class " + cc.userClassName() +
+ " from " + cc.sourceName());
classMap.put(className, cc);
} else {
missingClasses.put(className, className);
@@ -524,15 +499,17 @@ public ClassControl lookupClass(String className) {
ClassFileSource source = classPathOption.findClass(className);
while (true) {
- if (source == null)
+ if (source == null) {
return null;
+ }
//@olsen: cosmetics
try {
ClassControl cc = new ClassControl(source, this);
if (cc.className() != null &&
- cc.className().equals(className))
+ cc.className().equals(className)) {
return cc;
+ }
} catch (ClassFormatError e) {
}
@@ -557,12 +534,13 @@ public ClassControl getRenamedClass(String className) {
* Return a ArrayList of ClassControl objects which have the specified
* persistence type
*/
- public ArrayList collectClasses(int persistType) {
- ArrayList v = new ArrayList();
- for (Iterator e = classMap.values().iterator(); e.hasNext();) {
- ClassControl cc = (ClassControl)e.next();
- if (cc.persistType() == persistType)
+ public List collectClasses(int persistType) {
+ ArrayList v = new ArrayList<>();
+ for (Iterator e = classMap.values().iterator(); e.hasNext();) {
+ ClassControl cc = e.next();
+ if (cc.persistType() == persistType) {
v.add(cc);
+ }
}
return v;
}
@@ -571,10 +549,11 @@ public ArrayList collectClasses(int persistType) {
* Return an ArrayList of the ClassControls in classMap.
* This is useful in that it provides a stable base for enumeration.
*/
- public ArrayList collectClasses() {
- ArrayList v = new ArrayList();
- for (Iterator e = classMap.values().iterator(); e.hasNext(); )
+ public List collectClasses() {
+ ArrayList v = new ArrayList<>();
+ for (Iterator e = classMap.values().iterator(); e.hasNext(); ) {
v.add(e.next());
+ }
return v;
}
@@ -585,8 +564,9 @@ public ArrayList collectClasses() {
* for the class specified. Return null if not found.
*/
public ClassFileSource lookupDestClass(String className) {
- if (destClassPath == null && destinationDirectory != null)
+ if (destClassPath == null && destinationDirectory != null) {
destClassPath = new ClassPath(destinationDirectory.getPath());
+ }
return (destClassPath == null
? null : destClassPath.findClass(className));
}
@@ -600,25 +580,17 @@ public ClassFileSource lookupDestClass(String className) {
public Environment() {
}
-//@olsen: disabled feature
-/*
- public void setClassPath(String path) {
- message("setting class path to " + path);
- classPathOption = new ClassPath(path);
- }
-*/
-
public void setDestinationDirectory(String dir) {
final File dest = new File(dir);
if (destinationDirectory != null) {
//@olsen: support for I18N
- error(getI18N("destination_directory_already_set",//NOI18N
+ error(getI18N("destination_directory_already_set",
dir,
destinationDirectory.getPath()));
return;
}
if (!dest.isDirectory()) {
- error(getI18N("enhancer.destination_directory_not_exist",//NOI18N
+ error(getI18N("enhancer.destination_directory_not_exist",
dir));
return;
}
@@ -630,8 +602,9 @@ public void setDestinationDirectory(String dir) {
* is found in the class path.
*/
public void excludeDestinationDirectory() {
- if (destinationDirectory != null)
+ if (destinationDirectory != null) {
classPathOption.remove(destinationDirectory);
+ }
}
/**
@@ -640,8 +613,9 @@ public void excludeDestinationDirectory() {
*/
public void moveDestinationDirectoryToEnd() {
if (destinationDirectory != null &&
- classPathOption.remove(destinationDirectory))
+ classPathOption.remove(destinationDirectory)) {
classPathOption.append(destinationDirectory);
+ }
}
//@olsen: added method
@@ -782,25 +756,29 @@ static String validVMPackage(String pkg) {
while (i tmpRegisters;
/* List of double element register values (Integer) for temporaries */
- private Vector tmpDoubleRegisters;
+ private Vector tmpDoubleRegisters;
/* List of single word register values which cache fetches/stores
* Each of these registers must be initialized to null at the start of
@@ -162,7 +163,7 @@ class MethodAnnotater
/* Table mapping Insn to InsnNote - allows annotation computations to
* be attached to instructions non-intrusively */
- private Map insnNotes = new HashMap(11);
+ private Map insnNotes = new HashMap<>(11);
/* The largest loop contained within the method, or null. */
//@olsen: disabled feature
@@ -603,8 +604,9 @@ private InsnNote noteGetFieldAnnotation(Insn insn) {
final String fieldName
= fieldRef.nameAndType().name().asString();
final JDOMetaData meta = env.getJDOMetaData();
- if (!meta.isPersistentField(fieldOf, fieldName))
+ if (!meta.isPersistentField(fieldOf, fieldName)) {
return null;
+ }
//@olsen: disabled feature
/*
@@ -645,19 +647,22 @@ private InsnNote noteGetFieldAnnotation(Insn insn) {
Insn dep = findArgDepositer(insn, stackArgSize);
if (dep != null
&& dep.opcode() == opc_aload_0
- && !method.isStatic())
+ && !method.isStatic()) {
// This represents a fetch of "this"
flags |= FetchThis;
- else
+ } else {
flags |= FetchPersistent;
+ }
//@olsen: added test
- if (dfgField)
+ if (dfgField) {
flags |= DFGField;
+ }
//@olsen: added test
- if (pkField)
+ if (pkField) {
flags |= PKField;
+ }
//@olsen: changed to use JDOMetaData
return new InsnNote(insn, flags,
@@ -684,8 +689,9 @@ private InsnNote notePutFieldAnnotation(Insn insn) {
final String fieldName
= fieldRef.nameAndType().name().asString();
final JDOMetaData meta = env.getJDOMetaData();
- if (!meta.isPersistentField(fieldOf, fieldName))
+ if (!meta.isPersistentField(fieldOf, fieldName)) {
return null;
+ }
//@olsen: disabled feature
/*
@@ -727,19 +733,22 @@ private InsnNote notePutFieldAnnotation(Insn insn) {
Insn dep = findArgDepositer(insn, stackArgSize);
if (dep != null
&& dep.opcode() == opc_aload_0
- && !method.isStatic())
+ && !method.isStatic()) {
// This represents a dirtyfication of "this"
flags |= DirtyThis;
- else
+ } else {
flags |= DirtyPersistent;
+ }
//@olsen: added test
- if (dfgField)
+ if (dfgField) {
flags |= DFGField;
+ }
//@olsen: added test
- if (pkField)
+ if (pkField) {
flags |= PKField;
+ }
//@olsen: changed to use JDOMetaData
return new InsnNote(insn, flags,
@@ -845,8 +854,9 @@ private InsnNote noteArrayStoreAnnotation(Insn insn) {
void annotateMethod() {
//@olsen: cosmetics
final CodeAttribute codeAttr = method.codeAttribute();
- if (codeAttr == null || !needsAnnotation())
+ if (codeAttr == null || !needsAnnotation()) {
return;
+ }
//@olsen: disabled feature
/*
@@ -1039,8 +1049,9 @@ void annotateMethod() {
}
*/
- if (annotationStack > 0)
+ if (annotationStack > 0) {
codeAttr.setStackUsed(codeAttr.stackUsed() + annotationStack);
+ }
}
// ---------------------------------------------------------------------------
@@ -1202,8 +1213,9 @@ private void annotateClone(CodeAttribute codeAttr,
// which does a super.clone() call, and if it is, add
// field initializations for the jdoStateManager and jdoFlags
// fields.
- if (insn.opcode() != opc_invokespecial)
+ if (insn.opcode() != opc_invokespecial) {
continue;
+ }
final InsnConstOp invoke = (InsnConstOp)insn;
final ConstMethodRef methodRef = (ConstMethodRef)invoke.value();
@@ -1212,8 +1224,9 @@ private void annotateClone(CodeAttribute codeAttr,
final String methodSig = methodNT.signature().asString();
if (!(methodName.equals("clone")//NOI18N
- && methodSig.equals("()Ljava/lang/Object;")))//NOI18N
+ && methodSig.equals("()Ljava/lang/Object;"))) { //NOI18N
continue;
+ }
if (false) {
final ConstClass methodClass = methodRef.className();
@@ -1443,8 +1456,9 @@ private Insn insnAnnotation(final Insn insn) {
note = note.next()) { ... }
*/
InsnNote note = getNoteList(insn);
- if (note == null)
+ if (note == null) {
return insn;
+ }
//@olsen: ensured to use single note only (as instantiated)
affirm(insn == note.insn);
@@ -1556,7 +1570,7 @@ private Insn insnAnnotation(final Insn insn) {
// The value is hidden by 2 or more stack operands. Move
// the obscuring values into temporaries to get access to
// the value - put them back when done
- Stack stackTypes = state.stackTypes;
+ Stack stackTypes = state.stackTypes;
int depth = state.argDepth;
int elem = stackTypes.size()-1;
@@ -1568,7 +1582,7 @@ private Insn insnAnnotation(final Insn insn) {
// Now, move values into temp registers
while (depth > 0) {
int elemType =
- ((Integer)stackTypes.elementAt(elem--)).intValue();
+ stackTypes.elementAt(elem--).intValue();
int elemSize = Descriptor.elementSize(elemType);
depth -= elemSize;
int reg = ((elemSize == 1)
@@ -1577,20 +1591,22 @@ private Insn insnAnnotation(final Insn insn) {
regnums[regtotal++] = reg;
Insn store = InsnUtils.store(elemType, reg, pool);
- if (annotation == null)
+ if (annotation == null) {
annotation = store;
- else
+ } else {
annotation.append(store);
+ }
}
affirm((depth >= 0),
"Stack underflow while computing save registers");//NOI18N
annotation.append(frag0.annotation);
- while (regtotal > 0)
+ while (regtotal > 0) {
annotation.append(InsnUtils.load(
- ((Integer)stackTypes.elementAt(++elem)).intValue(),
+ stackTypes.elementAt(++elem).intValue(),
regnums[--regtotal], pool));
+ }
noteStack(frag0.stackRequired - note.arg());
}
@@ -2223,19 +2239,20 @@ String arrayFetchSignature(int arrayElementType) {
* specified temporary hasn't been allocated, allocated it now.
*/
private int tmpReg2(int idx) {
- if (tmpDoubleRegisters == null)
- tmpDoubleRegisters = new Vector(3);
+ if (tmpDoubleRegisters == null) {
+ tmpDoubleRegisters = new Vector<>(3);
+ }
// allocated as many 2 register pairs as necessary in order to
// make idx be a valid index
while (tmpDoubleRegisters.size() <= idx) {
final CodeAttribute codeAttr = method.codeAttribute();
final int reg = codeAttr.localsUsed();
- tmpDoubleRegisters.addElement(new Integer(reg));
+ tmpDoubleRegisters.addElement(Integer.valueOf(reg));
codeAttr.setLocalsUsed(reg+2);
}
- return ((Integer)tmpDoubleRegisters.elementAt(idx)).intValue();
+ return tmpDoubleRegisters.elementAt(idx).intValue();
}
/**
@@ -2244,57 +2261,30 @@ private int tmpReg2(int idx) {
* specified temporary hasn't been allocated, allocated it now.
*/
private int tmpReg(int idx) {
- if (tmpRegisters == null)
- tmpRegisters = new Vector(3);
+ if (tmpRegisters == null) {
+ tmpRegisters = new Vector<>(3);
+ }
// allocate as many registers as necessary in order to
// make idx be a valid index
while (tmpRegisters.size() <= idx) {
final CodeAttribute codeAttr = method.codeAttribute();
final int reg = codeAttr.localsUsed();
- tmpRegisters.addElement(new Integer(reg));
+ tmpRegisters.addElement(Integer.valueOf(reg));
codeAttr.setLocalsUsed(reg+1);
}
- return ((Integer)tmpRegisters.elementAt(idx)).intValue();
- }
-
- /**
- * Allocate an object fetch/store cache slot
- */
-//@olsen: disabled feature
-/*
- private int newCacheSlot() {
- CodeAttribute codeAttr = method.codeAttribute();
- int slot = codeAttr.localsUsed();
- codeAttr.setLocalsUsed(slot+1);
- if (caches == null)
- caches = new Vector(3);
- caches.addElement(new Integer(slot));
- return slot;
+ return tmpRegisters.elementAt(idx).intValue();
}
-*/
/**
* Note the following amount of stack used by a single annotation.
*/
private void noteStack(int stk) {
- if (stk > annotationStack)
+ if (stk > annotationStack) {
annotationStack = (short)stk;
+ }
}
- /**
- * Is this a non-static method of a persistence-capable class?
- */
-//@olsen: disabled feature
-/*
- private boolean thisIsPersistent() {
- return (ca.persistCapable() &&
- !method.isStatic());
- }
-*/
-
-// ---------------------------------------------------------------------------
-
/**
* Attempt to locate the instruction which deposits to the top of stack
* the 1 word stack argument to currInsn which is argDepth deep on the
@@ -2312,8 +2302,9 @@ private Insn findArgDepositer(Insn currInsn, int argDepth) {
// At control flow branch/merge points, abort the search for the
// target operand.
if (i.branches() ||
- ((i instanceof InsnTarget) && ((InsnTarget)i).isBranchTarget()))
+ ((i instanceof InsnTarget) && ((InsnTarget)i).isBranchTarget())) {
break;
+ }
int nArgs = i.nStackArgs();
int nResults = i.nStackResults();
@@ -2324,16 +2315,18 @@ private Insn findArgDepositer(Insn currInsn, int argDepth) {
// deposit more than one value. These are the
// long/doubleinstructions (which can't be depositing a one
// word value) and the dupX variants
- if (nResults > 1 && i.opcode() != opc_dup)
+ if (nResults > 1 && i.opcode() != opc_dup) {
break;
+ }
depositer = i;
// consider special cases which may cause us to look further
switch (i.opcode()) {
case opc_dup:
- if (argDepth == 0)
+ if (argDepth == 0) {
// keep going to find the real depositer at a greater depth
argDepth++;
+ }
break;
case opc_checkcast:
// keep going to find the real depositer
@@ -2362,9 +2355,9 @@ private void minimizeStack(StackState state) {
Insn i = state.insn;
int argDepth = state.argDepth;
- Stack argTypesStack = new Stack();
- Stack resultTypesStack = new Stack();
- Stack stackTypes = new Stack();
+ Stack argTypesStack = new Stack<>();
+ Stack resultTypesStack = new Stack<>();
+ Stack stackTypes = new Stack<>();
copyStack(state.stackTypes, stackTypes);
for (; argDepth > 0; i = i.prev()) {
@@ -2373,8 +2366,9 @@ private void minimizeStack(StackState state) {
// stack state computed thus far.
if (i.branches() ||
((i instanceof InsnTarget)
- && ((InsnTarget)i).isBranchTarget()))
+ && ((InsnTarget)i).isBranchTarget())) {
break;
+ }
int nArgs = i.nStackArgs();
int nResults = i.nStackResults();
@@ -2386,31 +2380,38 @@ private void minimizeStack(StackState state) {
// deposited multiple results (one of the dup type instructions)
// then we don't have the smarts to figure out where it came from
// so just quit looking
- if (argDepth < 0)
+ if (argDepth < 0) {
break;
+ }
argDepth += nArgs;
if (i.opcode() == opc_swap) {
- Object x = stackTypes.pop();
- Object y = stackTypes.pop();
+ Integer x = stackTypes.pop();
+ Integer y = stackTypes.pop();
stackTypes.push(x);
stackTypes.push(y);
} else {
// Make sure the arg types and result types stacks are empty
- while (!argTypesStack.empty()) argTypesStack.pop();
- while (!resultTypesStack.empty()) resultTypesStack.pop();
+ while (!argTypesStack.empty()) {
+ argTypesStack.pop();
+ }
+ while (!resultTypesStack.empty()) {
+ resultTypesStack.pop();
+ }
Descriptor.computeStackTypes(argTypes, argTypesStack);
Descriptor.computeStackTypes(resultTypes, resultTypesStack);
int expectWords = 0;
- while (!resultTypesStack.empty())
+ while (!resultTypesStack.empty()) {
expectWords += Descriptor.elementSize(
- ((Integer) resultTypesStack.pop()).intValue());
+ resultTypesStack.pop().intValue());
+ }
- while (expectWords > 0)
+ while (expectWords > 0) {
expectWords -= Descriptor.elementSize(
- ((Integer) stackTypes.pop()).intValue());
+ stackTypes.pop().intValue());
+ }
if (expectWords < 0) {
// perhaps we ought to signal an exception, but returning
@@ -2432,30 +2433,32 @@ private void minimizeStack(StackState state) {
/* Take all stack elements in fromStack and push them onto toStack
* such that they are in the same relative stack positions */
- private final void transferStackArgs(Stack fromStack, Stack toStack) {
+ private final void transferStackArgs(Stack fromStack, Stack toStack) {
if (!fromStack.empty()) {
- Object o = fromStack.pop();
+ Integer o = fromStack.pop();
transferStackArgs(fromStack, toStack);
toStack.push(o);
}
}
/* Make toStack look just like fromStack */
- private final void copyStack(Stack fromStack, Stack toStack) {
- while (!toStack.empty())
+ private final void copyStack(Stack fromStack, Stack toStack) {
+ while (!toStack.empty()) {
toStack.pop();
+ }
// take advantage of Stack's inheritance from Vector
- for (int i=0; i stack, int nWords) {
// take advantage of Stack's inheritance from Vector
for (int i=stack.size()-1; i>= 0 && nWords > 0; i--) {
int words = 0;
- switch (((Integer)stack.elementAt(i)).intValue()) {
+ switch (stack.elementAt(i).intValue()) {
case T_UNKNOWN:
case T_WORD:
case T_TWOWORD:
@@ -2501,7 +2504,7 @@ private final void addNoteList(InsnNote note) {
*/
//@olsen: made final
private final InsnNote getNoteList(Insn insn) {
- return (InsnNote)insnNotes.get(insn);
+ return insnNotes.get(insn);
}
}
@@ -2800,13 +2803,13 @@ class StackState implements VMConstants {
int argDepth;
/* Stack of types */
- Stack stackTypes;
+ Stack stackTypes;
/* the instruction after which, the word is argDepth deep */
Insn insn;
StackState(int depth, String stackSig, Insn i) {
- stackTypes = new Stack();
+ stackTypes = new Stack();
Descriptor.computeStackTypes(stackSig, stackTypes);
argDepth = depth;
insn = i;
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/MethodBuilder.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/MethodBuilder.java
index b88bd91442b..f44241e5256 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/MethodBuilder.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/impl/MethodBuilder.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022 Contributors to the Eclipse Foundation
+ * Copyright (c) 2022, 2026 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -190,311 +190,6 @@ ClassMethod makeNullMethod(final ClassAction ca,
return nullMethod;
}
- /**
- * Build the initializeContents method for the class
- */
-//@olsen: dropped method
-/*
- ClassMethod makeInitializeContents(ClassAction ca) {
- final ConstantPool pool = ca.classFile().pool();
- final ConstClass thisClass = ca.classFile().className();
-
- final AttributeVector methodAttrs = new AttributeVector();
- ClassMethod initializeContentsMethod =
- new ClassMethod(ACCPublic,
- pool.addUtf8("initializeContents"),
- pool.addUtf8("(Lcom/sun/forte4j/persistence/internal/ObjectContents;)V"),
- methodAttrs);
-
- // begin of method body
- Insn begin = new InsnTarget();
- Insn insn = begin;
-
- // Allocated reg 2 as cached ClassInfo*
- insn = insn.append(
- Insn.create(opc_getstatic,
- pool.addFieldRef(thisClass.asString(),
- ca.getClassInfoMember(),
- "Lcom/sun/forte4j/persistence/internal/ClassInfo;")));
- insn = insn.append(Insn.create(opc_astore_2));
-
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- FieldAction act = (FieldAction)e.next();
- if (act.isPersistent()) {
- int idx = act.index();
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
- // get GenericObject
- insn = insn.append(Insn.create(opc_aload_1));
- // get field index
- insn = insn.append(InsnUtils.integerConstant(idx, pool));
- // get ClassInfo
- insn = insn.append(Insn.create(opc_aload_2));
- // call the get method
- insn = insn.append(Insn.create(opc_invokevirtual,
- pool.addMethodRef("com/sun/forte4j/persistence/internal/ObjectContents",
- act.getMethod(), act.getMethodSig())));
-
- switch(act.getMethodReturn()) {
- case T_DOUBLE:
- case T_LONG:
- case T_BOOLEAN:
- case T_CHAR:
- case T_FLOAT:
- case T_BYTE:
- case T_SHORT:
- case T_INT:
- case TC_STRING:
- // The above types are assumed to be accurate, with no
- // conversions required
- break;
-
- case TC_OBJECT:
- case TC_INTERFACE:
- if (!act.typeDescriptor().equals("Ljava/lang/Object;")) {
- ConstClass fieldType = pool.addClass(act.typeName());
- // Add a cast to the appropriate type
- insn = insn.append(Insn.create(opc_checkcast, fieldType));
- }
- break;
- default:
- throw new InternalError("Unexpected return type");
- }
-
- // finally, store the result
- insn = insn.append(Insn.create(opc_putfield,
- pool.addFieldRef(thisClass.asString(), act.fieldName(),
- act.typeDescriptor())));
- }
- }
-
- ConstClass superClass = ca.classFile().superName();
- if (!ca.getImplementsPersistence()) {
- // Need to invoke initializeContents on super
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
- // get generic object
- insn = insn.append(Insn.create(opc_aload_1));
- // do the invoke
- insn = insn.append(Insn.create(opc_invokespecial,
- pool.addMethodRef(superClass.asString(),
- "initializeContents", "(Lcom/sun/forte4j/persistence/internal/ObjectContents;)V")));
- }
-
- // end of method body
- insn = insn.append(Insn.create(opc_return));
-
- methodAttrs.addElement(
- new CodeAttribute(pool.addUtf8(CodeAttribute.expectedAttrName),
- 4, // maxStack
- 3, // maxLocals
- begin,
- new ExceptionTable(),
- new AttributeVector()));
- return initializeContentsMethod;
- }
-*/
-
- /**
- * Build the flushContents method for the class
- */
-//@olsen: dropped method
-/*
- ClassMethod makeFlushContents(ClassAction ca) {
- final ConstantPool pool = ca.classFile().pool();
- final ConstClass thisClass = ca.classFile().className();
-
- final AttributeVector methodAttrs = new AttributeVector();
- ClassMethod flushContentsMethod =
- new ClassMethod(ACCPublic,
- pool.addUtf8("flushContents"),
- pool.addUtf8("(Lcom/sun/forte4j/persistence/internal/ObjectContents;)V"),
- methodAttrs);
-
- // begin of method body
- Insn begin = new InsnTarget();
- Insn insn = begin;
-
- // Allocated reg 2 as cached ClassInfo*
- insn = insn.append(
- Insn.create(opc_getstatic,
- pool.addFieldRef(thisClass.asString(),
- ca.getClassInfoMember(),
- "Lcom/sun/forte4j/persistence/internal/ClassInfo;")));
- insn = insn.append(Insn.create(opc_astore_2));
-
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- FieldAction act = (FieldAction)e.next();
- if (act.isPersistent()) {
- int idx = act.index();
- // get GenericObject
- insn = insn.append(Insn.create(opc_aload_1));
- // get field index
- insn = insn.append(InsnUtils.integerConstant(idx, pool));
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
- // get the field value
- insn = insn = insn.append(Insn.create(opc_getfield,
- pool.addFieldRef(thisClass.asString(), act.fieldName(),
- act.typeDescriptor())));
- // get ClassInfo
- insn = insn.append(Insn.create(opc_aload_2));
-
- // call the set method
- insn = insn.append(Insn.create(opc_invokevirtual,
- pool.addMethodRef("com/sun/forte4j/persistence/internal/ObjectContents",
- act.setMethod(), act.setMethodSig())));
- }
- }
-
- ConstClass superClass = ca.classFile().superName();
- if (!ca.getImplementsPersistence()) {
- // Need to invoke flushContents on super
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
- // get generic object
- insn = insn.append(Insn.create(opc_aload_1));
- // do the invoke
- insn = insn.append(Insn.create(opc_invokespecial,
- pool.addMethodRef(superClass.asString(),
- "flushContents", "(Lcom/sun/forte4j/persistence/internal/ObjectContents;)V")));
- }
-
- // end of method body
- insn = insn.append(Insn.create(opc_return));
-
- methodAttrs.addElement(
- new CodeAttribute(pool.addUtf8(CodeAttribute.expectedAttrName),
- 6, // maxStack (might actually be 5, but ok)
- 3, // maxLocals
- begin,
- new ExceptionTable(),
- new AttributeVector()));
- return flushContentsMethod;
- }
-*/
-
- /**
- * Build the clearContents method for the class
- */
-//@olsen: dropped method
-/*
- ClassMethod makeClearContents(ClassAction ca) {
- final ConstantPool pool = ca.classFile().pool();
- final ConstClass thisClass = ca.classFile().className();
-
- final AttributeVector methodAttrs = new AttributeVector();
- ClassMethod clearContentsMethod =
- new ClassMethod(ACCPublic,
- pool.addUtf8("clearContents"),
- pool.addUtf8("()V"),
- methodAttrs);
-
- // begin of method body
- Insn begin = new InsnTarget();
- Insn insn = begin;
-
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- FieldAction act = (FieldAction)e.next();
- if (act.isPersistent()) {
- int idx = act.index();
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
-
- // Use the getMethodReturn type to decide how to initialize
- switch(act.getMethodReturn()) {
- case T_DOUBLE:
- insn = insn.append(Insn.create(opc_dconst_0));
- break;
- case T_LONG:
- insn = insn.append(Insn.create(opc_lconst_0));
- break;
- case T_FLOAT:
- insn = insn.append(Insn.create(opc_fconst_0));
- break;
- case T_BOOLEAN:
- case T_CHAR:
- case T_BYTE:
- case T_SHORT:
- case T_INT:
- insn = insn.append(Insn.create(opc_iconst_0));
- break;
- case TC_STRING:
- case TC_OBJECT:
- case TC_INTERFACE:
- insn = insn.append(Insn.create(opc_aconst_null));
- break;
- default:
- throw new InternalError("Unexpected return type");
- }
-
- // finally, store the result
- insn = insn.append(Insn.create(opc_putfield,
- pool.addFieldRef(thisClass.asString(), act.fieldName(),
- act.typeDescriptor())));
- }
- }
-
- ConstClass superClass = ca.classFile().superName();
- if (!ca.getImplementsPersistence()) {
- // Need to invoke clearContents on super
- // get this
- insn = insn.append(Insn.create(opc_aload_0));
- // do the invoke
- insn = insn.append(Insn.create(opc_invokespecial,
- pool.addMethodRef(superClass.asString(),
- "clearContents", "()V")));
- }
-
- // end of method body
- insn = insn.append(Insn.create(opc_return));
-
- methodAttrs.addElement(
- new CodeAttribute(pool.addUtf8(CodeAttribute.expectedAttrName),
- 3, // maxStack (maybe only 2 - ok)
- 1, // maxLocals
- begin,
- new ExceptionTable(),
- new AttributeVector()));
- return clearContentsMethod;
- }
-*/
-
- /**
- * Build an empty class initializer method for this class
- */
-//@olsen: dropped method
-/*
- ClassMethod makeClassInit(ClassAction ca) {
- final ConstantPool pool = ca.classFile().pool();
- final ConstClass thisClass = ca.classFile().className();
-
- final AttributeVector methodAttrs = new AttributeVector();
- ClassMethod classInitMethod =
- new ClassMethod(ACCStatic,
- pool.addUtf8(""),
- pool.addUtf8("()V"),
- methodAttrs);
-
- // begin of method body
- Insn begin = new InsnTarget();
- Insn insn = begin;
-
- // return from the initializer
- // end of method body
- insn = insn.append(Insn.create(opc_return));
-
- methodAttrs.addElement(
- new CodeAttribute(pool.addUtf8(CodeAttribute.expectedAttrName),
- 0,
- 0, // maxLocals
- begin,
- new ExceptionTable(),
- new AttributeVector()));
- return classInitMethod;
- }
-*/
-
/**
* Build the jdoGetStateManager method for the class.
*
@@ -1385,8 +1080,8 @@ ClassMethod makeJDOClearMethod(final ClassAction ca,
}
// iterate over all declared fields of the class
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- final FieldAction act = (FieldAction)e.next();
+ for (Iterator e = ca.fieldActions(); e.hasNext();) {
+ final FieldAction act = e.next();
//printFieldAction(act);
//System.out.println();
@@ -1799,9 +1494,9 @@ ClassMethod makeJDOGetFieldMethod(final ClassAction ca,
final InsnTarget defaultOp = new InsnTarget();
if (nofFields > 0) {
// get the declared, persistent fields from the class
- final HashMap fieldsByName = new HashMap();
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- final FieldAction act = (FieldAction)e.next();
+ final HashMap fieldsByName = new HashMap<>();
+ for (Iterator e = ca.fieldActions(); e.hasNext();) {
+ final FieldAction act = e.next();
fieldsByName.put(act.fieldName(), act);
}
@@ -1821,7 +1516,7 @@ ClassMethod makeJDOGetFieldMethod(final ClassAction ca,
insn = insn.append(targetsOp[i]);
final FieldAction act
- = (FieldAction)fieldsByName.get(fieldNames[i]);
+ = fieldsByName.get(fieldNames[i]);
affirm(act,
("Field '" + fieldNames[i]//NOI18N
+ "' returned by JDOMetaData is not known by class '"//NOI18N
@@ -2040,9 +1735,9 @@ ClassMethod makeJDOSetFieldMethod(final ClassAction ca,
final InsnTarget defaultOp = new InsnTarget();
if (nofFields > 0) {
// get the declared, persistent fields from the class
- final HashMap fieldsByName = new HashMap();
- for (Iterator e = ca.fieldActions(); e.hasNext();) {
- final FieldAction act = (FieldAction)e.next();
+ final HashMap fieldsByName = new HashMap<>();
+ for (Iterator e = ca.fieldActions(); e.hasNext();) {
+ final FieldAction act = e.next();
fieldsByName.put(act.fieldName(), act);
}
@@ -2062,7 +1757,7 @@ ClassMethod makeJDOSetFieldMethod(final ClassAction ca,
insn = insn.append(targetsOp[i]);
final FieldAction act
- = (FieldAction)fieldsByName.get(fieldNames[i]);
+ = fieldsByName.get(fieldNames[i]);
affirm(act,
("Field '"//NOI18N
+ fieldNames[i]
@@ -2386,31 +2081,6 @@ ClassMethod makeJDOClone(final ClassAction ca,
return cloneMethod;
}
- // for debugging
- static private void printFieldAction(FieldAction act) {
- System.out.println("fieldName() = " + act.fieldName());//NOI18N
- System.out.println("userFieldName() = " + act.userFieldName());//NOI18N
- System.out.println("typeDescriptor() = " + act.typeDescriptor());//NOI18N
- System.out.println("typeName() = " + act.typeName());//NOI18N
- System.out.println("fieldClassName() = " + act.fieldClassName());//NOI18N
- System.out.println("isPersistent() = " + act.isPersistent());//NOI18N
- System.out.println("isPrimaryKey() = " + act.isPrimaryKey());//NOI18N
- System.out.println("isMutableSCO() = " + act.isMutableSCO());//NOI18N
- System.out.println("isSynthetic() = " + act.isSynthetic());//NOI18N
- //System.out.println("index() = " + act.index());
- System.out.println("nDims() = " + act.nDims());//NOI18N
- System.out.println("createMethod() = " + act.createMethod());//NOI18N
- System.out.println("createMethodSig() = " + act.createMethodSig());//NOI18N
- System.out.println("setMethod() = " + act.setMethod());//NOI18N
- System.out.println("setMethodSig() = " + act.setMethodSig());//NOI18N
- System.out.println("setMethodArg() = "//NOI18N
- + typeToString(act.setMethodArg()));
- System.out.println("getMethod() = " + act.getMethod());//NOI18N
- System.out.println("getMethodSig() = " + act.getMethodSig());//NOI18N
- System.out.println("getMethodReturn() = "//NOI18N
- + typeToString(act.getMethodReturn()));
- }
-
// for debugging
static private String typeToString(int val) {
switch(val) {
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataProperties.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataProperties.java
index 9be07d897e9..8364f35fad1 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataProperties.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataProperties.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,23 +15,16 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-//JDOMetaDataProperties - Java Source
-
-
//***************** package ***********************************************
package com.sun.jdo.api.persistence.enhancer.meta;
-
-//***************** import ************************************************
-
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
-import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -146,7 +140,7 @@ public final class JDOMetaDataProperties {
* classnames, the values are the appropriate
* JDOClass-object.
*/
- private final Map cachedJDOClasses = new HashMap ();
+ private final Map cachedJDOClasses = new HashMap<>();
/**
@@ -160,7 +154,7 @@ public final class JDOMetaDataProperties {
* A temporary vector (this is the reason why the implementation is not
* thread safe).
*/
- private final List tmpTokens = new ArrayList ();
+ private final List tmpTokens = new ArrayList<>();
/**********************************************************************
@@ -190,7 +184,7 @@ public JDOMetaDataProperties(Properties props) {
public JDOClass getJDOClass(String classname) throws JDOMetaDataUserException {
classname = toCanonicalClassName(classname);
- JDOClass clazz = (JDOClass) this.cachedJDOClasses.get(classname);
+ JDOClass clazz = this.cachedJDOClasses.get(classname);
if (clazz == NULL) // already searched but not found
{
return null;
@@ -245,15 +239,14 @@ public JDOField getJDOField(String fieldname, String classname) throws JDOMetaDa
*********************************************************************/
public String[] getKnownClassNames() {
- Collection classnames = new HashSet();
- for (Enumeration names = this.properties.propertyNames(); names.hasMoreElements();) {
- String name = (String) names.nextElement();
+ Collection classnames = new HashSet<>();
+ for (String name : this.properties.stringPropertyNames()) {
if (name.indexOf(FIELD_DELIMITER) < 0) {
classnames.add(fromCanonicalClassName(name));
}
}
- return (String[]) classnames.toArray(new String[classnames.size()]);
+ return (String[]) classnames.toArray(String[]::new);
} //JDOMetaDataProperties.getKnownClassNames()
@@ -303,11 +296,11 @@ private static String fromCanonicalClassName(String classname) {
*********************************************************************/
private JDOClass parseJDOClass(String classname, String attributes) throws JDOMetaDataUserException {
- List props = parseProperties(attributes);
+ List props = parseProperties(attributes);
//check each property
for (int i = 0; i < props.size(); i++) {
- Property prop = (Property) props.get(i);
+ Property prop = props.get(i);
validateClassProperty(prop, classname);
}
@@ -317,7 +310,7 @@ private JDOClass parseJDOClass(String classname, String attributes) throws JDOMe
//properties are OK - assign them to the JDOClass object
JDOClass clazz = new JDOClass(classname);
for (int i = 0; i < props.size(); i++) {
- Property prop = (Property) props.get(i);
+ Property prop = props.get(i);
if (prop.name.equals(PROPERTY_ACCESS_MODIFIER)) {
clazz.modifiers = getModifiers(prop.value);
} else if (prop.name.equals(PROPERTY_JDO_MODIFIER)) {
@@ -364,7 +357,6 @@ else if (value.equals(JDO_PERSISTENT) || value.equals(JDO_TRANSIENT)) {
}
} else {
//do we have a valid property name?
- String name = prop.name;
checkPropertyName (prop.name, new String []
{
PROPERTY_OID_CLASSNAME,
@@ -404,10 +396,9 @@ else if (value.equals(JDO_PERSISTENT) || value.equals(JDO_TRANSIENT)) {
private void parseJDOFields(JDOClass clazz) throws JDOMetaDataUserException {
// search for fields of the class
- for (Enumeration names = this.properties.propertyNames(); names.hasMoreElements();) {
- String name = (String) names.nextElement();
- if (name.startsWith(clazz.getName() + FIELD_DELIMITER)) // field found
- {
+ for (String name : properties.stringPropertyNames()) {
+ if (name.startsWith(clazz.getName() + FIELD_DELIMITER)) {
+ // field found
String fieldname = name.substring(name.indexOf(FIELD_DELIMITER) + 1, name.length());
validateFieldName(fieldname, clazz.getName());
clazz.addField(parseJDOField(this.properties.getProperty(name), fieldname, clazz));
@@ -431,11 +422,11 @@ private void parseJDOFields(JDOClass clazz) throws JDOMetaDataUserException {
private JDOField parseJDOField(String attributes, String fieldname, JDOClass clazz)
throws JDOMetaDataUserException {
- List props = parseProperties(attributes);
+ List props = parseProperties(attributes);
// check each property
for (int i = 0; i < props.size(); i++) {
- Property prop = (Property) props.get(i);
+ Property prop = props.get(i);
validateFieldProperty(prop, fieldname, clazz.getName());
}
@@ -445,7 +436,7 @@ private JDOField parseJDOField(String attributes, String fieldname, JDOClass cla
//properties are OK - assign them to the JDOField object
JDOField field = new JDOField(fieldname);
for (int i = 0; i < props.size(); i++) {
- Property prop = (Property) props.get(i);
+ Property prop = props.get(i);
if (prop.name.equals(PROPERTY_ACCESS_MODIFIER)) {
field.modifiers = getModifiers(prop.value);
} else if (prop.name.equals(PROPERTY_JDO_MODIFIER)) {
@@ -556,7 +547,7 @@ else if (value.equals(ANNOTATION_TYPE_PK) || value.equals(ANNOTATION_TYPE_DFG)
private void validateDependencies(JDOClass clazz) throws JDOMetaDataUserException {
for (int i = clazz.fields.size() - 1; i >= 0; i--) {
- JDOField field = (JDOField) clazz.fields.get(i);
+ JDOField field = clazz.fields.get(i);
// set the jdo field modifier according to the jdo class modifier (if jdo field not set
// yet)
@@ -635,11 +626,11 @@ private static void validateFieldName(String fieldname, String classname) throws
* @throws JDOMetaDataUserException If the check fails.
*********************************************************************/
- private static void checkForDuplicateProperties(List props, String entry) throws JDOMetaDataUserException {
+ private static void checkForDuplicateProperties(List props, String entry) throws JDOMetaDataUserException {
for (int i = 0; i < props.size(); i++) {
for (int j = i + 1; j < props.size(); j++) {
- Property p1 = (Property) props.get(i);
- Property p2 = (Property) props.get(j);
+ Property p1 = props.get(i);
+ Property p2 = props.get(j);
if (p1.name.equals(p2.name) && !p1.value.equals(p2.value)) {
throw new JDOMetaDataUserException(getErrorMsg(IErrorMessages.ERR_DUPLICATE_PROPERTY_NAME,
new String[] {entry, p1.name, p1.value, p2.value}));
@@ -729,7 +720,7 @@ static String getErrorMsg(String msg, String[] params) {
* @exception JDOMetaDataUserException If the parsing fails.
*********************************************************************/
- List parseProperties(String attributes) throws JDOMetaDataUserException {
+ List parseProperties(String attributes) throws JDOMetaDataUserException {
this.tmpTokens.clear();
StringTokenizer t = new StringTokenizer(attributes, PROPERTY_DELIMITERS);
while (t.hasMoreTokens()) {
@@ -889,8 +880,6 @@ private interface IErrorMessages
PREFIX + "A non-persistent class cannot have a transactional field (class ''{0}'' with field ''{1})''.";
String ERR_TRANSIENT_CLASS_WITH_ANNOTATED_FIELD =
PREFIX + "A non-persistent class cannot have an annotated field (''{1}'' of class ''{0}'') can''t have a fetch group.";
- String ERR_NON_PERSISTENT_ANNOTATED_FIELD =
- PREFIX + "A non-persistent field (''{1}'' of class ''{0}'') can''t be a annotated.";
} //IErrorMessages
@@ -932,7 +921,7 @@ static final class JDOClass {
/**
* A list of all parsed fields.
*/
- private final List fields = new ArrayList();
+ private final List fields = new ArrayList<>();
/**
*
@@ -1094,7 +1083,7 @@ public JDOField getField(String name) {
public int getIndexOfField(String name) {
for (int i = 0; i < this.fields.size(); i++) {
- JDOField field = (JDOField) this.fields.get(i);
+ JDOField field = this.fields.get(i);
if (field.getName().equals(name)) {
return i;
}
@@ -1113,11 +1102,11 @@ public int getIndexOfField(String name) {
public String[] getFields() {
if (this.fieldNames == null) {
final int n = this.fields.size();
- String[] fields = new String[n];
+ String[] fieldsTmp = new String[n];
for (int i = 0; i < n; i++) {
- fields[i] = ((JDOField) this.fields.get(i)).getName();
+ fieldsTmp[i] = this.fields.get(i).getName();
}
- this.fieldNames = fields;
+ this.fieldNames = fieldsTmp;
}
return this.fieldNames;
} // JDOClass.getFields()
@@ -1132,7 +1121,7 @@ public String[] getFields() {
*****************************************************************/
private void sortFields() {
- Collections.sort(this.fields, new Comparator() {
+ Collections.sort(this.fields, new Comparator() {
@Override
public final int compare(Object f1, Object f2) {
@@ -1160,9 +1149,9 @@ public final int compare(Object f1, Object f2) {
public String[] getManagedFieldNames() {
if (this.managedFieldNames == null) {
final int n = this.fields.size();
- List tmp = new ArrayList(n);
+ List tmp = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
- JDOField field = (JDOField) this.fields.get(i);
+ JDOField field = this.fields.get(i);
if (field.isManaged()) {
tmp.add(field.getName());
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataPropertyImpl.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataPropertyImpl.java
index 5b266ffb243..4559891d38e 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataPropertyImpl.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/meta/JDOMetaDataPropertyImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -31,17 +32,12 @@
* Provides the JDO meta information based on properties.
*/
//@olsen: new class
-public class JDOMetaDataPropertyImpl extends Support
- implements ExtendedJDOMetaData
-{
- // misc
-// static final String nl = System.getProperty("line.separator", "\n");
-// protected final PrintWriter out;
+public class JDOMetaDataPropertyImpl extends Support implements ExtendedJDOMetaData {
// model
- private static final HashSet transientTypePrefixes = new HashSet();
- private static final HashSet secondClassObjectTypes = new HashSet();
- private static final HashSet mutableSecondClassObjectTypes = new HashSet();
+ private static final HashSet transientTypePrefixes = new HashSet<>();
+ private static final HashSet secondClassObjectTypes = new HashSet<>();
+ private static final HashSet mutableSecondClassObjectTypes = new HashSet<>();
/**
@@ -56,37 +52,37 @@ public class JDOMetaDataPropertyImpl extends Support
static
{
- transientTypePrefixes.add("java/");//NOI18N
- transientTypePrefixes.add("javax/");//NOI18N
- transientTypePrefixes.add("com/sun/jdo/");//NOI18N
-
- mutableSecondClassObjectTypes.add("java/util/Date");//NOI18N
- mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/Date");//NOI18N
- mutableSecondClassObjectTypes.add("java/sql/Date");//NOI18N
- mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlTime");//NOI18N
- mutableSecondClassObjectTypes.add("java/sql/Time");//NOI18N
- mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlDate");//NOI18N
- mutableSecondClassObjectTypes.add("java/sql/Timestamp");//NOI18N
- mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlTimestamp");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/Collection");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/Set");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/List");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/HashSet");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/Vector");//NOI18N
- mutableSecondClassObjectTypes.add("java/util/ArrayList");//NOI18N
-
- secondClassObjectTypes.add("java/lang/Boolean");//NOI18N
- secondClassObjectTypes.add("java/lang/Byte");//NOI18N
- secondClassObjectTypes.add("java/lang/Short");//NOI18N
- secondClassObjectTypes.add("java/lang/Integer");//NOI18N
- secondClassObjectTypes.add("java/lang/Long");//NOI18N
- secondClassObjectTypes.add("java/lang/Float");//NOI18N
- secondClassObjectTypes.add("java/lang/Double");//NOI18N
- secondClassObjectTypes.add("java/lang/Number");//NOI18N
- secondClassObjectTypes.add("java/lang/Character");//NOI18N
- secondClassObjectTypes.add("java/lang/String");//NOI18N
- secondClassObjectTypes.add("java/math/BigInteger");//NOI18N
- secondClassObjectTypes.add("java/math/BigDecimal");//NOI18N
+ transientTypePrefixes.add("java/");
+ transientTypePrefixes.add("javax/");
+ transientTypePrefixes.add("com/sun/jdo/");
+
+ mutableSecondClassObjectTypes.add("java/util/Date");
+ mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/Date");
+ mutableSecondClassObjectTypes.add("java/sql/Date");
+ mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlTime");
+ mutableSecondClassObjectTypes.add("java/sql/Time");
+ mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlDate");
+ mutableSecondClassObjectTypes.add("java/sql/Timestamp");
+ mutableSecondClassObjectTypes.add("com/sun/jdo/spi/persistence/support/sqlstore/sco/SqlTimestamp");
+ mutableSecondClassObjectTypes.add("java/util/Collection");
+ mutableSecondClassObjectTypes.add("java/util/Set");
+ mutableSecondClassObjectTypes.add("java/util/List");
+ mutableSecondClassObjectTypes.add("java/util/HashSet");
+ mutableSecondClassObjectTypes.add("java/util/Vector");
+ mutableSecondClassObjectTypes.add("java/util/ArrayList");
+
+ secondClassObjectTypes.add("java/lang/Boolean");
+ secondClassObjectTypes.add("java/lang/Byte");
+ secondClassObjectTypes.add("java/lang/Short");
+ secondClassObjectTypes.add("java/lang/Integer");
+ secondClassObjectTypes.add("java/lang/Long");
+ secondClassObjectTypes.add("java/lang/Float");
+ secondClassObjectTypes.add("java/lang/Double");
+ secondClassObjectTypes.add("java/lang/Number");
+ secondClassObjectTypes.add("java/lang/Character");
+ secondClassObjectTypes.add("java/lang/String");
+ secondClassObjectTypes.add("java/math/BigInteger");
+ secondClassObjectTypes.add("java/math/BigDecimal");
secondClassObjectTypes.addAll(mutableSecondClassObjectTypes);
} //JDOMetaDataPropertyImpl.
@@ -103,13 +99,6 @@ public JDOMetaDataPropertyImpl(Properties properties, PrintWriter out)
final String msg = "Initializing meta data: properties == null";// NOI18N
throw new JDOMetaDataFatalError(msg);
}
- /*
- if (out == null) {
- final String msg
- = "Initializing meta data: output stream == null";//NOI18N
- throw new JDOMetaDataFatalError(msg);
- }
- */
this.properties = new JDOMetaDataProperties (properties);
readProperties ();
@@ -132,8 +121,8 @@ public JDOMetaDataPropertyImpl(Properties properties) throws JDOMetaDataUserExce
@Override
public boolean isPersistenceCapableClass(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError {
// check the transient prefixes
- for (Iterator i = transientTypePrefixes.iterator(); i.hasNext();) {
- final String typePrefix = (String) i.next();
+ for (Iterator i = transientTypePrefixes.iterator(); i.hasNext();) {
+ final String typePrefix = i.next();
if (classPath.startsWith(typePrefix)) {
return false;
}
@@ -524,7 +513,7 @@ public int[] getFieldNo(String classPath, String[] fieldNames)
@Override
public String[] getKeyFields(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError {
- final List keys = new ArrayList();
+ final List keys = new ArrayList<>();
final String[] fieldNames = getManagedFields(classPath);
final int n = fieldNames.length;
for (int i = 0; i < n; i++) {
@@ -568,68 +557,4 @@ public String getSuperKeyClass(String classPath) throws JDOMetaDataUserException
return null;
}
- /**********************************************************************
- *
- *********************************************************************/
-/*
- public static void main (String [] argv)
- {
-
- if (argv.length != 1)
- {
- System.err.println ("No property file specified.");
- return;
- }
- Properties p = new Properties ();
- try
- {
- java.io.InputStream in = new java.io.FileInputStream (new java.io.File (argv [0]));
- p.load (in);
- in.close ();
- System.out.println ("PROPERTIES: " + p);
- System.out.println ("############");
- JDOMetaDataProperties props = new JDOMetaDataProperties (p);
- }
- catch (Throwable ex)
- {
- ex.printStackTrace (System.err);
- }
-
- JDOMetaDataPropertyImpl jdo = new JDOMetaDataPropertyImpl (p, new PrintWriter (System.out));
- String [] classnames = jdo.getKnownClasses ();
- for (int k = 0; k < classnames.length; k++)
- {
- String classname = classnames [k];
- System.out.println ("CLASSNAME: " + classname);
- System.out.println ("\tpersistent: " + jdo.isPersistenceCapableClass (classname));
- System.out.println ("\tpersistent root: " + jdo.isPersistenceCapableRootClass (classname));
- System.out.println ("\tpersistent root: " + jdo.getPersistenceCapableRootClass (classname));
- String [] fieldnames = jdo.getKnownFields (classname);
- for (int j = 0; j < fieldnames.length; j++)
- {
- String fieldname = (String) fieldnames [j];
- System.out.println ("FIELDNAME: " + fieldname);
- System.out.println ("\tpersistent field: " + jdo.isPersistentField (classname, fieldname));
- System.out.println ("\tpk field: " + jdo.isPrimaryKeyField (classname, fieldname));
- System.out.println ("\tdfg field: " + jdo.isDefaultFetchGroupField (classname, fieldname));
- System.out.println ("\tnumber: " + jdo.getFieldNo (classname, fieldname));
- String [] names = jdo.getManagedFields (classname);
- final int n = (fieldnames != null ? names.length : 0);
- System.out.println ("managed fields: number: " + n);
- for (int i = 0; i < n; i++)
- {
- System.out.println (i + ": " + names [i] +
- " number: " + jdo.getFieldNo (classname, names [i]) +
- " pk: " + jdo.isPrimaryKeyField (classname, names [i]) +
- " dfg: " + jdo.isDefaultFetchGroupField (classname, names [i]));
- }
- }
- }
-
- } //JDOMetaDataPropertyImpl.main
-*/
-
-} //JDOMetaDataPropertyImpl
-
-
-//JDOMetaDataPropertyImpl
+}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPath.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPath.java
index 2bb003b61e7..8344b12e078 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPath.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPath.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -74,8 +75,9 @@ public static String fileNameOf(String className, char separator) {
StringBuffer path = new StringBuffer();
StringTokenizer parser = new StringTokenizer(className, "./", false);//NOI18N
for (boolean first = true; parser.hasMoreElements(); first = false) {
- if (!first)
+ if (!first) {
path.append(separator);
+ }
path.append(parser.nextToken());
}
path.append(".class");//NOI18N
@@ -114,8 +116,9 @@ public static String classNameOf(String fileName) {
StringBuffer className = new StringBuffer();
StringTokenizer parser = new StringTokenizer(fileName, "\\/", false);//NOI18N
for (boolean first = true; parser.hasMoreElements(); first = false) {
- if (!first)
+ if (!first) {
className.append('/');
+ }
className.append(parser.nextToken());
}
return className.toString();
@@ -133,10 +136,11 @@ public boolean remove(File directory) {
for (ClassPathElement cpe = firstElement; cpe != null; cpe = cpe.next()) {
if (cpe.matches(directory)) {
matched = true;
- if (prevElement == null)
+ if (prevElement == null) {
firstElement = cpe.next();
- else
+ } else {
prevElement.setNext(cpe.next());
+ }
} else {
prevElement = cpe;
}
@@ -156,10 +160,11 @@ public void append(File directory) {
* Append a class path element to the classpath.
*/
public void append(ClassPathElement anElement) {
- if (theClassPath == null)
+ if (theClassPath == null) {
theClassPath = anElement;
- else
+ } else {
theClassPath.append(anElement);
+ }
}
/**
@@ -174,7 +179,7 @@ public void append(ClassPathElement anElement) {
* that the class name returned might not correspond the the
* name of the class in the file.
*/
- public Enumeration classesInPackage(String packageName) {
+ public Enumeration classesInPackage(String packageName) {
return new ClassPackageEnumeration(this, packageName);
}
@@ -196,10 +201,11 @@ private void parsePath() {
while (parser.hasMoreElements()) {
ClassPathElement anElement = ClassPathElement.create(parser.nextToken());
- if (lastElement == null)
+ if (lastElement == null) {
theClassPath = anElement;
- else
+ } else {
lastElement.append(anElement);
+ }
lastElement = anElement;
}
@@ -212,7 +218,7 @@ private void parsePath() {
* can be found in a class path
*/
-class ClassPackageEnumeration implements Enumeration {
+class ClassPackageEnumeration implements Enumeration {
/* The next class path element to look for matches in once
the current enumeration is complete */
private ClassPathElement nextClassPathElement;
@@ -220,9 +226,8 @@ class ClassPackageEnumeration implements Enumeration {
/* The package name */
private String thePackageName;
- /* The enumeration of matching class names in the current class path
- element */
- private Enumeration currentElementEnumeration;
+ /* The enumeration of matching class names in the current class path element */
+ private Enumeration currentElementEnumeration;
/**
* Construct a ClassPackageEnumeration.
@@ -234,12 +239,11 @@ class ClassPackageEnumeration implements Enumeration {
thePackageName = packageName;
}
+ @Override
public boolean hasMoreElements() {
- while ((currentElementEnumeration == null ||
- !currentElementEnumeration.hasMoreElements()) &&
- nextClassPathElement != null) {
- currentElementEnumeration =
- nextClassPathElement.classesInPackage(thePackageName);
+ while ((currentElementEnumeration == null || !currentElementEnumeration.hasMoreElements())
+ && nextClassPathElement != null) {
+ currentElementEnumeration = nextClassPathElement.classesInPackage(thePackageName);
nextClassPathElement = nextClassPathElement.next();
}
@@ -247,9 +251,11 @@ public boolean hasMoreElements() {
currentElementEnumeration.hasMoreElements());
}
- public Object nextElement() {
- if (hasMoreElements())
+ @Override
+ public String nextElement() {
+ if (hasMoreElements()) {
return currentElementEnumeration.nextElement();
+ }
throw new NoSuchElementException();
}
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPathElement.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPathElement.java
index 758cc97afe8..2ffbf1971b4 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPathElement.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ClassPathElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -50,7 +51,7 @@ abstract class ClassPathElement {
* can be found. The return value may be null if the class
* path element is not valid.
*/
- public abstract Enumeration classesInPackage(String packageName);
+ public abstract Enumeration classesInPackage(String packageName);
/**
* Check to see if this ClassPathElement is a directory matching
@@ -84,11 +85,10 @@ void setNext(ClassPathElement next) {
*/
static ClassPathElement create(String elementSpec) {
File element = new File(elementSpec);
- if (!element.isDirectory() &&
- looksLikeZipName(elementSpec))
- return new ZipFileClassPathElement(element);
- else
+ if (element.isDirectory() || !looksLikeZipName(elementSpec)) {
return new DirectoryClassPathElement(element);
+ }
+ return new ZipFileClassPathElement(element);
}
/**
@@ -96,8 +96,9 @@ static ClassPathElement create(String elementSpec) {
*/
void append(ClassPathElement another) {
ClassPathElement e = this;
- while (e.next() != null)
+ while (e.next() != null) {
e = e.next();
+ }
e.next = another;
}
@@ -106,8 +107,8 @@ void append(ClassPathElement another) {
*/
static protected boolean looksLikeZipName(String fname) {
return (fname.length() > 4 &&
- (fname.regionMatches(true, fname.length() - 4, ".zip", 0, 4) ||//NOI18N
- fname.regionMatches(true, fname.length() - 4, ".jar", 0, 4)));//NOI18N
+ (fname.regionMatches(true, fname.length() - 4, ".zip", 0, 4) ||
+ fname.regionMatches(true, fname.length() - 4, ".jar", 0, 4)));
}
}
@@ -128,6 +129,7 @@ class DirectoryClassPathElement extends ClassPathElement {
* If this class path element resolves the class, return a
* ClassFileSource for the class.
*/
+ @Override
public ClassFileSource sourceOf(String className) {
File f = fileOf(className);
if (f != null && f.exists()) {
@@ -136,13 +138,16 @@ public ClassFileSource sourceOf(String className) {
return null;
}
- public Enumeration classesInPackage(String packageName) {
- if (!exists)
+ @Override
+ public Enumeration classesInPackage(String packageName) {
+ if (!exists) {
return null;
+ }
return new DirectoryClassPackageEnumerator(directory, packageName);
}
+ @Override
boolean matches(File matchDirectory) {
String dir = FilePath.canonicalize(directory);
String matchDir = FilePath.canonicalize(matchDirectory);
@@ -166,26 +171,20 @@ boolean matches(File matchDirectory) {
private File fileOf(String className) {
if (exists && directory.isDirectory()) {
StringBuffer newPath = new StringBuffer(directory.getPath());
- if (newPath.charAt(newPath.length() - 1) != File.separatorChar)
+ if (newPath.charAt(newPath.length() - 1) != File.separatorChar) {
newPath.append(File.separatorChar);
+ }
newPath.append(ClassPath.fileNameOf(className));
File f = new File(newPath.toString());
- if (f.isFile())
+ if (f.isFile()) {
return f;
+ }
}
return null;
}
- /**
- * Is this class path element valid? That is, does the directory
- * exist with the specified name?
- */
- private boolean isValid() {
- return exists;
- }
-
private void checkValid() {
exists = directory.isDirectory();
}
@@ -206,6 +205,7 @@ class ZipFileClassPathElement extends ClassPathElement {
* If this class path element resolves the class, return a
* ClassFileSource for the class.
*/
+ @Override
public ClassFileSource sourceOf(String className) {
if (zipFile != null) {
ZipEntry entry =
@@ -217,13 +217,16 @@ public ClassFileSource sourceOf(String className) {
return null;
}
- public Enumeration classesInPackage(String packageName) {
- if (zipFile == null)
+ @Override
+ public Enumeration classesInPackage(String packageName) {
+ if (zipFile == null) {
return null;
+ }
return new ZipFileClassPackageEnumerator(zipFile, packageName);
}
+ @Override
boolean matches(File directory) {
return false;
}
@@ -258,7 +261,7 @@ private void checkValid() {
* can be found relative to a particular directory.
*/
class DirectoryClassPackageEnumerator
-implements Enumeration, FilenameFilter {
+implements Enumeration, FilenameFilter {
private String[] matches;
private int nextMatch = -1;
@@ -278,32 +281,38 @@ class DirectoryClassPackageEnumerator
File packageDir = new File(packageDirName);
if (packageDir.isDirectory()) {
matches = packageDir.list(this);
- if (matches != null && matches.length > 0)
+ if (matches != null && matches.length > 0) {
nextMatch = 0;
+ }
}
}
+ @Override
public boolean hasMoreElements() {
return (nextMatch >= 0);
}
- public Object nextElement() {
- if (!hasMoreElements())
+ @Override
+ public String nextElement() {
+ if (!hasMoreElements()) {
throw new NoSuchElementException();
+ }
String next = matches[nextMatch++];
- if (nextMatch >= matches.length)
+ if (nextMatch >= matches.length) {
nextMatch = -1;
- return ClassPath.classNameOf(searchPackage + "/" + next);//NOI18N
+ }
+ return ClassPath.classNameOf(searchPackage + "/" + next);
}
/**
* Check whether the file name is valid.
* Needed for FilenameFilter implementation.
*/
+ @Override
public boolean accept(File dir, String name) {
int nameLength = name.length();
boolean isOk = (nameLength > 6 &&
- name.regionMatches(true, nameLength - 6, ".class", 0, 6));//NOI18N
+ name.regionMatches(true, nameLength - 6, ".class", 0, 6));
return isOk;
}
@@ -313,8 +322,8 @@ public boolean accept(File dir, String name) {
* An enumeration class which returns the names of the classes which
* can be found within a zip file.
*/
-class ZipFileClassPackageEnumerator implements Enumeration {
- Enumeration zipFileEntries;
+class ZipFileClassPackageEnumerator implements Enumeration {
+ Enumeration extends ZipEntry> zipFileEntries;
ZipEntry nextEntry;
String packageName;
@@ -323,10 +332,11 @@ class ZipFileClassPackageEnumerator implements Enumeration {
this.packageName = packageName;
}
+ @Override
public boolean hasMoreElements() {
while (nextEntry == null && zipFileEntries != null &&
zipFileEntries.hasMoreElements()) {
- ZipEntry ent = (ZipEntry) zipFileEntries.nextElement();
+ ZipEntry ent = zipFileEntries.nextElement();
String memName = ent.getName();
int memNameLength = memName.length();
int packageNameLength = packageName.length();
@@ -342,18 +352,21 @@ public boolean hasMoreElements() {
if (memName.indexOf('/', packageNameLength+1) == -1) {
boolean isOk =
(memNameLength > packageNameLength+7 &&
- memName.regionMatches(true, memNameLength - 6, ".class", 0, 6));//NOI18N
- if (isOk)
+ memName.regionMatches(true, memNameLength - 6, ".class", 0, 6));
+ if (isOk) {
nextEntry = ent;
+ }
}
}
}
return nextEntry != null;
}
- public Object nextElement() {
- if (!hasMoreElements())
+ @Override
+ public String nextElement() {
+ if (!hasMoreElements()) {
throw new NoSuchElementException();
+ }
String className = nextEntry.getName();
nextEntry = null;
return ClassPath.classNameOf(className);
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/Timer.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/Timer.java
index 08cf6f3d8fa..102d23f36ba 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/Timer.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/Timer.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -64,10 +65,10 @@ static private class MethodCall {
PrintWriter out = new PrintWriter(System.out, true);
// methods
- HashMap methods = new HashMap();
+ HashMap methods = new HashMap<>();
// method call stack
- private final ArrayList calls = new ArrayList(16);
+ private final ArrayList calls = new ArrayList<>(16);
public Timer() {
}
@@ -87,7 +88,7 @@ public final synchronized void push(String name, String message) {
final long now = System.currentTimeMillis();
// get a method descriptor
- MethodDescriptor current = (MethodDescriptor)methods.get(name);
+ MethodDescriptor current = methods.get(name);
if (current == null) {
current = new MethodDescriptor(name);
methods.put(name, current);
@@ -107,7 +108,7 @@ public final synchronized void pop() {
final long now = System.currentTimeMillis();
// update method call stack
- final MethodCall call = (MethodCall)calls.remove(calls.size()-1);
+ final MethodCall call = calls.remove(calls.size()-1);
// get current call's time
final long currentSelf = now - call.self;
@@ -115,7 +116,7 @@ public final synchronized void pop() {
// update previous call's self time
if (calls.size() > 0) {
- final MethodCall previous = (MethodCall)calls.get(calls.size()-1);
+ final MethodCall previous = calls.get(calls.size()-1);
previous.self += currentTotal;
}
@@ -135,8 +136,9 @@ public final synchronized void pop() {
static private final String pad(String s, int i) {
StringBuffer b = new StringBuffer();
- for (i -= s.length(); i > 0; i--)
- b.append((char)' ');
+ for (i -= s.length(); i > 0; i--) {
+ b.append(' ');
+ }
b.append(s);
return b.toString();
}
@@ -144,17 +146,12 @@ static private final String pad(String s, int i) {
public final synchronized void print() {
out.println("Timer : printing accumulated times ...");
- final Object[] calls = methods.values().toArray();
-
- Arrays.sort(calls,
- new Comparator() {
- public int compare(Object o1,
- Object o2) {
- return (int)(((MethodDescriptor)o2).total
- - ((MethodDescriptor)o1).total);
- }
- public boolean equals(Object obj) {
- return (obj != null && compare(this, obj) == 0);
+ final MethodDescriptor[] calls = methods.values().toArray(MethodDescriptor[]::new);
+ Arrays.sort(calls, new Comparator() {
+
+ @Override
+ public int compare(MethodDescriptor o1, MethodDescriptor o2) {
+ return (int) (o2.total - o1.total);
}
});
@@ -165,7 +162,7 @@ public boolean equals(Object obj) {
//nf.applyPattern("#,##0.00");
//out.println("Timer : pattern = " + nf.toPattern());
for (int i = 0; i < calls.length; i++) {
- final MethodDescriptor current = (MethodDescriptor)calls[i];
+ final MethodDescriptor current = calls[i];
out.println("Timer : "
+ pad(nf.format(current.total / 1000.0), 8) + " "
diff --git a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ZipFileRegistry.java b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ZipFileRegistry.java
index 7a10afde972..ab035d637ea 100644
--- a/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ZipFileRegistry.java
+++ b/appserver/persistence/cmp/enhancer/src/main/java/com/sun/jdo/api/persistence/enhancer/util/ZipFileRegistry.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -31,13 +32,13 @@
public class ZipFileRegistry {
/* A mapping of file name to ZipFile */
- private static Hashtable zipFileMap = new Hashtable(11);
+ private static Hashtable zipFileMap = new Hashtable<>(11);
/**
* Return a zip file which may already be open
*/
public static ZipFile openZipFile(File f) throws FileNotFoundException, IOException {
- ZipFile zf = (ZipFile) zipFileMap.get(f.getPath());
+ ZipFile zf = zipFileMap.get(f.getPath());
if (zf == null) {
zf = new ZipFile(f);
zipFileMap.put(zf.getName(), zf);
@@ -50,7 +51,7 @@ public static ZipFile openZipFile(File f) throws FileNotFoundException, IOExcept
* Return a zip file which must already be open
*/
public static ZipFile getZipFile(String path) {
- return (ZipFile) zipFileMap.get(path);
+ return zipFileMap.get(path);
}
@@ -58,7 +59,7 @@ public static ZipFile getZipFile(String path) {
* Returns an enumeration of the zip files in the registry
* Each element is a ZipFile.
*/
- public static Enumeration zipFiles() {
+ public static Enumeration zipFiles() {
return zipFileMap.elements();
}
diff --git a/appserver/persistence/cmp/generator-database/pom.xml b/appserver/persistence/cmp/generator-database/pom.xml
index 23148ccf42e..102c15957cf 100644
--- a/appserver/persistence/cmp/generator-database/pom.xml
+++ b/appserver/persistence/cmp/generator-database/pom.xml
@@ -52,7 +52,7 @@
org.glassfish.external
- dbschema
+ dbschema-osgi
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DBElementFactory.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DBElementFactory.java
index 8b9fe42a551..ad264d971cc 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DBElementFactory.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DBElementFactory.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,13 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * DBElementFactory.java
- *
- * Created on Jan 14, 2003
- */
-
-
package com.sun.jdo.spi.persistence.generator.database;
import org.netbeans.modules.dbschema.ColumnElement;
@@ -49,21 +43,19 @@ class DBElementFactory {
/**
* String which indicates that schema was generated.
*/
- private final static String TAGLINE =
- "generated schema version "; //NOI18N
+ private final static String TAGLINE = "generated schema version ";
/**
- * Signature which identifies version of database generator. Updated
+ * Signature which identifies version of database generator. Updated
* each time the file is checked in to CVS.
*/
- private static final String SIGNATURE =
- "$RCSfile: DBElementFactory.java,v $ $Revision: 1.3 $"; //NOI18N
+ private static final String SIGNATURE = "$RCSfile: DBElementFactory.java,v $ $Revision: 1.3 $";
/** Field type used if null is given in getColumnType. */
- private static final String UNKNOWN_FIELD_TYPE = "java.lang.Long"; // NOI18N
+ private static final String UNKNOWN_FIELD_TYPE = "java.lang.Long";
/** Field type used for user-defined types in getColumnType. */
- private static final String DEFAULT_FIELD_TYPE = "java.lang.Object"; // NOI18N
+ private static final String DEFAULT_FIELD_TYPE = "java.lang.Object";
/**
* Disallow outside construction.
@@ -78,10 +70,10 @@ private DBElementFactory() {
* @throws DBException
*/
static SchemaElement createSchema(String schemaName) throws DBException {
- SchemaElementImpl schemaImpl = new SchemaElementImpl();
- SchemaElement schema = new SchemaElement(schemaImpl);
+ SchemaElement schema = new SchemaElement(new SchemaElementImpl());
schema.setName(DBIdentifier.create(schemaName));
schema.setDatabaseProductVersion(TAGLINE + SIGNATURE);
+ schema.setDriver("DBElementFactoryVirtualDB");
return schema;
}
@@ -92,12 +84,8 @@ static SchemaElement createSchema(String schemaName) throws DBException {
* @return TableElement for this table name
* @throws DBException
*/
- static TableElement createAndAttachTable(SchemaElement schema,
- String tableName) throws DBException {
-
- String fullName = NameUtil.getAbsoluteTableName(
- schema.getName().getName(), tableName);
-
+ static TableElement createAndAttachTable(SchemaElement schema, String tableName) throws DBException {
+ String fullName = NameUtil.getAbsoluteTableName(schema.getName().getName(), tableName);
TableElementImpl tableImpl = new TableElementImpl(tableName);
TableElement table = new TableElement(tableImpl, schema);
table.setName(DBIdentifier.create(fullName));
@@ -113,12 +101,9 @@ static TableElement createAndAttachTable(SchemaElement schema,
* @return ColumnElement that represents the newly-added column.
* @throws DBException
*/
- static ColumnElement createAndAttachColumn(String columnName,
- TableElement table, JDBCInfo ji) throws DBException {
+ static ColumnElement createAndAttachColumn(String columnName, TableElement table, JDBCInfo ji) throws DBException {
// Create column id
- String fullName = NameUtil.getAbsoluteMemberName(
- table.getName().getName(), columnName);
DBIdentifier columnId = DBIdentifier.create(columnName);
ColumnElementImpl columnImpl = new ColumnElementImpl();
@@ -266,7 +251,7 @@ static JDBCInfo getColumnType(String fieldName, String fieldType,
// Object.
if (null == rc) {
// Treat as user-defined object type.
- rc = mappingPolicy.getJDBCInfo(null, DEFAULT_FIELD_TYPE); // NOI18N
+ rc = mappingPolicy.getJDBCInfo(null, DEFAULT_FIELD_TYPE);
}
return rc;
}
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseGenerator.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseGenerator.java
index 18c082fc704..2db6396e9a1 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseGenerator.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseGenerator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * DatabaseGenerator.java
- *
- * Created on Jan 14, 2003
- */
-
package com.sun.jdo.spi.persistence.generator.database;
import com.sun.jdo.api.persistence.model.Model;
@@ -35,9 +30,9 @@
import com.sun.jdo.api.persistence.model.mapping.impl.MappingFieldElementImpl;
import com.sun.jdo.api.persistence.model.mapping.impl.MappingRelationshipElementImpl;
import com.sun.jdo.spi.persistence.utility.JavaTypeHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import java.io.IOException;
+import java.lang.System.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -57,12 +52,16 @@
import org.netbeans.modules.dbschema.TableElement;
import org.netbeans.modules.dbschema.UniqueKeyElement;
+import static java.lang.System.Logger.Level.DEBUG;
+
/**
* This class generates a database schema and a Map of mapping classes from a
* set of JDO classes.
*/
public class DatabaseGenerator {
+ private static final Logger LOG = System.getLogger(DatabaseGenerator.class.getName());
+
/** @see DatabaseGenerationConstants#DOT */
private static final char DOT = DatabaseGenerationConstants.DOT;
@@ -74,11 +73,11 @@ public class DatabaseGenerator {
/** List of NameTuple objects which holds persistence class name,
* desired table name and hash class name for database generation. */
- private final List pcClasses;
+ private final List pcClasses;
/** Map from persistence-capable class names to MappingClassElement's. */
// See also DatabaseGenerator.Results.mappingClasses.
- private final Map mappingClasses = new HashMap();
+ private final Map mappingClasses = new HashMap<>();
/** Generated database schema. */
private final SchemaElement schema;
@@ -89,14 +88,8 @@ public class DatabaseGenerator {
*/
private final String classSuffix;
- /** The logger */
- private static final Logger logger =
- LogHelperDatabaseGenerator.getLogger();
-
/** I18N message handler */
- private static final ResourceBundle messages =
- I18NHelper.loadBundle(DatabaseGenerator.class);
-
+ private static final ResourceBundle messages = I18NHelper.loadBundle(DatabaseGenerator.class);
/**
* Contains the results of invoking DatabaseGenerator.generate()
@@ -110,11 +103,11 @@ public class Results {
// is intentional: DatabaseGenerator.addRelationships needs to get a
// MappingClassElement for a pc class name, but the clients of the
// DatabaseGenerator should only need the mapping classes.
- private final Set mappingClasses;
+ private final Set mappingClasses;
- Results(SchemaElement schema, Map mappingClasses) {
+ Results(SchemaElement schema, Map mappingClasses) {
this.schema = schema;
- this.mappingClasses = new HashSet(mappingClasses.values());
+ this.mappingClasses = new HashSet<>(mappingClasses.values());
}
/** @return Generated SchemaElement. */
@@ -123,7 +116,7 @@ public SchemaElement getSchema() {
}
/** @return Generated mapping classes. */
- public Set getMappingClasses() {
+ public Set getMappingClasses() {
return mappingClasses;
}
}
@@ -203,7 +196,7 @@ public String getDesiredTableName() {
* creating table names from class names.
*/
private DatabaseGenerator(
- Model model, List pcClasses, MappingPolicy mappingPolicy,
+ Model model, List pcClasses, MappingPolicy mappingPolicy,
String schemaName, String classSuffix)
throws DBException {
@@ -238,19 +231,14 @@ private DatabaseGenerator(
* of generation.
*/
public static Results generate(
- Model model, List pcClasses, MappingPolicy mappingPolicy,
+ Model model, List pcClasses, MappingPolicy mappingPolicy,
String schemaName, String classSuffix,
boolean generateMappingClasses)
throws DBException, IOException, ModelException {
- DatabaseGenerator generator = new DatabaseGenerator(
- model, pcClasses, mappingPolicy,
- schemaName, classSuffix);
-
+ DatabaseGenerator generator = new DatabaseGenerator(model, pcClasses, mappingPolicy, schemaName, classSuffix);
Results rc = generator.generate();
-
mappingPolicy.resetCounter();
-
return rc;
}
@@ -264,24 +252,19 @@ public static Results generate(
* of generation.
*/
private Results generate() throws DBException, ModelException {
- for (Iterator i = pcClasses.iterator(); i.hasNext();) {
- NameTuple nameTuple = (NameTuple) i.next();
+ for (Iterator i = pcClasses.iterator(); i.hasNext();) {
+ NameTuple nameTuple = i.next();
String pcClassName = nameTuple.getPersistenceClassName();
String desiredTableName = nameTuple.getDesiredTableName();
- PersistenceClassElement pcClass =
- model.getPersistenceClass(pcClassName);
-
- String tableName = mappingPolicy.getTableName(
- desiredTableName, getShortClassName(nameTuple.getHashClassName()));
- TableElement table = DBElementFactory.createAndAttachTable(
- schema, tableName);
- UniqueKeyElement pKey = DBElementFactory.createAndAttachPrimaryKey(
- table,
- mappingPolicy.getPrimaryKeyConstraintName(
- table.getName().getName()));
- MappingClassElement mappingClass = createMappingClass(
- pcClass, table);
+ PersistenceClassElement pcClass = model.getPersistenceClass(pcClassName);
+
+ String tableName = mappingPolicy.getTableName(desiredTableName,
+ getShortClassName(nameTuple.getHashClassName()));
+ TableElement table = DBElementFactory.createAndAttachTable(schema, tableName);
+ UniqueKeyElement pKey = DBElementFactory.createAndAttachPrimaryKey(table,
+ mappingPolicy.getPrimaryKeyConstraintName(table.getName().getName()));
+ MappingClassElement mappingClass = createMappingClass(pcClass, table);
PersistenceFieldElement[] fields = pcClass.getFields();
if (fields != null) {
@@ -289,35 +272,19 @@ private Results generate() throws DBException, ModelException {
PersistenceFieldElement field = fields[j];
String fieldName = field.getName();
if (!(field instanceof RelationshipElement)) {
- String columnName = mappingPolicy.getColumnName(
- desiredTableName, fieldName, tableName);
- String fieldType = model.getFieldType(
- pcClassName, fieldName);
- String fullFieldName =
- new StringBuffer(desiredTableName)
- .append(DOT).append(fieldName).toString();
- JDBCInfo columnType =
- DBElementFactory.getColumnType(
- fullFieldName,
- fieldType,
- mappingPolicy);
- if (logger.isLoggable(Logger.FINEST)) {
- logger.fine(
- "DBGenerator.generate: " // NOI18N
- + tableName + "." + columnName + ": " // NOI18N
- + columnType.toString());
- }
- ColumnElement column =
- DBElementFactory.createAndAttachColumn(
- columnName, table, columnType);
+ String columnName = mappingPolicy.getColumnName(desiredTableName, fieldName, tableName);
+ String fieldType = model.getFieldType(pcClassName, fieldName);
+ String fullFieldName = new StringBuilder(desiredTableName).append(DOT).append(fieldName).toString();
+ JDBCInfo columnType = DBElementFactory.getColumnType(fullFieldName, fieldType, mappingPolicy);
+ LOG.log(DEBUG, () -> "generate: " + tableName + "." + columnName + ": " + columnType);
+ ColumnElement column = DBElementFactory.createAndAttachColumn(columnName, table, columnType);
createAndAttachMappingField(fieldName, mappingClass, column);
if (field.isKey()) {
column.setNullable(false);
pKey.addColumn(column);
pKey.getAssociatedIndex().addColumn(column);
- mappingClass.getTable(tableName).addKeyColumn(
- column);
+ mappingClass.getTable(tableName).addKeyColumn(column);
}
}
}
@@ -338,15 +305,14 @@ private Results generate() throws DBException, ModelException {
private TableElement getPrimaryTable(MappingClassElement mappingClass)
throws DBException {
- List tables = mappingClass.getTables();
+ List tables = mappingClass.getTables();
- MappingTableElement tbl = (MappingTableElement) tables.get(0);
- if (tbl != null) {
- DBIdentifier tblName = DBIdentifier.create(tbl.getTable());
- return schema.getTable(tblName);
- } else {
+ MappingTableElement tbl = tables.get(0);
+ if (tbl == null) {
return null;
}
+ DBIdentifier tblName = DBIdentifier.create(tbl.getTable());
+ return schema.getTable(tblName);
}
/**
@@ -356,16 +322,13 @@ private TableElement getPrimaryTable(MappingClassElement mappingClass)
* @return MappingClassElement associated with table and PC class
* @throws ModelException
*/
- private MappingClassElement createMappingClass(
- PersistenceClassElement pcClass, TableElement table)
- throws ModelException {
-
- MappingClassElement mappingClass =
- new MappingClassElementImpl(pcClass);
+ private MappingClassElement createMappingClass(PersistenceClassElement pcClass, TableElement table)
+ throws ModelException {
+ MappingClassElement mappingClass = new MappingClassElementImpl(pcClass);
- mappingClass.setDatabaseRoot(schema);
- mappingClass.addTable(table);
- return mappingClass;
+ mappingClass.setDatabaseRoot(schema);
+ mappingClass.addTable(table);
+ return mappingClass;
}
/**
@@ -407,9 +370,8 @@ private void addMappingRelationship(String relationName,
MappingClassElement declaringClass, ForeignKeyElement fkey)
throws ModelException {
- MappingRelationshipElement impl = new MappingRelationshipElementImpl(
- relationName, declaringClass);
- ColumnPairElement [] pairs = fkey.getColumnPairs();
+ MappingRelationshipElement impl = new MappingRelationshipElementImpl(relationName, declaringClass);
+ ColumnPairElement[] pairs = fkey.getColumnPairs();
for (int i = 0; i < pairs.length; i++) {
ColumnPairElement pair = pairs[i];
@@ -431,14 +393,10 @@ private void addMappingRelationship(String relationName,
private void addAssocMappingRelationship(String relationName,
MappingClassElement declaringClass, ForeignKeyElement fkeyForeign)
throws ModelException {
-
- MappingRelationshipElement impl =
- (MappingRelationshipElement) declaringClass.getField(
- relationName);
+ MappingRelationshipElement impl = (MappingRelationshipElement) declaringClass.getField(relationName);
if (null == impl) {
- impl = new MappingRelationshipElementImpl(
- relationName, declaringClass);
+ impl = new MappingRelationshipElementImpl(relationName, declaringClass);
declaringClass.addField(impl);
}
@@ -477,8 +435,7 @@ private void addInverseMappingRelationship(String relationName,
// for join table, need to add two MappingRelationshipElement
if (null == impl) {
- impl = new MappingRelationshipElementImpl(relationName,
- declaringClass);
+ impl = new MappingRelationshipElementImpl(relationName, declaringClass);
declaringClass.addField(impl);
}
@@ -524,13 +481,11 @@ private ForeignKeyElement createRelationship(TableElement srcTable,
srcTable, relTable, relName, mappingPolicy, uniqueId);
if (srcIsJoin) {
- addInverseMappingRelationship(relName, mappingClass,
- fKey, true);
+ addInverseMappingRelationship(relName, mappingClass, fKey, true);
addAssocMappingRelationship(inverseRelName, relMappingClass, fKey);
} else {
addMappingRelationship(relName, mappingClass, fKey);
- addInverseMappingRelationship(inverseRelName, relMappingClass,
- fKey, false);
+ addInverseMappingRelationship(inverseRelName, relMappingClass, fKey, false);
}
return fKey;
}
@@ -541,28 +496,25 @@ private ForeignKeyElement createRelationship(TableElement srcTable,
* @throws DBException
* @throws ModelExpception
*/
- private void addRelationships()
- throws DBException, ModelException {
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("add relationship"); // NOI18N
- }
+ private void addRelationships() throws DBException, ModelException {
+ LOG.log(DEBUG, "add relationship");
- Map relationFKey = new HashMap();
+ Map relationFKey = new HashMap<>();
// This is a list of 1-1 relationships that are deferred for
// processing until all other relationships are processed. Deferral
// allows us to concentrate foreign keys on one side of the
// relationship.
- List deferredRelationships = new ArrayList();
+ List deferredRelationships = new ArrayList<>();
- for (Iterator i = mappingClasses.values().iterator(); i.hasNext();) {
- MappingClassElement mappingClass = (MappingClassElement) i.next();
+ for (Iterator i = mappingClasses.values().iterator(); i.hasNext();) {
+ MappingClassElement mappingClass = i.next();
String pcClassName = mappingClass.getName();
PersistenceClassElement pcClass =
model.getPersistenceClass(pcClassName);
- validateModel(pcClass, "pcClass", pcClassName); // NOI18N
+ validateModel(pcClass, "pcClass", pcClassName);
TableElement sourceTable = getPrimaryTable(mappingClass);
- validateModel(sourceTable, "sourceTable", pcClassName); // NOI18N
+ validateModel(sourceTable, "sourceTable", pcClassName);
// Create a string that can keep names unique
String uniqueId = getShortClassName(pcClassName);
@@ -581,49 +533,33 @@ private void addRelationships()
int upperBound = relation.getUpperBound();
// inverseRelationship
- String inverseRelName =
- relation.getInverseRelationshipName();
- validateModel(inverseRelName,
- "inverseRelName", relationName); // NOI18N
+ String inverseRelName = relation.getInverseRelationshipName();
+ validateModel(inverseRelName, "inverseRelName", relationName);
String relClassName = model.getRelatedClass(relation);
- validateModel(relClassName,
- "relClassName", relationName); // NOI18N
+ validateModel(relClassName, "relClassName", relationName);
// get related MappingClass and PersistenceClass
- MappingClassElement relMappingClass =
- (MappingClassElement) mappingClasses.get(relClassName);
- validateModel(relMappingClass,
- "relMappingClass", relClassName); // NOI18N
- PersistenceClassElement relClass =
- model.getPersistenceClass(relClassName);
- validateModel(relClass,
- "relClass", relClassName); // NOI18N
- RelationshipElement inverseRelation =
- relClass.getRelationship(inverseRelName);
- validateModel(inverseRelation,
- "inverseRelation", inverseRelName); // NOI18N
+ MappingClassElement relMappingClass = mappingClasses.get(relClassName);
+ validateModel(relMappingClass, "relMappingClass", relClassName);
+ PersistenceClassElement relClass = model.getPersistenceClass(relClassName);
+ validateModel(relClass, "relClass", relClassName);
+ RelationshipElement inverseRelation = relClass.getRelationship(inverseRelName);
+ validateModel(inverseRelation, "inverseRelation", inverseRelName);
TableElement relTable = getPrimaryTable(relMappingClass);
- validateModel(relTable,
- "relTable", relClassName); // NOI18N
+ validateModel(relTable, "relTable", relClassName);
int relUpperBound = inverseRelation.getUpperBound();
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine(
- "Before adding relationship:" // NOI18N
- + getTblInfo("sourceTable", sourceTable, relationName) // NOI18N
- + getTblInfo("relTable", relTable, inverseRelName)); // NOI18N
- }
+ LOG.log(DEBUG,
+ () -> "Before adding relationship:" + getTblInfo("sourceTable", sourceTable, relationName)
+ + getTblInfo("relTable", relTable, inverseRelName));
// XXX Suggest making each block below a separate method.
- if ((upperBound > 1) && (relUpperBound > 1)) {
+ if (upperBound > 1 && relUpperBound > 1) {
// M-N relationship, create new table
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("M-N relationship"); // NOI18N
- }
+ LOG.log(DEBUG, "M-N relationship");
- ForeignKeyElement fKey = getMappedForeignKey(
- relation, inverseRelation, relationFKey);
+ ForeignKeyElement fKey = getMappedForeignKey(relation, inverseRelation, relationFKey);
if (fKey == null) {
TableElement joinTable =
DBElementFactory.createAndAttachTable(
@@ -648,24 +584,14 @@ private void addRelationships()
// equal 1 side. So here, we do nothing: We add
// relationships at the 1 side for 1-M relationships,
// and the current mapping class is the many side.
-
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("M-1 relationship: skip"); // NOI18N
- }
-
+ LOG.log(DEBUG, "M-1 relationship: skip");
} else if ((upperBound == 1) && (relUpperBound >1)) {
// 1-M relationship, add foreign key at upperBound =
// 1 side
-
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("1-M relationship"); // NOI18N
- }
-
- ForeignKeyElement fKey = getMappedForeignKey(relation,
- inverseRelation, relationFKey);
+ LOG.log(DEBUG, "1-M relationship");
+ ForeignKeyElement fKey = getMappedForeignKey(relation, inverseRelation, relationFKey);
if (fKey == null) {
- fKey = createRelationship(sourceTable, relTable,
- relationName, inverseRelName, mappingClass,
+ fKey = createRelationship(sourceTable, relTable, relationName, inverseRelName, mappingClass,
relMappingClass, uniqueId, false);
relationFKey.put(relation, fKey);
}
@@ -682,9 +608,7 @@ private void addRelationships()
if (fKey == null) {
if (relation.getDeleteAction() ==
RelationshipElement.CASCADE_ACTION) {
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("1-1 relationship: cascade(this)"); // NOI18N
- }
+ LOG.log(DEBUG, "1-1 relationship: cascade(this)");
fKey = createRelationship(
sourceTable, relTable, relationName,
inverseRelName, mappingClass,
@@ -692,9 +616,7 @@ private void addRelationships()
relationFKey.put(relation, fKey);
} else if (inverseRelation.getDeleteAction() ==
RelationshipElement.CASCADE_ACTION) {
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("1-1 relationship: cascade(inverse)"); // NOI18N
- }
+ LOG.log(DEBUG, "1-1 relationship: cascade(inverse)");
fKey = createRelationship(
relTable, sourceTable,
inverseRelName, relationName,
@@ -702,9 +624,7 @@ private void addRelationships()
uniqueId, false);
relationFKey.put(inverseRelation, fKey);
} else {
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("1-1 relationship: defer"); // NOI18N
- }
+ LOG.log(DEBUG, "1-1 relationship: defer");
deferredRelationships.add(
new DeferredRelationship(
relation, inverseRelation,
@@ -715,12 +635,10 @@ private void addRelationships()
}
}
}
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine(
- "After adding relationship:" // NOI18N
- + getTblInfo("sourceTable", sourceTable, relationName) // NOI18N
- + getTblInfo("relTable", relTable, inverseRelName)); // NOI18N
- }
+ LOG.log(DEBUG, () ->
+ "After adding relationship:"
+ + getTblInfo("sourceTable", sourceTable, relationName)
+ + getTblInfo("relTable", relTable, inverseRelName));
}
}
}
@@ -739,11 +657,11 @@ private void addRelationships()
* indicating which relationships have already been mapped.
*/
private void addDeferredRelationships(
- List deferredRelationships, Map relationFKey)
+ List deferredRelationships, Map relationFKey)
throws DBException, ModelException {
- for (Iterator i = deferredRelationships.iterator(); i.hasNext();) {
- DeferredRelationship dr = (DeferredRelationship)i.next();
+ for (Iterator i = deferredRelationships.iterator(); i.hasNext();) {
+ DeferredRelationship dr = i.next();
RelationshipElement relation = dr.getRelation();
RelationshipElement inverseRelation = dr.getInverseRelation();
@@ -774,24 +692,21 @@ private void addDeferredRelationships(
relationName, inverseRelName,
mappingClass, relMappingClass,
uniqueId, false);
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine(
- "1-1 deferred relationship (this)" // NOI18N
- + getTblInfo("sourceTable", sourceTable, relationName) // NOI18N
- + getTblInfo("relTable", relTable, inverseRelName)); // NOI18N
- }
+
+ LOG.log(DEBUG, () -> "1-1 deferred relationship (this)"
+ + getTblInfo("sourceTable", sourceTable, relationName)
+ + getTblInfo("relTable", relTable, inverseRelName));
+
} else {
fKey = createRelationship(
relTable, sourceTable,
inverseRelName, relationName,
relMappingClass, mappingClass,
uniqueId, false);
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine(
- "1-1 deferred relationship (inverse)" // NOI18N
- + getTblInfo("sourceTable", sourceTable, relationName) // NOI18N
- + getTblInfo("relTable", relTable, inverseRelName)); // NOI18N
- }
+ LOG.log(DEBUG, () -> "1-1 deferred relationship (inverse)"
+ + getTblInfo("sourceTable", sourceTable, relationName)
+ + getTblInfo("relTable", relTable, inverseRelName));
+
}
relationFKey.put(relation, fKey);
}
@@ -860,18 +775,14 @@ static class DeferredRelationship {
* @param relationFKey a map to hold relation and foreign key
* @return the foreign key element or null
*/
- private ForeignKeyElement getMappedForeignKey(
- RelationshipElement relation, RelationshipElement inverseRelation,
- Map relationFKey) {
-
- ForeignKeyElement fkey =
- (ForeignKeyElement) relationFKey.get(relation);
+ private ForeignKeyElement getMappedForeignKey(RelationshipElement relation, RelationshipElement inverseRelation,
+ Map relationFKey) {
+ ForeignKeyElement fkey = relationFKey.get(relation);
if (fkey == null) {
- return (ForeignKeyElement) relationFKey.get(inverseRelation);
- } else {
- return fkey;
+ return relationFKey.get(inverseRelation);
}
+ return fkey;
}
/**
@@ -905,12 +816,7 @@ private void validateModel(Object o,
String failedItem,
String accessor) throws ModelException {
if (null == o) {
- String msg = I18NHelper.getMessage(
- messages,
- "EXC_InvalidRelationshipMapping", // NOI18N
- failedItem,
- accessor);
- logger.log(Logger.SEVERE, msg);
+ String msg = I18NHelper.getMessage(messages, "EXC_InvalidRelationshipMapping", failedItem, accessor);
throw new ModelException(msg);
}
}
@@ -929,8 +835,8 @@ private static String getTblInfo(String tblName, TableElement tbl, String relNam
fk = tbl.getForeignKeys()[0];
}
return " " + tblName + "=" + tbl.toString()
- + ", # keys=" + numFK // NOI18N
- + ", 1st key=" + fk // NOI18N
- + "; relationship Name=" + relName; // NOI18N
+ + ", # keys=" + numFK
+ + ", 1st key=" + fk
+ + "; relationship Name=" + relName;
}
}
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseOutputStream.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseOutputStream.java
index b02e91876c0..9f341c25285 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseOutputStream.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/DatabaseOutputStream.java
@@ -23,13 +23,14 @@
package com.sun.jdo.spi.persistence.generator.database;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
import java.io.OutputStream;
+import java.lang.System.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
+import static java.lang.System.Logger.Level.DEBUG;
+
/*
* Represents a database connection as an output stream.
@@ -37,9 +38,8 @@
* @author Jie Leng
*/
public class DatabaseOutputStream extends OutputStream {
- /** The logger */
- private static final Logger logger =
- LogHelperDatabaseGenerator.getLogger();
+ private static final Logger LOG = System.getLogger(DatabaseOutputStream.class.getName());
+
/** Connection to the database. */
// XXX FIXME S/b final; make it so if we can get rid of setConnection.
@@ -60,6 +60,7 @@ public DatabaseOutputStream() {
/**
* Closes the database connection.
*/
+ @Override
public void close() {
try {
// XXX test is not necessary once we assert not null in constructor
@@ -70,14 +71,14 @@ public void close() {
}
} catch (SQLException e) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine("Exception in cleanup", e); // NOI18N
+ LOG.log(DEBUG, "Exception in close", e);
}
}
/**
* Commits the database connection.
*/
+ @Override
public void flush() {
try {
// XXX test is not necessary once we assert not null in constructor
@@ -85,8 +86,7 @@ public void flush() {
conn_.commit();
}
} catch (SQLException e) {
- if (logger.isLoggable(Logger.FINE))
- logger.fine("Exception in cleanup", e); // NOI18N
+ LOG.log(DEBUG, "Exception in commit", e);
}
}
@@ -96,6 +96,7 @@ public void flush() {
* always throws UnsupportedOperationException.
* @throws UnsupportedOperationException
*/
+ @Override
public void write(int b) {
throw new UnsupportedOperationException();
}
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/JDBCInfo.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/JDBCInfo.java
index a5af1048045..2c1ab5ffc68 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/JDBCInfo.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/JDBCInfo.java
@@ -18,7 +18,10 @@
import com.sun.jdo.spi.persistence.utility.StringHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
+
+import java.lang.System.Logger;
+
+import static java.lang.System.Logger.Level.DEBUG;
/**
* Represents how a JDBC type (i.e., one defined by java.sql.Types) is
@@ -58,10 +61,6 @@ class JDBCInfo {
/** Flag value which indicates that a JDBCInfo does not have a length. */
private static final Integer NO_LENGTH = new Integer(-1);
- /** Logger for warning & error messages */
- private static final Logger logger =
- LogHelperDatabaseGenerator.getLogger();
-
/** Value from java.sql.Types. */
private int jdbcType;
@@ -104,6 +103,7 @@ class JDBCInfo {
private static final byte MASK_ALL = MASK_JDBC_TYPE | MASK_NULLABLE
| MASK_PRECISION | MASK_SCALE | MASK_LENGTH;
+ private static final Logger LOG = System.getLogger(JDBCInfo.class.getName());
/**
* Constructor which initializes all fields.
@@ -229,11 +229,9 @@ private Integer getIntegerValue(String s) {
// specifies an invalid override, we should log a warning, warn the user,
// and use the other..
void complete(JDBCInfo other) {
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("Entering JDBCInfo.complete: " // NOI18N
- + "\nthis: " + this // NOI18N
- + "\nother: " + other); // NOI18N
- }
+ LOG.log(DEBUG, () -> "Entering JDBCInfo.complete: "
+ + "\nthis: " + this
+ + "\nother: " + other);
if (MASK_ALL != fieldsWithValues) {
if ((fieldsWithValues & MASK_JDBC_TYPE) == 0) {
this.jdbcType = other.jdbcType;
@@ -259,12 +257,10 @@ void complete(JDBCInfo other) {
fieldsWithValues = MASK_ALL;
}
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("Leaving JDBCInfo.complete: " // NOI18N
- + "\nthis: " + this); // NOI18N
- }
+ LOG.log(DEBUG, () -> "Leaving JDBCInfo.complete.\nthis: " + this);
}
+
/**
* @return true if this instance has been assigned values
* for all fields.
@@ -333,14 +329,15 @@ public Integer getLength() {
* Debugging support.
* @return A String with the value of each field.
*/
+ @Override
public String toString() {
- return "JDBCInfo:" // NOI18N
- + " jdbcType=" + jdbcType // NOI18N
- + " nullable=" + nullable // NOI18N
- + " precision=" + precision // NOI18N
- + " scale=" + scale // NOI18N
- + " length=" + length // NOI18N
- + " fieldsWithValues=0x" + Integer.toHexString(fieldsWithValues); // NOI18N
+ return "JDBCInfo:"
+ + " jdbcType=" + jdbcType
+ + " nullable=" + nullable
+ + " precision=" + precision
+ + " scale=" + scale
+ + " length=" + length
+ + " fieldsWithValues=0x" + Integer.toHexString(fieldsWithValues);
}
/**
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/LogHelperDatabaseGenerator.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/LogHelperDatabaseGenerator.java
index 648ed1e3b36..63aa5d17fd4 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/LogHelperDatabaseGenerator.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/LogHelperDatabaseGenerator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,26 +15,16 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * LogHelperDBGenerator.java
- *
- * Created on Jan 14, 2003
- */
-
-
package com.sun.jdo.spi.persistence.generator.database;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
/**
*
- * @author Jie Leng
+ * @author Jie Leng 2003
*/
class LogHelperDatabaseGenerator {
/** The component name for this component */
- private static final String componentName = "databaseGenerator"; // NOI18N
+ private static final String componentName = "databaseGenerator";
/** The class loader for this component */
private static final ClassLoader loader =
@@ -41,12 +32,6 @@ class LogHelperDatabaseGenerator {
/** The bundle name for this component */
private static final String bundleName =
- "com.sun.jdo.spi.persistence.generator.database.Bundle"; // NOI18N
+ "com.sun.jdo.spi.persistence.generator.database.Bundle";
- /**
- * @return The logger for the database generator component.
- */
- static Logger getLogger() {
- return LogHelper.getLogger(componentName, bundleName, loader);
- }
}
diff --git a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java
index 063c15fb9fa..e3c5e5c3582 100644
--- a/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java
+++ b/appserver/persistence/cmp/generator-database/src/main/java/com/sun/jdo/spi/persistence/generator/database/MappingPolicy.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2024 Contributors to the Eclipse Foundation.
+ * Copyright (c) 2024, 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -15,21 +15,15 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingPolicy.java
- *
- * Created on Jan 14, 2003
- */
-
package com.sun.jdo.spi.persistence.generator.database;
import com.sun.jdo.spi.persistence.utility.StringHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.System.Logger;
import java.sql.Types;
import java.util.Enumeration;
import java.util.HashMap;
@@ -46,6 +40,10 @@
import org.glassfish.persistence.common.I18NHelper;
import org.glassfish.persistence.common.database.DBVendorTypeHelper;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.ERROR;
+import static java.lang.System.Logger.Level.INFO;
+
// XXX Capitalization of acronyms such as Jdbc vs. JDBC is inconsistent
// throught out this package.
@@ -77,18 +75,18 @@ public class MappingPolicy implements Cloneable {
//
/** Base name to denote a class. */
- private static final String CLASS_BASE = "{class-name}"; //NOI18N
+ private static final String CLASS_BASE = "{class-name}";
/** Base name to denote a field. */
- private static final String FIELD_BASE = "{field-name}"; //NOI18N
+ private static final String FIELD_BASE = "{field-name}";
/** Base name to denote a relationship field. */
private static final String RELATIONSHIP_BASE =
- "{relationship-field-name}"; //NOI18N
+ "{relationship-field-name}";
/** Represents a '.' in a regular expression */
- private static String REGEXP_DOT = "\\."; // NOI18N
+ private static String REGEXP_DOT = "\\.";
/** Synonym for DatabaseGenerationConstants.INDICATOR_JDBC_PREFIX. */
private static final String INDICATOR_JDBC_PREFIX =
@@ -109,19 +107,19 @@ public class MappingPolicy implements Cloneable {
/** Indicator that property is for a table name. */
private static final String INDICATOR_TABLE_NAME =
- "table-name"; //NOI18N
+ "table-name";
/** Indicator that property is for a column name. */
private static final String INDICATOR_COLUMN_NAME =
- "column-name"; //NOI18N
+ "column-name";
/** Indicator that property is for a join table name. */
private static final String INDICATOR_JOIN_TABLE_NAME =
- "join-table-name"; //NOI18N
+ "join-table-name";
/** Indicator that property is for a constraint name. */
private static final String INDICATOR_CONSTRAINT_NAME =
- "constraint-name"; //NOI18N
+ "constraint-name";
//
@@ -162,7 +160,7 @@ public class MappingPolicy implements Cloneable {
/** Property value indicating table name must be same as class name. */
private static final String TABLE_NAME_AS_CLASSNAME =
- "{className}"; //NOI18N
+ "{className}";
/** Property value indicating table name must be upper case. */
private static final String TABLE_NAME_UPPERCASE =
@@ -170,11 +168,11 @@ public class MappingPolicy implements Cloneable {
/** Property value indicating table name must be uppercase and unique. */
private static final String TABLE_NAME_HASH_UPPERCASE =
- "{HASH-CLASSNAME}"; //NOI18N
+ "{HASH-CLASSNAME}";
/** Property value indicating colum name must be same as field name. */
private static final String COLUMN_NAME_AS_FIELDNAME =
- "{fieldName}"; //NOI18N
+ "{fieldName}";
/** Property value indicating column name must be uppercase. */
private static final String COLUMN_NAME_UPPERCASE =
@@ -182,11 +180,11 @@ public class MappingPolicy implements Cloneable {
/** Property value indicating join table name must be uppercase. */
private static final String JOIN_TABLE_NAME_UPPERCASE =
- "{CLASSNAMES}"; //NOI18N
+ "{CLASSNAMES}";
/** Property value indicating constraint name must be uppercase. */
private static final String CONSTRAINT_NAME_UPPERCASE =
- "{FIELDNAMES}"; //NOI18N
+ "{FIELDNAMES}";
//
@@ -195,74 +193,74 @@ public class MappingPolicy implements Cloneable {
//
/** Indicator that property is for formatting SQL */
- private static final String INDICATOR_SQL_FORMAT = "sql-format"; //NOI18N
+ private static final String INDICATOR_SQL_FORMAT = "sql-format";
/** The indicator for a statement separator. */
private static final String STATEMENT_SEPARATOR_INDICATOR =
- "statementSeparator"; // NOI18N
+ "statementSeparator";
/** The indicator for starting a "create table". */
private static final String CREATE_TABLE_START_INDICATOR =
- "createTableStart"; // NOI18N
+ "createTableStart";
/** The indicator for ending a "create table". */
private static final String CREATE_TABLE_END_INDICATOR =
- "createTableEnd"; // NOI18N
+ "createTableEnd";
/** The indicator for "create index". Added for Symfoware support as */
/** indexes on primary keys are mandatory */
private static final String CREATE_INDEX_INDICATOR =
- "createIndex"; // NOI18N
+ "createIndex";
/** The indicator for starting a "drop table". */
private static final String DROP_TABLE_INDICATOR =
- "dropTable"; // NOI18N
+ "dropTable";
/** The indicator for "add constraint". */
private static final String ALTER_TABLE_ADD_CONSTRAINT_START_INDICATOR =
- "alterTableAddConstraintStart"; // NOI18N
+ "alterTableAddConstraintStart";
/** The indicator for "drop constraint". */
private static final String ALTER_TABLE_DROP_CONSTRAINT_INDICATOR =
- "alterTableDropConstraint"; // NOI18N
+ "alterTableDropConstraint";
/** The indicator for adding a primary key constraint. */
private static final String PRIMARY_KEY_CONSTRAINT_INDICATOR =
- "primaryKeyConstraint"; // NOI18N
+ "primaryKeyConstraint";
/** The indicator for adding a foreign key constraint. */
private static final String FOREIGN_KEY_CONSTRAINT_INDICATOR =
- "foreignKeyConstraint"; // NOI18N
+ "foreignKeyConstraint";
/** The indicator for verbose nullability. */
private static final String COLUMN_NULLABILITY_INDICATOR =
- "columnNullability"; // NOI18N
+ "columnNullability";
/** The indicator for information used with LOB columns. */
private static final String LOB_LOGGING_INDICATOR =
- "LOBLogging"; // NOI18N
+ "LOBLogging";
//
// The remaining constants are neither bases nor indicators.
//
/** Prefix of column names which are primary key columns. */
- private static final String PK_PREFIX = "PK_"; //NOI18N
+ private static final String PK_PREFIX = "PK_";
/** Prefix of column names which are foreign key columns. */
- private static final String FK_PREFIX = "FK_"; //NOI18N
+ private static final String FK_PREFIX = "FK_";
/** Name of the "global" namespace. */
- private static final String GLOBAL_NAMING_SPACE = "GLOBAL"; //NOI18N
+ private static final String GLOBAL_NAMING_SPACE = "GLOBAL";
/** Property name which indicates unique table names should be generated. */
- public static final String USE_UNIQUE_TABLE_NAMES = "use-unique-table-names"; // NOI18N
+ public static final String USE_UNIQUE_TABLE_NAMES = "use-unique-table-names";
/** Property name which indicates reserved words. */
- private static final String RESERVED_WORDS = "reserved-words";// NOI18N
+ private static final String RESERVED_WORDS = "reserved-words";
/** When appended to a reserved word, causes it to be not-reserved. */
- private static final String RESERVED_WORD_UNRESERVER = "9"; // NOI18N
+ private static final String RESERVED_WORD_UNRESERVER = "9";
/**
* Maximum length of the counter used to create unique names with a
@@ -279,10 +277,10 @@ public class MappingPolicy implements Cloneable {
* are located.
*/
private static final String PROPERTY_FILE_DIR =
- "com/sun/jdo/spi/persistence/generator/database/"; // NOI18N
+ "com/sun/jdo/spi/persistence/generator/database/";
/** Extension used by properties files. */
- private static final String PROPERTY_FILE_EXT = ".properties"; // NOI18N
+ private static final String PROPERTY_FILE_EXT = ".properties";
//
// The above are all constants; below things get "interesting".
@@ -305,13 +303,14 @@ public class MappingPolicy implements Cloneable {
* Map from String names to the Integer-boxed values from
* java.sql.Types.
*/
- private static final Map jdbcTypes = new HashMap();
+ private static final Map jdbcTypes = new HashMap<>();
/**
* Maps from Integer-boxed values from java.sql.Types to String names.
*/
- private static final Map jdbcTypeNames = new HashMap();
+ private static final Map jdbcTypeNames = new HashMap<>();
+ private static final Logger LOG = System.getLogger(MappingPolicy.class.getName());
/**
* Global counter for creating unique names in each of the namespaces.
@@ -323,7 +322,7 @@ public class MappingPolicy implements Cloneable {
* Map from namespaces to Set of names defined in each namespace. Used
* to ensure uniqueness within namespaces.
*/
- private Map namespaces = new HashMap();
+ private Map> namespaces = new HashMap<>();
/**
* Indicates whether or not generated table names should include a
@@ -334,12 +333,12 @@ public class MappingPolicy implements Cloneable {
/**
* Set of reserved words for a particular policy.
*/
- private final Set reservedWords = new TreeSet();
+ private final Set reservedWords = new TreeSet<>();
/**
* Set of reserved words for the default database.
*/
- private static Set defaultReservedWords;
+ private static Set defaultReservedWords;
/**
* Map from the string names of the java types (e.g. "java.lang.String")
@@ -347,20 +346,20 @@ public class MappingPolicy implements Cloneable {
* type. Different for different dbvendor types, but the same instance,
* per dbvendor, is shared by all MappingPolicy instances.
*/
- private final Map dbJdbcInfoMap = new HashMap();
+ private final Map dbJdbcInfoMap = new HashMap<>();
/**
* Similar to {@link #dbJdbcInfoMap}, but is reinitialized by each
* clone(). Contains user-provided overrides of the information in
* dbjdbcInfoMap.
*/
- private Map userJdbcInfoMap = new HashMap();
+ private Map userJdbcInfoMap = new HashMap<>();
/**
* Map from a boxed value based on fields in java.sql.Types to the String
* name of a SQL type.
*/
- private final Map sqlInfo = new HashMap();
+ private final Map sqlInfo = new HashMap<>();
//
@@ -425,15 +424,10 @@ public class MappingPolicy implements Cloneable {
private final Map namingPolicy = new HashMap();
/** Map from database vendor names to instances of MappingPolicy. */
- private static final Map instances = new HashMap();
-
- /** Logger for warning & error messages */
- private static final Logger logger =
- LogHelperDatabaseGenerator.getLogger();
+ private static final Map instances = new HashMap<>();
/** I18N message handler */
- private final static ResourceBundle messages =
- I18NHelper.loadBundle(MappingPolicy.class);
+ private static final ResourceBundle messages = I18NHelper.loadBundle(MappingPolicy.class);
//
// Initialize the JDBC String to Integer map and the default (SQL92)
@@ -449,43 +443,43 @@ public class MappingPolicy implements Cloneable {
// is given: Error? Warning, continue running?
static {
// Initialize jdbcType map.
- jdbcTypes.put("BIGINT", new Integer(Types.BIGINT)); // NOI18N
- jdbcTypes.put("BIT", new Integer(Types.BIT)); // NOI18N
- jdbcTypes.put("BLOB", new Integer(Types.BLOB)); // NOI18N
- jdbcTypes.put("CHAR", new Integer(Types.CHAR)); // NOI18N
- jdbcTypes.put("CLOB", new Integer(Types.CLOB)); // NOI18N
- jdbcTypes.put("DATE", new Integer(Types.DATE)); // NOI18N
- jdbcTypes.put("DECIMAL", new Integer(Types.DECIMAL)); // NOI18N
- jdbcTypes.put("DOUBLE", new Integer(Types.DOUBLE)); // NOI18N
- jdbcTypes.put("INTEGER", new Integer(Types.INTEGER)); // NOI18N
- jdbcTypes.put("LONGVARBINARY", new Integer(Types.LONGVARBINARY)); // NOI18N
- jdbcTypes.put("LONGVARCHAR", new Integer(Types.LONGVARCHAR)); // NOI18N
- jdbcTypes.put("NULL", new Integer(Types.NULL)); // NOI18N
- jdbcTypes.put("REAL", new Integer(Types.REAL)); // NOI18N
- jdbcTypes.put("SMALLINT", new Integer(Types.SMALLINT)); // NOI18N
- jdbcTypes.put("TIME", new Integer(Types.TIME)); // NOI18N
- jdbcTypes.put("TIMESTAMP", new Integer(Types.TIMESTAMP)); // NOI18N
- jdbcTypes.put("TINYINT", new Integer(Types.TINYINT)); // NOI18N
- jdbcTypes.put("VARCHAR", new Integer(Types.VARCHAR)); // NOI18N
-
- jdbcTypeNames.put(new Integer(Types.BIGINT), "BIGINT"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.BIT), "BIT"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.BLOB), "BLOB"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.CHAR), "CHAR"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.CLOB), "CLOB"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.DATE), "DATE"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.DECIMAL), "DECIMAL"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.DOUBLE), "DOUBLE"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.INTEGER), "INTEGER"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.LONGVARBINARY), "LONGVARBINARY"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.LONGVARCHAR), "LONGVARCHAR"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.NULL), "NULL"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.REAL), "REAL"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.SMALLINT), "SMALLINT"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.TIME), "TIME"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.TIMESTAMP), "TIMESTAMP"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.TINYINT), "TINYINT"); // NOI18N
- jdbcTypeNames.put(new Integer(Types.VARCHAR), "VARCHAR"); // NOI18N
+ jdbcTypes.put("BIGINT", Integer.valueOf(Types.BIGINT));
+ jdbcTypes.put("BIT", Integer.valueOf(Types.BIT));
+ jdbcTypes.put("BLOB", Integer.valueOf(Types.BLOB));
+ jdbcTypes.put("CHAR", Integer.valueOf(Types.CHAR));
+ jdbcTypes.put("CLOB", Integer.valueOf(Types.CLOB));
+ jdbcTypes.put("DATE", Integer.valueOf(Types.DATE));
+ jdbcTypes.put("DECIMAL", Integer.valueOf(Types.DECIMAL));
+ jdbcTypes.put("DOUBLE", Integer.valueOf(Types.DOUBLE));
+ jdbcTypes.put("INTEGER", Integer.valueOf(Types.INTEGER));
+ jdbcTypes.put("LONGVARBINARY", Integer.valueOf(Types.LONGVARBINARY));
+ jdbcTypes.put("LONGVARCHAR", Integer.valueOf(Types.LONGVARCHAR));
+ jdbcTypes.put("NULL", Integer.valueOf(Types.NULL));
+ jdbcTypes.put("REAL", Integer.valueOf(Types.REAL));
+ jdbcTypes.put("SMALLINT", Integer.valueOf(Types.SMALLINT));
+ jdbcTypes.put("TIME", Integer.valueOf(Types.TIME));
+ jdbcTypes.put("TIMESTAMP", Integer.valueOf(Types.TIMESTAMP));
+ jdbcTypes.put("TINYINT", Integer.valueOf(Types.TINYINT));
+ jdbcTypes.put("VARCHAR", Integer.valueOf(Types.VARCHAR));
+
+ jdbcTypeNames.put(Integer.valueOf(Types.BIGINT), "BIGINT");
+ jdbcTypeNames.put(Integer.valueOf(Types.BIT), "BIT");
+ jdbcTypeNames.put(Integer.valueOf(Types.BLOB), "BLOB");
+ jdbcTypeNames.put(Integer.valueOf(Types.CHAR), "CHAR");
+ jdbcTypeNames.put(Integer.valueOf(Types.CLOB), "CLOB");
+ jdbcTypeNames.put(Integer.valueOf(Types.DATE), "DATE");
+ jdbcTypeNames.put(Integer.valueOf(Types.DECIMAL), "DECIMAL");
+ jdbcTypeNames.put(Integer.valueOf(Types.DOUBLE), "DOUBLE");
+ jdbcTypeNames.put(Integer.valueOf(Types.INTEGER), "INTEGER");
+ jdbcTypeNames.put(Integer.valueOf(Types.LONGVARBINARY), "LONGVARBINARY");
+ jdbcTypeNames.put(Integer.valueOf(Types.LONGVARCHAR), "LONGVARCHAR");
+ jdbcTypeNames.put(Integer.valueOf(Types.NULL), "NULL");
+ jdbcTypeNames.put(Integer.valueOf(Types.REAL), "REAL");
+ jdbcTypeNames.put(Integer.valueOf(Types.SMALLINT), "SMALLINT");
+ jdbcTypeNames.put(Integer.valueOf(Types.TIME), "TIME");
+ jdbcTypeNames.put(Integer.valueOf(Types.TIMESTAMP), "TIMESTAMP");
+ jdbcTypeNames.put(Integer.valueOf(Types.TINYINT), "TINYINT");
+ jdbcTypeNames.put(Integer.valueOf(Types.VARCHAR), "VARCHAR");
try {
@@ -493,11 +487,8 @@ public class MappingPolicy implements Cloneable {
new MappingPolicy();
} catch (Throwable ex) {
- logger.log(Logger.SEVERE,
- I18NHelper.getMessage(
- messages,
- "EXC_MappingPolicyNotFound", //NOI18N
- DBVendorTypeHelper.DEFAULT_DB));
+ LOG.log(ERROR,
+ () -> I18NHelper.getMessage(messages, "EXC_MappingPolicyNotFound", DBVendorTypeHelper.DEFAULT_DB));
}
}
@@ -507,8 +498,7 @@ public class MappingPolicy implements Cloneable {
// This should be invoked only once per JVM. See the class static
// block of code above.
private MappingPolicy() throws IOException {
- load(getPropertyFileName(DBVendorTypeHelper.DEFAULT_DB),
- defaultProps, false);
+ load(getPropertyFileName(DBVendorTypeHelper.DEFAULT_DB), defaultProps, false);
init(defaultProps);
// The DEFAULT_DB has reserved words for the default database type.
@@ -518,9 +508,7 @@ private MappingPolicy() throws IOException {
instances.put(DBVendorTypeHelper.DEFAULT_DB, this);
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("new MappingPolicy():\n" + toString()); // NOI18N
- }
+ LOG.log(DEBUG, () -> "new MappingPolicy():\n" + toString());
}
/**
@@ -537,10 +525,7 @@ private MappingPolicy(String databaseType) throws IOException {
init(mergedProp);
instances.put(databaseType, this);
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("new MappingPolicy(" // NOI18N
- + databaseType + "):\n" + toString()); // NOI18N
- }
+ LOG.log(DEBUG, () -> "new MappingPolicy(" + databaseType + "):\n" + toString());
}
/**
@@ -553,12 +538,8 @@ private MappingPolicy(String databaseType) throws IOException {
* @throws IOException if there are problems reading the vendor-
* specific mappinng policy file
*/
- public synchronized static MappingPolicy getMappingPolicy(
- String databaseType) throws IOException {
-
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("get MappingPolicy"+databaseType); // NOI18N
- }
+ public synchronized static MappingPolicy getMappingPolicy(String databaseType) throws IOException {
+ LOG.log(DEBUG, "get MappingPolicy {0}", databaseType);
MappingPolicy mappingPolicy = null;
try {
@@ -568,7 +549,7 @@ public synchronized static MappingPolicy getMappingPolicy(
// are *not* using databaseType given, that we are using
// SQL92 instead, and provide list of recognized names.
}
- mappingPolicy = (MappingPolicy) instances.get(databaseType);
+ mappingPolicy = instances.get(databaseType);
if (mappingPolicy == null) {
mappingPolicy = new MappingPolicy(databaseType);
}
@@ -608,9 +589,7 @@ private synchronized void load(
final String resourceName, Properties properties, boolean override)
throws IOException {
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("load resource:" + resourceName); // NOI18N
- }
+ LOG.log(DEBUG, () ->"load resource: " + resourceName);
InputStream bin = null;
InputStream in = null;
@@ -632,15 +611,13 @@ private synchronized void load(
if (in == null) {
throw new IOException(I18NHelper.getMessage(messages,
- "EXC_ResourceNotFound", resourceName));// NOI18N
+ "EXC_ResourceNotFound", resourceName));
}
}
bin = new BufferedInputStream(in);
properties.load(bin);
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("load "+resourceName + " successfuly"); // NOI18N
- }
+ LOG.log(DEBUG, () -> "load " + resourceName + " successfuly");
} finally {
try {
bin.close();
@@ -666,43 +643,34 @@ void resetCounter() {
* @param props Properties which override built in defaults.
*/
public void setUserPolicy(Properties props) {
- if (null != props) {
-
- // Look for and set JDBCInfo entries. Use Enumeration instead of
- // iterator because former gets default values while latter does
- // not.
- for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
- String name = (String) e.nextElement();
- String value = props.getProperty(name);
-
- if (name.equals(USE_UNIQUE_TABLE_NAMES)) {
- if (! StringHelper.isEmpty(value)) {
- uniqueTableName =
- Boolean.valueOf(value).booleanValue();
- }
- continue;
+ if (props == null) {
+ return;
+ }
+ // Look for and set JDBCInfo entries. Use Enumeration instead of
+ // iterator because former gets default values while latter does
+ // not.
+ for (String name : props.stringPropertyNames()) {
+ String value = props.getProperty(name);
+ if (name.equals(USE_UNIQUE_TABLE_NAMES)) {
+ if (!StringHelper.isEmpty(value)) {
+ uniqueTableName = Boolean.valueOf(value).booleanValue();
}
+ continue;
+ }
- StringTokenizer nameParser =
- new StringTokenizer(name, String.valueOf(DOT));
+ StringTokenizer nameParser = new StringTokenizer(name, String.valueOf(DOT));
- // Get the last element from key which is separated by DOT.
- String indicator = null;
- while (nameParser.hasMoreTokens()) {
- indicator = nameParser.nextToken();
- }
+ // Get the last element from key which is separated by DOT.
+ String indicator = null;
+ while (nameParser.hasMoreTokens()) {
+ indicator = nameParser.nextToken();
+ }
+
+ if (indicator.startsWith(INDICATOR_JDBC_PREFIX)) {
+ setJDBCInfoEntry(userJdbcInfoMap, name, value, indicator);
+ } else {
+ LOG.log(INFO, () -> I18NHelper.getMessage(messages, "MSG_UnexpectedUserProp", name, value));
- if (indicator.startsWith(INDICATOR_JDBC_PREFIX)) {
- setJDBCInfoEntry(userJdbcInfoMap, name, value, indicator);
- } else {
- if (logger.isLoggable(Logger.INFO)) {
- logger.info(
- I18NHelper.getMessage(
- messages,
- "MSG_UnexpectedUserProp", // NOI18N
- name, value)); // NOI18N
- }
- }
}
}
}
@@ -722,19 +690,14 @@ public void setUniqueTableName(boolean uniqueTableName) {
* @return Name of SQL type corresponding to given jdbcType.
*/
public String getSQLTypeName(int jdbcType) {
- String rc = null;
-
// The name is in sqlInfo if it was loaded from one of our
// vendor-specific properties files.
- Object o = sqlInfo.get(new Integer(jdbcType));
- if (null != o) {
- rc = (String) o;
- } else {
- // Otherwise, user has overriden, e.g. java.lang.String -> CLOB.
- rc = getJdbcTypeName(jdbcType);
+ String stringType = sqlInfo.get(Integer.valueOf(jdbcType));
+ if (stringType == null) {
+ // Otherwise, user has overridden, e.g. java.lang.String -> CLOB.
+ return getJdbcTypeName(jdbcType);
}
-
- return rc;
+ return stringType;
}
/**
@@ -762,18 +725,15 @@ public String getSQLTypeName(int jdbcType) {
public JDBCInfo getJDBCInfo(String fieldName, String fieldType) {
JDBCInfo rc = null;
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("Entering MappingPolicy.getJDBCInfo: " // NOI18N
- + fieldName + ", " + fieldType); // NOI18N
- }
+ LOG.log(DEBUG, () -> "Entering MappingPolicy.getJDBCInfo: " + fieldName + ", " + fieldType);
- if (null != fieldName) {
+ if (fieldName != null) {
// If fieldName is given, try to find a JDBCInfo using that name.
// Looking up fieldName only makes sense in userJdbcInfoMap
// which contains the user's overrides.
- rc = (JDBCInfo) userJdbcInfoMap.get(fieldName);
- if (null != rc && (! rc.isComplete())) {
+ rc = userJdbcInfoMap.get(fieldName);
+ if (rc != null && (! rc.isComplete())) {
// There is an override for the field named fieldName, but
// it is not complete, i.e., not all possible information
@@ -796,7 +756,7 @@ public JDBCInfo getJDBCInfo(String fieldName, String fieldType) {
}
}
- if (null == rc) {
+ if (rc == null) {
// Either fieldName is null, or there is no JDBCInfo specific to
// fieldName, so use fieldType.
@@ -811,12 +771,8 @@ public JDBCInfo getJDBCInfo(String fieldName, String fieldType) {
JDBCInfo ji = getdbJDBCInfo(rc.getJdbcType());
rc.override(ji);
- if (logger.isLoggable(Logger.FINEST)) {
- logger.finest("Leaving MappingPolicy.getJDBCInfo: " // NOI18N
- + fieldName + ", " + fieldType // NOI18N
- + " => " + rc); // NOI18N
- }
-
+ final JDBCInfo jdbcInfo = rc;
+ LOG.log(DEBUG, () -> "Leaving MappingPolicy.getJDBCInfo: " + fieldName + ", " + fieldType + " => " + jdbcInfo);
return rc;
}
@@ -832,7 +788,7 @@ public JDBCInfo getJDBCInfo(String fieldName, String fieldType) {
*/
private JDBCInfo getdbJDBCInfo(int jdbcType) {
String typename = getJdbcTypeName(jdbcType);
- return (JDBCInfo) dbJdbcInfoMap.get(typename);
+ return dbJdbcInfoMap.get(typename);
}
/**
@@ -841,13 +797,13 @@ private JDBCInfo getdbJDBCInfo(int jdbcType) {
* @return a JDBCInfo for the given fieldType
*/
private JDBCInfo getdbJDBCInfo(String fieldType) {
- JDBCInfo rc = (JDBCInfo) dbJdbcInfoMap.get(fieldType);
+ JDBCInfo rc = dbJdbcInfoMap.get(fieldType);
if (null == rc) {
// There is also nothing provided for the field's
// type, so use a BLOB.
- rc = (JDBCInfo) dbJdbcInfoMap.get("BLOB"); // NOI18N
+ rc = dbJdbcInfoMap.get("BLOB");
}
return rc;
}
@@ -860,7 +816,7 @@ private JDBCInfo getdbJDBCInfo(String fieldType) {
* jdbcTypeName is not that of a recognized JDBC type.
*/
static Integer getJdbcType(String jdbcTypeName) {
- return (Integer) jdbcTypes.get(jdbcTypeName.toUpperCase());
+ return jdbcTypes.get(jdbcTypeName.toUpperCase());
}
/**
@@ -954,7 +910,7 @@ public static String getOverrideForType(
*/
public static String getJdbcTypeName(int type) throws
IllegalArgumentException {
- String rc = (String) jdbcTypeNames.get(new Integer(type));
+ String rc = jdbcTypeNames.get(Integer.valueOf(type));
if (null == rc) {
throw new IllegalArgumentException();
}
@@ -1085,12 +1041,8 @@ public String getConstraintName(String relName, String uniqueId) {
}
rc = getUniqueGlobalName(rc, constraintNameMaxLength);
-
- if (logger.isLoggable(Logger.FINER)) {
- logger.finer("MappingPolicy.getConstraintName: " // NOI8N
- + relName + " -> " + rc); // NOI18N
- }
-
+ String constraintName = rc;
+ LOG.log(DEBUG, () -> "MappingPolicy.getConstraintName: " + relName + " -> " + constraintName);
return rc;
}
@@ -1185,12 +1137,12 @@ private String getUniqueName(String name, String namespace, int maxLen) {
rc += RESERVED_WORD_UNRESERVER;
}
- Set names = (Set) namespaces.get(namespace);
+ Set names = namespaces.get(namespace);
if (names == null) {
// Name is first entry in namespace, therefore already unique, no
// need to append counter.
- names = new HashSet();
+ names = new HashSet<>();
names.add(nameUpper);
namespaces.put(namespace, names);
@@ -1409,7 +1361,7 @@ private void setSqlFormatEntry(String name, String value) {
* @param value Value to be bound to that property.
*/
private void setJDBCInfoEntry(
- Map jdbcInfoMap, String name, String value, String indicator) {
+ Map jdbcInfoMap, String name, String value, String indicator) {
if (value != null) {
@@ -1421,7 +1373,7 @@ private void setJDBCInfoEntry(
fieldOrType = name.substring(0, i);
}
- JDBCInfo ji = (JDBCInfo) jdbcInfoMap.get(fieldOrType);
+ JDBCInfo ji = jdbcInfoMap.get(fieldOrType);
try {
if (null != ji) {
@@ -1432,11 +1384,7 @@ private void setJDBCInfoEntry(
jdbcInfoMap.put(fieldOrType, ji);
}
} catch (JDBCInfo.IllegalJDBCTypeException ex) {
- String msg = I18NHelper.getMessage(
- messages,
- "EXC_InvalidJDBCTypeName", // NOI18N
- value, fieldOrType);
- logger.log(Logger.SEVERE, msg);
+ String msg = I18NHelper.getMessage(messages, "EXC_InvalidJDBCTypeName", value, fieldOrType);
throw new IllegalArgumentException(msg);
}
}
@@ -1503,29 +1451,29 @@ private static String getPropertyFileName(String databaseType) {
@Override
public String toString() {
StringBuffer rc = new StringBuffer(
- "statementSeparator=" + statementSeparator // NOI18N
- + "\ncreateTableStart=" + createTableStart // NOI18N
- + "\ncreateTableEnd=" + createTableEnd // NOI18N
- + "\ncreateIndex=" + createIndex // NOI18N
- + "\ndropTable=" + dropTable // NOI18N
- + "\nalterTableAddConstraintStart=" + alterTableAddConstraintStart // NOI18N
- + "\nalterTableDropConstraint=" + alterTableDropConstraint // NOI18N
- + "\nprimaryKeyConstraint=" + primaryKeyConstraint // NOI18N
- + "\nforeignKeyConstraint=" + foreignKeyConstraint // NOI18N
- + "\ncolumnNullability=" + columnNullability // NOI18N
- + "\nlobLogging=" + lobLogging // NOI18N
- + "\ntableNameMaxLength=" + tableNameMaxLength // NOI18N
- + "\ncolumnNameMaxLength=" + columnNameMaxLength // NOI18N
- + "\nconstraintNameMaxLength=" + constraintNameMaxLength // NOI18N
- + "\nuniqueTableName=" + uniqueTableName // NOI18N
- + "\ncounter=" + counter // NOI18N
- + "\n\n"); // NOI18N
- rc.append(" dbJdbcInfoMap:\n").append(stringifyMap(dbJdbcInfoMap)); // NOI18N
- rc.append(" userJdbcInfoMap:\n").append(stringifyMap(userJdbcInfoMap)); // NOI18N
- rc.append(" sqlInfo:\n").append(stringifyMap(sqlInfo)); // NOI18N
- rc.append(" namingPolicy:\n").append(stringifyMap(namingPolicy)); // NOI18N
- rc.append(" namespaces:\n").append(stringifyMap(namespaces)); // NOI18N
- rc.append(" reservedWords:\n").append(stringifySet(reservedWords)); // NOI18N
+ "statementSeparator=" + statementSeparator
+ + "\ncreateTableStart=" + createTableStart
+ + "\ncreateTableEnd=" + createTableEnd
+ + "\ncreateIndex=" + createIndex
+ + "\ndropTable=" + dropTable
+ + "\nalterTableAddConstraintStart=" + alterTableAddConstraintStart
+ + "\nalterTableDropConstraint=" + alterTableDropConstraint
+ + "\nprimaryKeyConstraint=" + primaryKeyConstraint
+ + "\nforeignKeyConstraint=" + foreignKeyConstraint
+ + "\ncolumnNullability=" + columnNullability
+ + "\nlobLogging=" + lobLogging
+ + "\ntableNameMaxLength=" + tableNameMaxLength
+ + "\ncolumnNameMaxLength=" + columnNameMaxLength
+ + "\nconstraintNameMaxLength=" + constraintNameMaxLength
+ + "\nuniqueTableName=" + uniqueTableName
+ + "\ncounter=" + counter
+ + "\n\n");
+ rc.append(" dbJdbcInfoMap:\n").append(stringifyMap(dbJdbcInfoMap));
+ rc.append(" userJdbcInfoMap:\n").append(stringifyMap(userJdbcInfoMap));
+ rc.append(" sqlInfo:\n").append(stringifyMap(sqlInfo));
+ rc.append(" namingPolicy:\n").append(stringifyMap(namingPolicy));
+ rc.append(" namespaces:\n").append(stringifyMap(namespaces));
+ rc.append(" reservedWords:\n").append(stringifySet(reservedWords));
return rc.toString();
}
@@ -1539,8 +1487,8 @@ private String stringifyMap(Map m) {
StringBuffer rc = new StringBuffer();
for (Iterator i = m.entrySet().iterator(); i.hasNext();) {
Map.Entry e = (Map.Entry) i.next();
- rc.append(e.getKey()).append("=") // NOI18N
- .append(e.getValue()).append("\n"); // NOI18N
+ rc.append(e.getKey()).append("=")
+ .append(e.getValue()).append("\n");
}
return rc.toString();
}
@@ -1555,9 +1503,9 @@ private String stringifySet(Set s) {
StringBuffer rc = new StringBuffer();
int count = 0;
for (Iterator i = s.iterator(); i.hasNext();) {
- rc.append(i.next()).append(" "); // NOI18N
+ rc.append(i.next()).append(" ");
if (count++ > 6) {
- rc.append("\n"); // NOI18N
+ rc.append("\n");
count = 0;
}
}
diff --git a/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/PersistenceManager.java b/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/PersistenceManager.java
index 5390fd6c9c2..d749854afad 100644
--- a/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/PersistenceManager.java
+++ b/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/PersistenceManager.java
@@ -73,7 +73,7 @@ public interface PersistenceManager
* @param cls the Class of the candidate instances
* @return the new Query
*/
- Query newQuery(Class cls);
+ Query newQuery(Class> cls);
/** Create a new Query with the Class of the candidate instances and candidate Collection.
* specified.
@@ -81,7 +81,7 @@ public interface PersistenceManager
* @param cln the Collection of candidate instances
* @return the new Query
*/
- Query newQuery(Class cls,Collection cln);
+ Query newQuery(Class> cls, Collection> cln);
/** Create a new Query with the Class of the candidate instances and Filter.
* specified.
@@ -89,7 +89,7 @@ public interface PersistenceManager
* @param filter the Filter for candidate instances
* @return the new Query
*/
- Query newQuery (Class cls, String filter);
+ Query newQuery (Class> cls, String filter);
/** Create a new Query with the Class of the candidate instances, candidate Collection,
* and Filter.
@@ -98,7 +98,7 @@ public interface PersistenceManager
* @param filter the Filter for candidate instances
* @return the new Query
*/
- Query newQuery (Class cls, Collection cln, String filter);
+ Query newQuery (Class> cls, Collection> cln, String filter);
/** The PersistenceManager may manage a collection of instances in the data
* store based on the class of the instances. This method returns a
@@ -109,7 +109,7 @@ public interface PersistenceManager
* @return a Collection of instances
* @see Query
*/
- Collection getExtent(Class persistenceCapableClass,boolean subclasses);
+ Collection> getExtent(Class> persistenceCapableClass,boolean subclasses);
/** This method locates a persistent instance in the cache of instances
* managed by this PersistenceManager. If an instance with the same ObjectId
@@ -164,7 +164,7 @@ public interface PersistenceManager
* @param pcs a Collection of transient instances
* @see #makePersistent(Object pc)
*/
- void makePersistent (Collection pcs);
+ void makePersistent (Collection> pcs);
/** Delete the persistent instance from the data store.
* This method must be called in an active transaction.
@@ -190,7 +190,7 @@ public interface PersistenceManager
* @param pcs a Collection of persistent instances
* @see #deletePersistent(Object pc)
*/
- void deletePersistent (Collection pcs);
+ void deletePersistent (Collection> pcs);
/** This method returns the PersistenceManagerFactory used to create
* this PersistenceManager. It returns null if this instance was
@@ -231,7 +231,7 @@ public interface PersistenceManager
* @param cls the PersistenceCapable Class
* @return the Class of the ObjectId of the parameter
*/
- Class getObjectIdClass(Class cls);
+ Class> getObjectIdClass(Class> cls);
/**
@@ -245,7 +245,7 @@ public interface PersistenceManager
* @param fieldName the field to notify upon changes
* @return the object of the class type
*/
- Object newSCOInstance (Class type, Object owner, String fieldName);
+ Object newSCOInstance (Class> type, Object owner, String fieldName);
/**
@@ -264,8 +264,8 @@ public interface PersistenceManager
* @param initialSize initial size of the Collection
* @return the object of the class type
*/
- Object newCollectionInstance (Class type, Object owner, String fieldName,
- Class elementType, boolean allowNulls, int initialSize);
+ Object newCollectionInstance (Class> type, Object owner, String fieldName,
+ Class> elementType, boolean allowNulls, int initialSize);
/** This method locates a persistent instance in the cache of instances
diff --git a/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/Query.java b/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/Query.java
index 32229933398..a30724b3c9d 100644
--- a/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/Query.java
+++ b/appserver/persistence/cmp/internal-api/src/main/java/com/sun/jdo/api/persistence/support/Query.java
@@ -53,12 +53,12 @@ public interface Query extends java.io.Serializable
* put into the result Collection.
* @param cls the Class of the candidate instances.
*/
- void setClass(Class cls);
+ void setClass(Class> cls);
/** Set the candidate Collection to query.
* @param pcs the Candidate collection.
*/
- void setCandidates(Collection pcs);
+ void setCandidates(Collection> pcs);
/** Set the filter for the query.
*
@@ -174,7 +174,7 @@ public interface Query extends java.io.Serializable
* @see #executeWithArray (Object[] parameters)
* @param parameters the Map containing all of the parameters.
*/
- Object executeWithMap (Map parameters);
+ Object executeWithMap (Map parameters);
/** Execute the query and return the filtered Collection.
*
diff --git a/appserver/persistence/cmp/model/pom.xml b/appserver/persistence/cmp/model/pom.xml
index 5027244a21b..f89bb02668b 100644
--- a/appserver/persistence/cmp/model/pom.xml
+++ b/appserver/persistence/cmp/model/pom.xml
@@ -57,7 +57,7 @@
org.glassfish.external
- dbschema
+ dbschema-osgi
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Bundle.properties b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Bundle.properties
index 2ca9b0dc1fb..0dc5a31279a 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Bundle.properties
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Bundle.properties
@@ -68,7 +68,6 @@
file.cannot_save=JDO72000:Cannot save file for class {0}
file.incompatible_version=JDO72001:Incompatible mapping file version; please remap \
class {0}
-file.cannot_read=JDO72002:Cannot read mapping file for class {0}; exception is {1}
# RuntimeModel messages for class loader handling
# {0}=class name
@@ -549,5 +548,3 @@ Update the column mapping or choose a different version field.
#
# Please update this as necessary.
-# logging messages - not brandable for ejb context at this time
-model.parse_error=Errors during persistence validation
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/EnhancerModel.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/EnhancerModel.java
index ef9cdbf5336..ce67a27e92c 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/EnhancerModel.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/EnhancerModel.java
@@ -22,6 +22,7 @@
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.Field;
import java.util.List;
/**
@@ -49,6 +50,7 @@ class EnhancerModel extends Model {
* @return true if this class name represents an interface;
* false otherwise.
*/
+ @Override
public boolean isInterface (String className) {
throw new UnsupportedOperationException();
}
@@ -65,6 +67,7 @@ public boolean isInterface (String className) {
* @return the input stream for the specified resource, null
* if an error occurs or none exists
*/
+ @Override
protected BufferedInputStream getInputStreamForResource (String className,
ClassLoader classLoader, String resourceName)
{
@@ -91,6 +94,7 @@ protected BufferedInputStream getInputStreamForResource (String className,
* @return the top non-Object superclass for className,
* className if an error occurs or none exists
*/
+ @Override
protected String findPenultimateSuperclass (String className) {
debug("findPenultimateSuperclass(" + className + ")"); // NOI18N
throw new UnsupportedOperationException();
@@ -102,6 +106,7 @@ protected String findPenultimateSuperclass (String className) {
* @return the superclass for className, null if an error
* occurs or none exists
*/
+ @Override
protected String getSuperclass (String className) {
debug("getSuperclass (" + className + ")"); // NOI18N
return null; // "java.lang.Object"; // NOI18N
@@ -120,12 +125,13 @@ protected String getSuperclass (String className) {
*
* @exception IOException if there is some error creating the file
*/
- protected BufferedOutputStream createFile (String className, String baseFileName,
- String extension) throws IOException
- {
+ @Override
+ protected BufferedOutputStream createFile(String className, String baseFileName, String extension)
+ throws IOException {
throw new UnsupportedOperationException();
}
+
/**
* Deletes the file with the given file name which is parallel
* to the supplied class.
@@ -133,9 +139,8 @@ protected BufferedOutputStream createFile (String className, String baseFileName
* @param fileName the name of the file
* @exception IOException if there is some error deleting the file
*/
- protected void deleteFile (String className, String fileName)
- throws IOException
- {
+ @Override
+ protected void deleteFile(String className, String fileName) throws IOException {
throw new UnsupportedOperationException();
}
@@ -144,8 +149,8 @@ protected void deleteFile (String className, String fileName)
* @param classLoader the class loader used to check the class
* @return the class element for the specified className
*/
- public Object getClass (String className, ClassLoader classLoader)
- {
+ @Override
+ public Class> getClass(String className, ClassLoader classLoader) {
throw new UnsupportedOperationException();
}
@@ -159,9 +164,8 @@ public Object getClass (String className, ClassLoader classLoader)
* false otherwise.
* @see #getClass
*/
- public boolean implementsInterface (Object classElement,
- String interfaceName)
- {
+ @Override
+ public boolean implementsInterface(Object classElement, String interfaceName) {
throw new UnsupportedOperationException();
}
@@ -171,8 +175,8 @@ public boolean implementsInterface (Object classElement,
* false otherwise.
* @see #getClass
*/
- public boolean hasConstructor (String className)
- {
+ @Override
+ public boolean hasConstructor(String className) {
throw new UnsupportedOperationException();
}
@@ -186,8 +190,8 @@ public boolean hasConstructor (String className)
* @return the constructor element
* @see #getClass
*/
- public Object getConstructor (String className, String[] argTypeNames)
- {
+ @Override
+ public Object getConstructor(String className, String[] argTypeNames) {
throw new UnsupportedOperationException();
}
@@ -202,9 +206,8 @@ public Object getConstructor (String className, String[] argTypeNames)
* @return the method element
* @see #getClass
*/
- public Object getMethod (String className, String methodName,
- String[] argTypeNames)
- {
+ @Override
+ public Object getMethod(String className, String methodName, String[] argTypeNames) {
throw new UnsupportedOperationException();
}
@@ -219,8 +222,8 @@ public Object getMethod (String className, String methodName,
* @see #getField
* @see #getMethod
*/
- public String getType (Object element)
- {
+ @Override
+ public String getType(Object element) {
throw new UnsupportedOperationException();
}
@@ -230,7 +233,8 @@ public String getType (Object element)
* @param className the fully qualified name of the class to be checked
* @return the names of the field elements for the specified class
*/
- public List getFields (String className) {
+ @Override
+ public List getFields (String className) {
throw new UnsupportedOperationException();
}
@@ -242,7 +246,8 @@ public List getFields (String className) {
* @param fieldName the name of the field to be checked
* @return the field element for the specified fieldName
*/
- public Object getField (String className, String fieldName) {
+ @Override
+ public Field getField (String className, String fieldName) {
throw new UnsupportedOperationException();
}
@@ -257,8 +262,8 @@ public Object getField (String className, String fieldName) {
* false otherwise.
* @see #getField
*/
- public boolean isSerializable (Object fieldElement)
- {
+ @Override
+ public boolean isSerializable(Object fieldElement) {
throw new UnsupportedOperationException();
}
@@ -272,6 +277,7 @@ public boolean isSerializable (Object fieldElement)
* field; false otherwise.
* @see #getFieldType
*/
+ @Override
public boolean isArray (String className, String fieldName) {
throw new UnsupportedOperationException();
}
@@ -290,6 +296,7 @@ public boolean isArray (String className, String fieldName) {
* @see #getConstructor
* @see #getMethod
*/
+ @Override
public String getDeclaringClass (Object memberElement)
{
throw new UnsupportedOperationException();
@@ -308,6 +315,7 @@ public String getDeclaringClass (Object memberElement)
* @see #getConstructor
* @see #getMethod
*/
+ @Override
public int getModifiers (Object memberElement)
{
throw new UnsupportedOperationException();
@@ -322,6 +330,7 @@ public int getModifiers (Object memberElement)
* @return the PersistenceFieldElement for the specified field,
* null if an error occurs or none exists
*/
+ @Override
public PersistenceFieldElement getPersistenceField(String className,
String fieldName)
{
@@ -337,6 +346,7 @@ public PersistenceFieldElement getPersistenceField(String className,
* @return true if this field name represents a key field;
* false otherwise.
*/
+ @Override
public boolean isKey (String className, String fieldName)
{
PersistenceFieldElement field =
@@ -346,7 +356,8 @@ public boolean isKey (String className, String fieldName)
}
private void debug (Object o) {
- if (DEBUG)
+ if (DEBUG) {
System.out.println("EnhancerModel::" + o); // NOI18N
+ }
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Model.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Model.java
index 694b0919369..25e2142c0ef 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Model.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/Model.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * Model.java
- *
- * Created on March 9, 2000, 6:19 PM
- */
-
package com.sun.jdo.api.persistence.model;
import com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement;
@@ -31,13 +26,12 @@
import com.sun.jdo.api.persistence.model.mapping.MappingClassElement;
import com.sun.jdo.api.persistence.model.mapping.MappingFieldElement;
import com.sun.jdo.api.persistence.model.mapping.impl.MappingClassElementImpl;
-import com.sun.jdo.api.persistence.model.util.LogHelperModel;
+import com.sun.jdo.api.persistence.model.util.ModelValidationException;
import com.sun.jdo.api.persistence.model.util.ModelValidator;
import com.sun.jdo.spi.persistence.utility.JavaTypeHelper;
import com.sun.jdo.spi.persistence.utility.StringHelper;
import com.sun.jdo.spi.persistence.utility.WeakHashSet;
import com.sun.jdo.spi.persistence.utility.WeakValueHashMap;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -45,22 +39,24 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
+import java.lang.System.Logger;
+import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
-import java.util.Set;
import org.glassfish.persistence.common.I18NHelper;
import org.netbeans.modules.dbschema.SchemaElement;
import org.netbeans.modules.dbschema.migration.archiver.XMLInputStream;
import org.netbeans.modules.dbschema.migration.archiver.XMLOutputStream;
+import static java.lang.System.Logger.Level.WARNING;
+
/* TODO:
1. think about moving illegal lists of static info out to a properties file
2. think about throwing an exception or setting the declaring class/table
@@ -75,12 +71,11 @@ on add member in both models (jdo and mapping).
*/
/**
- *
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
-public abstract class Model
-{
+public abstract class Model {
+ private static final Logger LOG = System.getLogger(Model.class.getName());
+
/** Default instance of the model for use at runtime. */
public static final Model RUNTIME;
@@ -95,35 +90,35 @@ public abstract class Model
/** Map of mapping class elements which have been loaded. Keys are fully
* qualified class names.
*/
- private final Map _classes = new WeakValueHashMap();
+ private final WeakValueHashMap _classes = new WeakValueHashMap<>();
/** Set of fully qualified names of classes known to be
* non persistence-capable.
*/
- private final Set _nonPCClasses = new WeakHashSet();
+ private final WeakHashSet _nonPCClasses = new WeakHashSet<>();
/** List of illegal package name prefixes for superclasses of
* persistence capable classes.
*/
- private static List _illegalPrefixes;
+ private static List _illegalPrefixes;
/** List of illegal class names for superclasses of persistence capable
* classes.
*/
- private static List _illegalClasses;
+ private static List _illegalClasses;
/** List of class names for second class objects. */
- private static List _scoClasses;
+ private static List _scoClasses;
/** List of class names for mutable second class objects. */
- private static List _mutableScoClasses;
+ private static List _mutableScoClasses;
/** List of class names for collections. */
- private static List _collectionClasses;
+ private static List _collectionClasses;
/** I18N message base */
public static final String messageBase =
- "com.sun.jdo.api.persistence.model.Bundle"; // NOI18N
+ "com.sun.jdo.api.persistence.model.Bundle";
/** I18N message handler */
private static final ResourceBundle _messages = I18NHelper.loadBundle(
@@ -132,74 +127,78 @@ public abstract class Model
static
{
String prefixes[] =
- {"java.awt", "java.applet", "javax.swing", "jakarta.ejb"};// NOI18N
- String classes[] = {"java.lang.Throwable"}; // NOI18N
- String collectionClasses[] = { "java.util.Collection", // NOI18N
- "java.util.AbstractCollection", // NOI18N
- //"java.util.List", "java.util.AbstractList", // NOI18N
- "java.util.Set", "java.util.AbstractSet", // NOI18N
- //"java.util.ArrayList", "java.util.Vector", // NOI18N
- "java.util.HashSet", // NOI18N
- //"com.sun.jdo.spi.persistence.support.sqlstore.sco.ArrayList", // NOI18N
- //"com.sun.jdo.spi.persistence.support.sqlstore.sco.Vector", // NOI18N
- "com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet"}; // NOI18N
- String mutableScoClasses[] = {"java.util.Date", // NOI18N
- "com.sun.jdo.spi.persistence.support.sqlstore.sco.Date", "java.sql.Date",// NOI18N
- "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlDate", // NOI18N
- "java.sql.Time", "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlTime", // NOI18N
- "java.sql.Timestamp", // NOI18N
- "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlTimestamp"}; // NOI18N
- String scoClasses[] = {"java.lang.String", // NOI18N
- "java.lang.Character", "java.lang.Boolean", // NOI18N
- "java.lang.Long", "java.lang.Number", "java.lang.Byte", // NOI18N
- "java.lang.Short", "java.lang.Integer", "java.lang.Float", // NOI18N
- "java.lang.Double", "java.math.BigDecimal", // NOI18N
- "java.math.BigInteger"}; // NOI18N
+ {"java.awt", "java.applet", "javax.swing", "jakarta.ejb"};
+ String classes[] = {"java.lang.Throwable"};
+ String collectionClasses[] = { "java.util.Collection",
+ "java.util.AbstractCollection",
+ //"java.util.List", "java.util.AbstractList",
+ "java.util.Set", "java.util.AbstractSet",
+ //"java.util.ArrayList", "java.util.Vector",
+ "java.util.HashSet",
+ //"com.sun.jdo.spi.persistence.support.sqlstore.sco.ArrayList",
+ //"com.sun.jdo.spi.persistence.support.sqlstore.sco.Vector",
+ "com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet"};
+ String mutableScoClasses[] = {"java.util.Date",
+ "com.sun.jdo.spi.persistence.support.sqlstore.sco.Date", "java.sql.Date",
+ "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlDate",
+ "java.sql.Time", "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlTime",
+ "java.sql.Timestamp",
+ "com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlTimestamp"};
+ String scoClasses[] = {"java.lang.String",
+ "java.lang.Character", "java.lang.Boolean",
+ "java.lang.Long", "java.lang.Number", "java.lang.Byte",
+ "java.lang.Short", "java.lang.Integer", "java.lang.Float",
+ "java.lang.Double", "java.math.BigDecimal",
+ "java.math.BigInteger"};
_illegalPrefixes = Arrays.asList(prefixes);
_illegalClasses = Arrays.asList(classes);
_collectionClasses = Arrays.asList(collectionClasses);
- _mutableScoClasses = new ArrayList(Arrays.asList(mutableScoClasses));
+ _mutableScoClasses = new ArrayList<>(Arrays.asList(mutableScoClasses));
_mutableScoClasses.addAll(_collectionClasses);
- _scoClasses = new ArrayList(Arrays.asList(scoClasses));
+ _scoClasses = new ArrayList<>(Arrays.asList(scoClasses));
_scoClasses.addAll(_mutableScoClasses);
// always load the runtime model
- RUNTIME = NewModel(null, "com.sun.jdo.api.persistence.model.RuntimeModel"); //NOI18N
+ RUNTIME = NewModel(null, "com.sun.jdo.api.persistence.model.RuntimeModel");
// always load the enhancer model
- ENHANCER = NewModel(null, "com.sun.jdo.api.persistence.model.EnhancerModel"); //NOI18N
- }
-
- /** Create a new Model of the requested type. If the class definition
- * exists in the class path of the environment, then this method will
- * create a new instance of the Model.
- * @param modelName the fully qualified name of the class to be
- * instantiated.
- * @param testName the fully qualified name of the class to be tested
- * as a precondition to loading.
- * @return a new instance of the requested class (which implements
- * Model).
- */
- static protected Model NewModel (String testName, String modelName) {
- Class DynamicClass = null;
- Model model = null;
- try {
- if (testName != null)
- // try this class as a precondition to the real class to load
- Class.forName (testName);
- DynamicClass = Class.forName (modelName);
- if (DynamicClass != null)
- model = (Model) DynamicClass.newInstance();
+ ENHANCER = NewModel(null, "com.sun.jdo.api.persistence.model.EnhancerModel");
+ }
+
+ /**
+ * Create a new Model of the requested type. If the class definition
+ * exists in the class path of the environment, then this method will
+ * create a new instance of the Model.
+ *
+ * @param modelName the fully qualified name of the class to be
+ * instantiated.
+ * @param testName the fully qualified name of the class to be tested
+ * as a precondition to loading.
+ * @return a new instance of the requested class (which implements
+ * Model).
+ */
+ private static Model NewModel(String testName, String modelName) {
+ try {
+ if (testName != null) {
+ // try this class as a precondition to the real class to load
+ Class.forName(testName);
}
- catch (Exception e) {
- // this is expected in the environment
+ @SuppressWarnings("unchecked")
+ Class extends Model> dynamicClass = (Class extends Model>) Class.forName(modelName);
+ if (dynamicClass != null) {
+ return dynamicClass.getDeclaredConstructor().newInstance();
}
- return model;
+ } catch (Exception e) {
+ // this is expected in the environment
}
- /** @return I18N message handler for this element
+ return null;
+ }
+
+
+ /**
+ * @return I18N message handler for this element
*/
- protected static final ResourceBundle getMessages ()
- {
+ protected static final ResourceBundle getMessages() {
return _messages;
}
@@ -212,7 +211,7 @@ protected static final ResourceBundle getMessages ()
* @return the input stream for the specified resource, null
* if an error occurs or none exists
*/
- abstract protected BufferedInputStream getInputStreamForResource (
+ protected abstract BufferedInputStream getInputStreamForResource (
String className, ClassLoader classLoader, String resourceName);
/** Determines if the specified className represents an interface type.
@@ -220,7 +219,7 @@ abstract protected BufferedInputStream getInputStreamForResource (
* @return true if this class name represents an interface;
* false otherwise.
*/
- abstract public boolean isInterface (String className);
+ public abstract boolean isInterface (String className);
/** Determines if the specified className has a persistent superclass.
* @param className the fully qualified name of the class to be checked
@@ -232,8 +231,9 @@ public boolean hasPersistentSuperclass (String className)
{
while ((className = getSuperclass(className)) != null)
{
- if (isPersistent(className))
+ if (isPersistent(className)) {
return true;
+ }
}
return false;
@@ -245,14 +245,14 @@ public boolean hasPersistentSuperclass (String className)
* @return the top non-Object superclass for className,
* className if an error occurs or none exists
*/
- abstract protected String findPenultimateSuperclass (String className);
+ protected abstract String findPenultimateSuperclass (String className);
/** Returns the name of the superclass for the given class name.
* @param className the fully qualified name of the class to be checked
* @return thesuperclass for className, null if an error
* occurs or none exists
*/
- abstract protected String getSuperclass (String className);
+ protected abstract String getSuperclass (String className);
/** Returns a PersistenceClassElement created from the specified class name.
* Since our implementation of the mapping model class includes the
@@ -280,24 +280,22 @@ public PersistenceClassElement getPersistenceClass (String className)
* null if an error occurs or none exists
* @see #getMappingClass
*/
- public PersistenceClassElement getPersistenceClass (String className,
- ClassLoader classLoader)
- {
+ public PersistenceClassElement getPersistenceClass(String className, ClassLoader classLoader) {
return getPersistenceClass(getMappingClass(className, classLoader));
}
- /** Returns a PersistenceClassElement created from the mapping class.
+
+ /**
+ * Returns a PersistenceClassElement created from the mapping class.
+ *
* @param mappingClass the mapping class element to which the persistence
- * class is associated
+ * class is associated
* @return the PersistenceClassElement for mappingClass,
- * null if an error occurs or none exists
+ * null if an error occurs or none exists
* @see #getMappingClass
*/
- protected PersistenceClassElement getPersistenceClass (
- MappingClassElement mappingClass)
- {
- return ((mappingClass == null) ? null :
- ((MappingClassElementImpl)mappingClass).getPersistenceElement());
+ protected PersistenceClassElement getPersistenceClass(MappingClassElement mappingClass) {
+ return ((mappingClass == null) ? null : ((MappingClassElementImpl) mappingClass).getPersistenceElement());
}
/** Returns the MappingClassElement created for the specified class name.
@@ -307,8 +305,7 @@ protected PersistenceClassElement getPersistenceClass (
* @return the MappingClassElement for class,
* null if an error occurs or none exists
*/
- public MappingClassElement getMappingClass (String className)
- {
+ public MappingClassElement getMappingClass(String className) {
return getMappingClass(className, null);
}
@@ -321,9 +318,7 @@ public MappingClassElement getMappingClass (String className)
* null if an error occurs or none exists
* @see MappingClassElementImpl#forName
*/
- public MappingClassElement getMappingClass (String className,
- ClassLoader classLoader)
- {
+ public MappingClassElement getMappingClass(String className, ClassLoader classLoader) {
// This method synchronizes the access of the _classes cache,
// rather than using a synchronized map. This is for optimization only.
// Otherwise two parallel calls would read the mapping file twice,
@@ -331,34 +326,27 @@ public MappingClassElement getMappingClass (String className,
// the first in the cache.
// Any other access of _classes potentially needs to be synchronized
// using the same variable _classes (e.g. updateKeyForClass).
- synchronized (this._classes)
- {
- MappingClassElement mappingClass =
- (MappingClassElement)_classes.get(className);
+ synchronized (this._classes) {
+ MappingClassElement mappingClass = _classes.get(className);
- if (mappingClass == null)
- {
+ if (mappingClass == null) {
// check whether the class is known to be non PC
- if (_nonPCClasses.contains(className))
+ if (_nonPCClasses.contains(className)) {
return null;
+ }
- try
- {
- InputStream stream = getInputStreamForResource(className,
- classLoader, getResourceNameWithExtension(className));
+ try {
+ InputStream stream = getInputStreamForResource(className, classLoader,
+ getResourceNameWithExtension(className));
- if (stream != null)
- {
+ if (stream != null) {
// if the file is empty, the archiver prints an
// exception, so protect against that case and
// return null without updating either cache
- if (stream.available() > 0)
- {
- XMLInputStream xmlInput = new XMLInputStream(stream,
- getClass().getClassLoader());
+ if (stream.available() > 0) {
+ XMLInputStream xmlInput = new XMLInputStream(stream, getClass().getClassLoader());
- mappingClass =
- (MappingClassElement)xmlInput.readObject();
+ mappingClass = (MappingClassElement) xmlInput.readObject();
xmlInput.close();
// postUnarchive performs version number checking
@@ -374,53 +362,36 @@ public MappingClassElement getMappingClass (String className,
// persistence classes since the xml archiver uses
// all the set methods
mappingClass.setModified(false);
- getPersistenceClass(mappingClass).
- setModified(false);
+ getPersistenceClass(mappingClass).setModified(false);
}
- }
- else
- {
+ } else {
// stream is null, mapping file does not exist =>
// class is not PC, so store the class name in the
// set of classes known to be non PC
_nonPCClasses.add(className);
}
- }
- catch (ModelException e)
- {
+ } catch (ModelException e) {
// MBO: print reason to logger
- LogHelperModel.getLogger().log(Logger.WARNING,
- e.getMessage());
+ LOG.log(WARNING, "Cannot read mapping file for class " + className, e);
return null;
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
// MBO: print reason to logger
- LogHelperModel.getLogger().log(Logger.WARNING,
- I18NHelper.getMessage(getMessages(),
- "file.cannot_read", className, e.toString())); //NOI18N
- } // will return null
+ LOG.log(WARNING, "Cannot read mapping file for class " + className, e);
+ } // will return null
}
return mappingClass;
}
}
- /** Returns an unmodifiable copy of the MappingClassElement cache.
- * @return unmodifiable MappingClassElement cache
- */
- public Map getMappingCache ()
- {
- return Collections.unmodifiableMap(_classes);
- }
-
- /** Returns an unmodifiable copy of the ClassLoader cache.
+ /**
+ * Returns an unmodifiable copy of the ClassLoader cache.
* This implementation returns null, but subclasses (such as RuntimeModel)
* can override this method if they support a class loader cache.
+ *
* @return unmodifiable ClassLoader cache
*/
- public Map getClassLoaderCache ()
- {
+ public Map getClassLoaderCache() {
return null;
}
@@ -444,24 +415,21 @@ public void removeResourcesFromCaches (ClassLoader classLoader)
* will determine the status of the classes.
* @param classNames a collection of fully qualified class names
*/
- protected void removeResourcesFromCaches (Collection classNames)
- {
- if (classNames == null)
+ protected void removeResourcesFromCaches(Collection classNames) {
+ if (classNames == null) {
return;
+ }
- synchronized (this._classes)
- {
- for (Iterator i = classNames.iterator(); i.hasNext();)
- {
- String className = (String)i.next();
- MappingClassElement mapping =
- (MappingClassElement)_classes.get(className);
+ synchronized (this._classes) {
+ for (String className : classNames) {
+ MappingClassElement mapping = _classes.get(className);
// If the cache has a MappingClassElement with the specified
// className, get its databaseRoot and remove the corresonding
// SchemaElement from the SchemaElement cache.
- if (mapping != null)
+ if (mapping != null) {
SchemaElement.removeFromCache(mapping.getDatabaseRoot());
+ }
// remove the corresponding MappingClassElement from cache
_classes.remove(className);
@@ -477,10 +445,8 @@ protected void removeResourcesFromCaches (Collection classNames)
* The next call getMappingClass will determine the status of the class.
* @param className the fully qualified name of the class
*/
- public void removeFromCache (String className)
- {
- synchronized (this._classes)
- {
+ public void removeFromCache(String className) {
+ synchronized (this._classes) {
// remove the class from the set of classes known to be non PC
_nonPCClasses.remove(className);
}
@@ -493,77 +459,66 @@ public void removeFromCache (String className)
* @exception IOException if there is some error saving the class
* @see #createFile
*/
- public void storeMappingClass (MappingClassElement mappingClass)
- throws IOException
- {
- if (mappingClass != null)
- {
+ public void storeMappingClass(MappingClassElement mappingClass) throws IOException {
+ if (mappingClass != null) {
String className = mappingClass.getName();
- OutputStream stream = ((className == null) ? null :
- createFile(className, getFileName(className),
- MappingClassElement.MAPPING_EXTENSION));
+ OutputStream stream = ((className == null) ? null
+ : createFile(className, getFileName(className), MappingClassElement.MAPPING_EXTENSION));
storeMappingClass(mappingClass, stream);
}
}
- /** Stores the supplied MappingClassElement to an xml file in the
- * specified output stream. The caller is responsible for updating
+
+ /**
+ * Stores the supplied MappingClassElement to an xml file in the
+ * specified output stream. The caller is responsible for updating
* the cache by calling updateKeyForClass, if necessary.
+ *
* @param mappingClass the mapping class to be saved
* @param stream the output stream
* @exception IOException if there is some error saving the class
* @see #createFile
*/
- public void storeMappingClass (MappingClassElement mappingClass,
- OutputStream stream) throws IOException
- {
- if (mappingClass != null)
- {
- String className = mappingClass.getName();
-
- if (stream != null)
- {
- XMLOutputStream xmlOutput = new XMLOutputStream(stream);
-
- try
- {
- mappingClass.preArchive(); // call pre archive hook
- xmlOutput.writeObject(mappingClass);
-
- // update modified flags for the mapping and persistence
- // classes after save
- mappingClass.setModified(false);
- getPersistenceClass(mappingClass).setModified(false);
- }
- catch (ModelException e)
- {
- // MBO: print reason to logger
- LogHelperModel.getLogger().log(Logger.WARNING,
- e.getMessage());
- }
- finally
- {
- if (xmlOutput != null)
- xmlOutput.close();
+ public void storeMappingClass(MappingClassElement mappingClass, OutputStream stream) throws IOException {
+ if (mappingClass == null) {
+ return;
+ }
+ String className = mappingClass.getName();
- unlockFile(stream, className);
- }
- return;
+ if (stream == null) {
+ throw new IOException(I18NHelper.getMessage(getMessages(), "file.cannot_save", className));
+ }
+ XMLOutputStream xmlOutput = new XMLOutputStream(stream);
+
+ try {
+ mappingClass.preArchive(); // call pre archive hook
+ xmlOutput.writeObject(mappingClass);
+
+ // update modified flags for the mapping and persistence
+ // classes after save
+ mappingClass.setModified(false);
+ getPersistenceClass(mappingClass).setModified(false);
+ } catch (ModelException e) {
+ // MBO: print reason to logger
+ LOG.log(WARNING, "Failed to store mapping class " + mappingClass, e);
+ } finally {
+ if (xmlOutput != null) {
+ xmlOutput.close();
}
- throw new IOException(I18NHelper.getMessage(getMessages(),
- "file.cannot_save", className)); // NOI18N
+ unlockFile(stream, className);
}
+ return;
}
- public void unlockFile (OutputStream stream, String className)
- throws IOException
- {
+
+ public void unlockFile(OutputStream stream, String className) throws IOException {
unlockFile(className);
- if (stream != null)
+ if (stream != null) {
stream.close();
+ }
}
// overridden in DevelopmentModel
@@ -579,13 +534,11 @@ public void unlockFile (String className) {}
* @exception IOException if there is some error saving the class
* @see #storeMappingClass
*/
- public void storeMappingClass (String className) throws IOException
- {
+ public void storeMappingClass(String className) throws IOException {
MappingClassElement mappingClass = null;
- synchronized (this._classes)
- {
- mappingClass = (MappingClassElement)_classes.get(className);
+ synchronized (this._classes) {
+ mappingClass = _classes.get(className);
}
storeMappingClass(mappingClass);
}
@@ -598,20 +551,17 @@ public void storeMappingClass (String className) throws IOException
* @param oldName the fully qualified name of the old key for the mapping
* class (use null to add the new key but not replace it)
*/
- public void updateKeyForClass (MappingClassElement mappingClass,
- String oldName)
- {
+ public void updateKeyForClass(MappingClassElement mappingClass, String oldName) {
// need to synchronize _classes access here
// (for details see getMappingClass)
- synchronized (this._classes)
- {
+ synchronized (this._classes) {
// remove the old key from the cache
- if (oldName != null)
+ if (oldName != null) {
_classes.remove(oldName);
+ }
// store the class under the new key in the cache
- if (mappingClass != null)
- {
+ if (mappingClass != null) {
String className = mappingClass.getName();
_classes.put(className, mappingClass);
@@ -663,31 +613,30 @@ public boolean isPersistent (String className, ClassLoader classLoader)
* @see #isInterface
* @see #findPenultimateSuperclass
*/
- public boolean isPersistenceCapableAllowed (String className)
- {
+ public boolean isPersistenceCapableAllowed(String className) {
int modifier = getModifiersForClass(className);
- if (!Modifier.isStatic(modifier) && !Modifier.isAbstract(modifier) &&
- !isInterface(className) && !hasPersistentSuperclass(className))
- {
+ if (!Modifier
+ .isStatic(modifier) && !Modifier.isAbstract(modifier) && !isInterface(className)
+ && !hasPersistentSuperclass(className)) {
String highestSuperclassName = findPenultimateSuperclass(className);
- Iterator iterator = _illegalPrefixes.iterator();
+ Iterator iterator = _illegalPrefixes.iterator();
- while (iterator.hasNext())
- {
+ while (iterator.hasNext()) {
String nextPrefix = iterator.next().toString();
- if (highestSuperclassName.startsWith(nextPrefix))
+ if (highestSuperclassName.startsWith(nextPrefix)) {
return false;
+ }
}
iterator = _illegalClasses.iterator();
- while (iterator.hasNext())
- {
+ while (iterator.hasNext()) {
String nextClass = iterator.next().toString();
- if (highestSuperclassName.equals(nextClass))
+ if (highestSuperclassName.equals(nextClass)) {
return false;
+ }
}
return true;
@@ -696,17 +645,18 @@ public boolean isPersistenceCapableAllowed (String className)
return false;
}
- /** Computes the mapping file resource name (with extension) for the
+
+ /**
+ * Computes the mapping file resource name (with extension) for the
* supplied class name by converting the package name to a resource name.
+ *
* @param className the fully qualified name of the class
* @return the mapping file resource name (with extension) for the supplied
- * class name
+ * class name
* @see MappingClassElement#MAPPING_EXTENSION
*/
- protected String getResourceNameWithExtension (String className)
- {
- return getResourceName(className) + "." + // NOI18N
- MappingClassElement.MAPPING_EXTENSION;
+ protected String getResourceNameWithExtension(String className) {
+ return getResourceName(className) + "." + MappingClassElement.MAPPING_EXTENSION;
}
/** Computes the base resource name (without extension) for the supplied
@@ -715,8 +665,7 @@ protected String getResourceNameWithExtension (String className)
* @return the base resource name (without extension) for the supplied
* class name
*/
- protected String getResourceName (String className)
- {
+ protected String getResourceName(String className) {
return ((className != null) ?
className.replace('.', '/') : null);
}
@@ -729,10 +678,8 @@ protected String getResourceName (String className)
* @see #getFileName
* @see MappingClassElement#MAPPING_EXTENSION
*/
- protected String getFileNameWithExtension (String className)
- {
- return getFileName(className) + "." + // NOI18N
- MappingClassElement.MAPPING_EXTENSION;
+ protected String getFileNameWithExtension(String className) {
+ return getFileName(className) + "." + MappingClassElement.MAPPING_EXTENSION;
}
/** Computes the base file name (without extension) for the supplied
@@ -741,71 +688,63 @@ protected String getFileNameWithExtension (String className)
* @return the base file name (without extension) for the supplied
* class name
*/
- protected String getFileName (String className)
- {
- return ((className != null) ?
- className.replace('.', File.separatorChar) : null);
+ protected String getFileName(String className) {
+ return ((className != null) ? className.replace('.', File.separatorChar) : null);
}
- /** Converts the class with the supplied name to or from persistence
+
+ /**
+ * Converts the class with the supplied name to or from persistence
* capable depending on the flag.
+ *
* @param className the fully qualified name of the class
* @param flag if true, convert this class to be
- * persistence capable, if false, convert this class
- * to be non-persistence capable
+ * persistence capable, if false, convert this class
+ * to be non-persistence capable
* @exception IOException if there is some error converting the class
*/
- public void convertToPersistenceCapable (String className,
- boolean flag) throws IOException
- {
+ public void convertToPersistenceCapable(String className, boolean flag) throws IOException {
boolean classIsPersistent = isPersistent(className);
Exception conversionException = null;
- if (flag && !classIsPersistent &&
- isPersistenceCapableAllowed(className))
- {
- try
- {
+ if (flag && !classIsPersistent && isPersistenceCapableAllowed(className)) {
+ try {
// this calls updateKeyForClass which updates
// the mapping cache and the set of classes known to be non PC
createSkeletonMappingClass(className);
- }
- catch (Exception e)
- {
+ } catch (Exception e) {
// need to unconvert whatever partial conversion succeeded
conversionException = e;
}
}
- if ((!flag && classIsPersistent) || (conversionException != null))
- {
- try
- {
+ if ((!flag && classIsPersistent) || (conversionException != null)) {
+ try {
// delete the mapping file
deleteFile(className, getFileNameWithExtension(className));
- synchronized (this._classes)
- {
+ synchronized (this._classes) {
// remove the corresponding MappingClassElement from cache
_classes.remove(className);
// put the class in the set of classes known to be non PC
_nonPCClasses.add(className);
}
- }
- catch (Exception e) // rethrow if not a problem during unconvert
- {
- if (conversionException == null)
+ } catch (Exception e) {
+ // rethrow if not a problem during unconvert
+ if (conversionException == null) {
conversionException = e;
+ }
}
}
- if (conversionException != null) // rethrow the exception
+ if (conversionException != null) // rethrow the exception
{
- if (conversionException instanceof RuntimeException)
- throw (RuntimeException)conversionException;
- else if (conversionException instanceof IOException)
- throw (IOException)conversionException;
+ if (conversionException instanceof RuntimeException) {
+ throw (RuntimeException) conversionException;
+ } else if (conversionException instanceof IOException) {
+ throw (IOException) conversionException;
+ }
}
}
@@ -814,9 +753,7 @@ else if (conversionException instanceof IOException)
* @param className the fully qualified name of the class
* @exception IOException if there is some error storing the class
*/
- public void convertToPersistenceCapable (String className)
- throws IOException
- {
+ public void convertToPersistenceCapable(String className) throws IOException {
convertToPersistenceCapable(className, true);
convertDefaultFields(className);
storeMappingClass(className);
@@ -829,11 +766,8 @@ public void convertToPersistenceCapable (String className)
* @see #convertDefaultFields
* @see #updateKeyForClass
*/
- private void createSkeletonMappingClass (String className)
- {
- PersistenceClassElement element = new PersistenceClassElement(
- new PersistenceClassElementImpl(className));
-
+ private void createSkeletonMappingClass(String className) {
+ PersistenceClassElement element = new PersistenceClassElement(new PersistenceClassElementImpl(className));
updateKeyForClass(new MappingClassElementImpl(element), null);
}
@@ -844,8 +778,7 @@ private void createSkeletonMappingClass (String className)
* @see #createSkeletonMappingClass
* @see #convertFields
*/
- public void convertDefaultFields (String className)
- {
+ public void convertDefaultFields(String className) {
convertFields(className, getFields(className));
}
@@ -855,88 +788,58 @@ public void convertDefaultFields (String className)
* @param fields a list of (short) field names
* @see #convertDefaultFields
*/
- public void convertFields (String className, List fields)
- {
+ public void convertFields(String className, List fields) {
PersistenceClassElement element = getPersistenceClass(className);
- if (element != null)
- {
- Iterator iterator = fields.iterator();
+ if (element != null) {
+ Iterator iterator = fields.iterator();
// iterate the list of fields and create corresponding
// PersistenceFieldElements (& RelationshipElements)
- while (iterator.hasNext())
- {
- String fieldName = (String)iterator.next();
+ while (iterator.hasNext()) {
+ String fieldName = iterator.next();
- if (isPersistentAllowed(className, fieldName) &&
- shouldBePersistent(className, fieldName))
- {
+ if (isPersistentAllowed(className, fieldName) && shouldBePersistent(className, fieldName)) {
addFieldElement(element, fieldName);
}
}
-
- /* comment out -- not supporting concurrency groups for beta
- // add everything to one concurrency group by default
- PersistenceFieldElement[] persistentFields = element.getFields();
- if ((persistentFields != null) && (persistentFields.length > 0))
- {
- String defaultGroupName = I18NHelper.getMessage(getMessages(),
- "jdo.concurrency_group.default");
- ConcurrencyGroupElement group = new ConcurrencyGroupElement(
- new ConcurrencyGroupElementImpl(defaultGroupName), element);
-
- try
- {
- group.addFields(persistentFields);
- element.addConcurrencyGroup(group);
- }
- catch (ModelException e)
- {} // just don't add this group
- }*/
}
}
- /** Adds a PersistenceFieldElement for the specified field to the
+
+ /**
+ * Adds a PersistenceFieldElement for the specified field to the
* supplied PersistenceClassElement, creating a RelationshipElement if
* necessary.
+ *
* @param element the persistence class element to be used
* @param fieldName the name of the field to be added
*/
- public boolean addFieldElement (PersistenceClassElement element,
- String fieldName)
- {
+ public boolean addFieldElement(PersistenceClassElement element, String fieldName) {
String fieldType = getFieldType(element.getName(), fieldName);
boolean isCollection = isCollection(fieldType);
- try
- {
+ try {
// check if should be relationship here
- if (isPersistent(fieldType) || isCollection)
- {
- RelationshipElement relationship = new RelationshipElement(
- new RelationshipElementImpl(fieldName), element);
+ if (isPersistent(fieldType) || isCollection) {
+ RelationshipElement relationship = new RelationshipElement(new RelationshipElementImpl(fieldName),
+ element);
- if (isCollection)
- {
- relationship.setCollectionClass(
- getDefaultCollectionClass(fieldType));
- }
- else // set upper bound = 1 (jdo model should really do this)
+ if (isCollection) {
+ relationship.setCollectionClass(getDefaultCollectionClass(fieldType));
+ } else { // set upper bound = 1 (jdo model should really do this)
relationship.setUpperBound(1);
+ }
element.addField(relationship);
- }
- else
- {
- element.addField(new PersistenceFieldElement(new
- PersistenceFieldElementImpl(fieldName), element));
+ } else {
+ element.addField(new PersistenceFieldElement(new PersistenceFieldElementImpl(fieldName), element));
}
return true;
+ } catch (ModelException e) {
+ // will return false
}
- catch (ModelException e)
- {} // will return false
return false;
}
@@ -977,17 +880,11 @@ public void removeFieldElement (PersistenceFieldElement element)
* @param element the relationship element to be examined
* @return the name of the related class
*/
- public String getRelatedClass (RelationshipElement element)
- {
- if (element != null)
- {
- String fieldType = getFieldType(
- element.getDeclaringClass().getName(), element.getName());
- String relatedClass = (isCollection(fieldType) ?
- element.getElementClass() : fieldType);
-
- return (StringHelper.isEmpty(relatedClass) ? null :
- relatedClass.trim());
+ public String getRelatedClass(RelationshipElement element) {
+ if (element != null) {
+ String fieldType = getFieldType(element.getDeclaringClass().getName(), element.getName());
+ String relatedClass = (isCollection(fieldType) ? element.getElementClass() : fieldType);
+ return StringHelper.isEmpty(relatedClass) ? null : relatedClass.trim();
}
return null;
@@ -1001,28 +898,9 @@ public String getRelatedClass (RelationshipElement element)
* @see #getFieldType
* @see #getDefaultCollectionClass
*/
- public ArrayList getSupportedCollectionClasses (String className)
- {
- String supportedSet = "java.util.HashSet"; // NOI18N
- // String supportedList = "java.util.ArrayList"; // NOI18N
- // String supportedVector = "java.util.Vector"; // NOI18N
- ArrayList returnList = new ArrayList();
-
- // for dogwood, only support sets
- returnList.add(supportedSet);
- /* if (className.indexOf("Collection") != -1) // NOI18N
- {
- returnList.add(supportedSet);
- returnList.add(supportedList);
- returnList.add(supportedVector);
- }
- else if (className.indexOf("List") != -1) // NOI18N
- returnList.add(supportedList);
- else if (className.indexOf("Set") != -1) // NOI18N
- returnList.add(supportedSet);
- else if (supportedVector.equals(className))
- returnList.add(supportedVector);
- */
+ public List getSupportedCollectionClasses(String className) {
+ ArrayList returnList = new ArrayList<>();
+ returnList.add("java.util.HashSet");
return returnList;
}
@@ -1035,19 +913,11 @@ else if (supportedVector.equals(className))
* @see #getFieldType
* @see #getSupportedCollectionClasses
*/
- public String getDefaultCollectionClass (String className)
- {
- String collectionClass = "java.util.HashSet"; // NOI18N
-
- // for dogwood, only support sets
- /* if (className.indexOf("List") != -1) // NOI18N
- collectionClass = "java.util.ArrayList"; // NOI18N
- else if ("java.util.Vector".equals(className)) // NOI18N
- collectionClass = className;
- */
- return collectionClass;
+ public String getDefaultCollectionClass(String className) {
+ return "java.util.HashSet";
}
+
/** Creates a file with the given base file name and extension
* parallel to the supplied class (if it does not yet exist).
* @param className the fully qualified name of the class
@@ -1057,7 +927,7 @@ else if ("java.util.Vector".equals(className)) // NOI18N
* if an error occurs or none exists
* @exception IOException if there is some error creating the file
*/
- abstract protected BufferedOutputStream createFile (String className,
+ protected abstract BufferedOutputStream createFile (String className,
String baseFileName, String extension) throws IOException;
/** Deletes the file with the given file name which is parallel
@@ -1066,7 +936,7 @@ abstract protected BufferedOutputStream createFile (String className,
* @param fileName the name of the file
* @exception IOException if there is some error deleting the file
*/
- abstract protected void deleteFile (String className, String fileName)
+ protected abstract void deleteFile (String className, String fileName)
throws IOException;
/** Returns a list of names of all the declared field elements in the
@@ -1074,7 +944,7 @@ abstract protected void deleteFile (String className, String fileName)
* @param className the fully qualified name of the class to be checked
* @return the names of the field elements for the specified class
*/
- abstract public List getFields (String className);
+ public abstract List getFields(String className);
/** Returns a list of names of all the field elements in the
* class with the specified name. This list includes the inherited
@@ -1082,12 +952,10 @@ abstract protected void deleteFile (String className, String fileName)
* @param className the fully qualified name of the class to be checked
* @return the names of the field elements for the specified class
*/
- public List getAllFields (String className)
- {
- List returnList = new ArrayList();
+ public List getAllFields(String className) {
+ List returnList = new ArrayList<>();
- while (className != null)
- {
+ while (className != null) {
returnList.addAll(getFields(className));
className = getSuperclass(className);
}
@@ -1099,25 +967,27 @@ public List getAllFields (String className)
* @param className the fully qualified name of the class to be checked
* @return the class element for the specified className
*/
- public Object getClass (String className)
- {
+ public Class> getClass(String className) {
return getClass(className, null);
}
- /** Returns the class element with the specified className.
+ /**
+ * Returns the class element with the specified className.
+ *
* @param className the fully qualified name of the class to be checked
* @param classLoader the class loader used to find mapping information
* @return the class element for the specified className
*/
- abstract public Object getClass (String className, ClassLoader classLoader);
+ public abstract Class> getClass(String className, ClassLoader classLoader);
- /** Determines if a class with the specified className exists.
+ /**
+ * Determines if a class with the specified className exists.
+ *
* @param className the fully qualified name of the class to be checked
* @return true if this class name represents a valid
- * class; false otherwise.
+ * class; false otherwise.
*/
- public boolean hasClass (String className)
- {
+ public boolean hasClass(String className) {
return hasClass(className, null);
}
@@ -1127,9 +997,8 @@ public boolean hasClass (String className)
* @return true if this class name represents a valid
* class; false otherwise.
*/
- public boolean hasClass (String className, ClassLoader classLoader)
- {
- return (getClass(className, classLoader) != null);
+ public boolean hasClass(String className, ClassLoader classLoader) {
+ return getClass(className, classLoader) != null;
}
/** Determines if the specified class implements the specified interface.
@@ -1142,7 +1011,7 @@ public boolean hasClass (String className, ClassLoader classLoader)
* false otherwise.
* @see #getClass
*/
- abstract public boolean implementsInterface (Object classElement,
+ public abstract boolean implementsInterface (Object classElement,
String interfaceName);
/** Determines if the class with the specified name declares a constructor.
@@ -1151,7 +1020,7 @@ abstract public boolean implementsInterface (Object classElement,
* false otherwise.
* @see #getClass
*/
- abstract public boolean hasConstructor (String className);
+ public abstract boolean hasConstructor (String className);
/** Returns the constructor element for the specified argument types
* in the class with the specified name. Types are specified as type
@@ -1163,8 +1032,7 @@ abstract public boolean implementsInterface (Object classElement,
* @return the constructor element
* @see #getClass
*/
- abstract public Object getConstructor (String className,
- String[] argTypeNames);
+ public abstract Object getConstructor(String className, String[] argTypeNames);
/** Returns the method element for the specified method name and argument
* types in the class with the specified name. Types are specified as
@@ -1177,8 +1045,7 @@ abstract public Object getConstructor (String className,
* @return the method element
* @see #getClass
*/
- abstract public Object getMethod (String className, String methodName,
- String[] argTypeNames);
+ public abstract Object getMethod(String className, String methodName, String[] argTypeNames);
/** Returns the inherited method element for the specified method
* name and argument types in the class with the specified name.
@@ -1193,15 +1060,11 @@ abstract public Object getMethod (String className, String methodName,
* @return the method element
* @see #getClass
*/
- public Object getInheritedMethod (String className, String methodName,
- String[] argTypeNames)
- {
+ public Object getInheritedMethod(String className, String methodName, String[] argTypeNames) {
String superClass = getSuperclass(className);
- Object method = null;
+ Method method = null;
- while ((superClass != null) && ((method =
- getMethod(superClass, methodName, argTypeNames)) == null))
- {
+ while ((superClass != null) && ((method = (Method) getMethod(superClass, methodName, argTypeNames)) == null)) {
superClass = getSuperclass(superClass);
}
@@ -1219,7 +1082,7 @@ public Object getInheritedMethod (String className, String methodName,
* @see #getField
* @see #getMethod
*/
- abstract public String getType (Object element);
+ public abstract String getType(Object element);
/** Returns the field element for the specified fieldName in the class
* with the specified className.
@@ -1228,7 +1091,7 @@ public Object getInheritedMethod (String className, String methodName,
* @param fieldName the name of the field to be checked
* @return the field element for the specified fieldName
*/
- abstract public Object getField (String className, String fieldName);
+ public abstract Object getField(String className, String fieldName);
/** Returns the inherited field element for the specified fieldName in
* the class with the specified className. Note that the class
@@ -1239,17 +1102,12 @@ public Object getInheritedMethod (String className, String methodName,
* @param fieldName the name of the field to be checked
* @return the field element for the specified fieldName
*/
- public Object getInheritedField (String className, String fieldName)
- {
+ public Object getInheritedField(String className, String fieldName) {
String superClass = getSuperclass(className);
Object field = null;
-
- while ((superClass != null) &&
- ((field = getField(superClass, fieldName)) == null))
- {
+ while ((superClass != null) && ((field = getField(superClass, fieldName)) == null)) {
superClass = getSuperclass(superClass);
}
-
return field;
}
@@ -1261,9 +1119,8 @@ public Object getInheritedField (String className, String fieldName)
* @return true if this field name represents a valid
* field; false otherwise.
*/
- public boolean hasField (String className, String fieldName)
- {
- return (getField(className, fieldName) != null);
+ public boolean hasField(String className, String fieldName) {
+ return getField(className, fieldName) != null;
}
/** Returns the field type for the specified fieldName in the class
@@ -1273,8 +1130,7 @@ public boolean hasField (String className, String fieldName)
* @param fieldName the name of the field to be checked
* @return the field type for the specified fieldName
*/
- public String getFieldType (String className, String fieldName)
- {
+ public String getFieldType(String className, String fieldName) {
return getType(getField(className, fieldName));
}
@@ -1289,7 +1145,7 @@ public String getFieldType (String className, String fieldName)
* false otherwise.
* @see #getField
*/
- abstract public boolean isSerializable (Object fieldElement);
+ public abstract boolean isSerializable (Object fieldElement);
/** Determines if a field with the specified fieldName in the class
* with the specified className has a primitive type.
@@ -1300,8 +1156,7 @@ public String getFieldType (String className, String fieldName)
* field; false otherwise.
* @see #getFieldType
*/
- public boolean isPrimitive (String className, String fieldName)
- {
+ public boolean isPrimitive(String className, String fieldName) {
return isPrimitive(getFieldType(className, fieldName));
}
@@ -1312,10 +1167,8 @@ public boolean isPrimitive (String className, String fieldName)
* false otherwise.
* @see #getFieldType
*/
- protected boolean isPrimitive (String className)
- {
- return ((className != null) &&
- JavaTypeHelper.getPrimitiveClass(className) != null);
+ protected boolean isPrimitive(String className) {
+ return className != null && JavaTypeHelper.getPrimitiveClass(className) != null;
}
/** Determines if a field with the specified fieldName in the class
@@ -1327,7 +1180,7 @@ protected boolean isPrimitive (String className)
* field; false otherwise.
* @see #getFieldType
*/
- abstract public boolean isArray (String className, String fieldName);
+ public abstract boolean isArray (String className, String fieldName);
/** Determines if a field with the specified fieldName in the class
* with the specified className is a byte array.
@@ -1338,8 +1191,7 @@ protected boolean isPrimitive (String className)
* field; false otherwise.
* @see #getFieldType
*/
- public boolean isByteArray (String className, String fieldName)
- {
+ public boolean isByteArray(String className, String fieldName) {
return isByteArray(getFieldType(className, fieldName));
}
@@ -1349,9 +1201,8 @@ public boolean isByteArray (String className, String fieldName)
* @return true if this class represents a byte array;
* false otherwise.
*/
- protected boolean isByteArray (String className)
- {
- return ("byte[]".equals(className)); // NOI18N
+ protected boolean isByteArray(String className) {
+ return ("byte[]".equals(className));
}
/** Determines if the class name represents a collection.
@@ -1360,8 +1211,7 @@ protected boolean isByteArray (String className)
* false otherwise.
* @see #getFieldType
*/
- public boolean isCollection (String className)
- {
+ public boolean isCollection(String className) {
return _collectionClasses.contains(className);
}
@@ -1376,8 +1226,7 @@ public boolean isCollection (String className)
* @see #isCollection
* @see #getFieldType
*/
- public boolean isSecondClassObject (String className)
- {
+ public boolean isSecondClassObject(String className) {
return _scoClasses.contains(className);
}
@@ -1392,8 +1241,7 @@ public boolean isSecondClassObject (String className)
* @see #isCollection
* @see #getFieldType
*/
- public boolean isMutableSecondClassObject (String className)
- {
+ public boolean isMutableSecondClassObject(String className) {
return _mutableScoClasses.contains(className);
}
@@ -1411,7 +1259,7 @@ public boolean isMutableSecondClassObject (String className)
* @see #getConstructor
* @see #getMethod
*/
- abstract public String getDeclaringClass (Object memberElement);
+ public abstract String getDeclaringClass (Object memberElement);
/** Returns the modifier mask for the specified member element.
* Note, the member element is either a class element as returned by
@@ -1426,15 +1274,14 @@ public boolean isMutableSecondClassObject (String className)
* @see #getConstructor
* @see #getMethod
*/
- abstract public int getModifiers (Object memberElement);
+ public abstract int getModifiers (Object memberElement);
/** Returns the modifier mask for the specified className.
* @param className the fully qualified name of the class to be checked
* @return the modifier mask for the specified class
* @see java.lang.reflect.Modifier
*/
- public int getModifiersForClass (String className)
- {
+ public int getModifiersForClass(String className) {
return getModifiers(getClass(className));
}
@@ -1446,8 +1293,7 @@ public int getModifiersForClass (String className)
* @return the modifier mask for the specified field
* @see java.lang.reflect.Modifier
*/
- protected int getModifiers (String className, String fieldName)
- {
+ protected int getModifiers(String className, String fieldName) {
return getModifiers(getField(className, fieldName));
}
@@ -1467,8 +1313,7 @@ protected int getModifiers (String className, String fieldName)
* @see #isSecondClassObject
* @see #shouldBePersistent
*/
- public boolean isPersistentAllowed (String className, String fieldName)
- {
+ public boolean isPersistentAllowed(String className, String fieldName) {
return isPersistentAllowed(className, null, fieldName);
}
@@ -1487,18 +1332,12 @@ public boolean isPersistentAllowed (String className, String fieldName)
* @see #isPersistentTypeAllowed
* @see #shouldBePersistent
*/
- public boolean isPersistentAllowed (String className,
- ClassLoader classLoader, String fieldName)
- {
+ public boolean isPersistentAllowed(String className, ClassLoader classLoader, String fieldName) {
int modifier = getModifiers(className, fieldName);
-
- if (!Modifier.isStatic(modifier) && !Modifier.isFinal(modifier))
- {
- return isPersistentTypeAllowed(
- getFieldType(className, fieldName), classLoader);
+ if (Modifier.isStatic(modifier) || Modifier.isFinal(modifier)) {
+ return false;
}
-
- return false;
+ return isPersistentTypeAllowed(getFieldType(className, fieldName), classLoader);
}
/** Returns true if the a field of the specified class or
@@ -1515,11 +1354,9 @@ public boolean isPersistentAllowed (String className,
* @see #isPersistent
* @see #isSecondClassObject
*/
- protected boolean isPersistentTypeAllowed (String className,
- ClassLoader classLoader)
- {
- return (isPrimitive(className) || isSecondClassObject(className) ||
- isByteArray(className) || isPersistent(className, classLoader));
+ protected boolean isPersistentTypeAllowed(String className, ClassLoader classLoader) {
+ return isPrimitive(className) || isSecondClassObject(className) || isByteArray(className)
+ || isPersistent(className, classLoader);
}
/** Returns true if the specified field should be made
@@ -1532,8 +1369,7 @@ protected boolean isPersistentTypeAllowed (String className,
* @return whether the specified field should be made persistent
* see #getModifiers(String,String)
*/
- public boolean shouldBePersistent (String className, String fieldName)
- {
+ public boolean shouldBePersistent(String className, String fieldName) {
return !Modifier.isVolatile(getModifiers(className, fieldName));
}
@@ -1545,11 +1381,8 @@ public boolean shouldBePersistent (String className, String fieldName)
* @return the PersistenceFieldElement for the specified field,
* null if an error occurs or none exists
*/
- public PersistenceFieldElement getPersistenceField (String className,
- String fieldName)
- {
- return (hasField(className, fieldName) ?
- getPersistenceFieldInternal(className, fieldName) : null);
+ public PersistenceFieldElement getPersistenceField(String className, String fieldName) {
+ return hasField(className, fieldName) ? getPersistenceFieldInternal(className, fieldName) : null;
}
/** Returns the PersistenceFieldElement with the supplied fieldName found
@@ -1560,13 +1393,9 @@ public PersistenceFieldElement getPersistenceField (String className,
* @return the PersistenceFieldElement for the specified field,
* null if an error occurs or none exists
*/
- protected PersistenceFieldElement getPersistenceFieldInternal
- (String className, String fieldName)
- {
+ protected PersistenceFieldElement getPersistenceFieldInternal(String className, String fieldName) {
PersistenceClassElement classElement = getPersistenceClass(className);
-
- return ((classElement != null) ?
- classElement.getField(fieldName) : null);
+ return classElement == null ? null : classElement.getField(fieldName);
}
/** Determines if the specified className and fieldName pair represent a
@@ -1577,18 +1406,12 @@ public PersistenceFieldElement getPersistenceField (String className,
* @return true if this field name represents a persistent
* field; false otherwise.
*/
- public boolean isPersistent (String className, String fieldName)
- {
- PersistenceFieldElement fieldElement =
- getPersistenceField(className, fieldName);
-
- if (fieldElement != null)
- {
- return (PersistenceFieldElement.PERSISTENT ==
- fieldElement.getPersistenceType());
+ public boolean isPersistent(String className, String fieldName) {
+ PersistenceFieldElement fieldElement = getPersistenceField(className, fieldName);
+ if (fieldElement == null) {
+ return false;
}
-
- return false;
+ return (PersistenceFieldElement.PERSISTENT == fieldElement.getPersistenceType());
}
/** Determines if the specified className and fieldName pair represent a
@@ -1599,22 +1422,16 @@ public boolean isPersistent (String className, String fieldName)
* @return true if this field name represents a key field;
* false otherwise.
*/
- public boolean isKey (String className, String fieldName)
- {
- if (hasField(className, fieldName))
- {
- PersistenceClassElement classElement =
- getPersistenceClass(className);
-
- if (classElement != null)
- {
+ public boolean isKey(String className, String fieldName) {
+ if (hasField(className, fieldName)) {
+ PersistenceClassElement classElement = getPersistenceClass(className);
+ if (classElement != null) {
String keyClass = classElement.getKeyClass();
-
- if (keyClass != null)
+ if (keyClass != null) {
return hasField(keyClass, fieldName);
+ }
}
}
-
return false;
}
@@ -1628,15 +1445,14 @@ public boolean isKey (String className, String fieldName)
* @return true if this field name represents a field
* with a valid type for a key field; false otherwise.
*/
- public boolean isValidKeyType (String className, String fieldName)
- {
+ public boolean isValidKeyType(String className, String fieldName) {
String fieldType = getFieldType(className, fieldName);
- if (fieldType == null)
+ if (fieldType == null) {
fieldType = getType(getInheritedField(className, fieldName));
+ }
- return (isPrimitive(fieldType) ||
- (isSecondClassObject(fieldType) && !isCollection(fieldType)));
+ return (isPrimitive(fieldType) || (isSecondClassObject(fieldType) && !isCollection(fieldType)));
}
/** Determines if the specified className and fieldName pair represent a
@@ -1647,17 +1463,14 @@ public boolean isValidKeyType (String className, String fieldName)
* @return true if this field name represents a field in
* the default fetch group; false otherwise.
*/
- public boolean isDefaultFetchGroup (String className, String fieldName)
- {
+ public boolean isDefaultFetchGroup(String className, String fieldName) {
MappingClassElement mappingClass = getMappingClass(className);
- try
- {
- return (MappingFieldElement.GROUP_DEFAULT ==
- mappingClass.getField(fieldName).getFetchGroup());
+ try {
+ return (MappingFieldElement.GROUP_DEFAULT == mappingClass.getField(fieldName).getFetchGroup());
+ } catch (Exception e) {
+ // will return false
}
- catch (Exception e)
- {} // will return false
return false;
}
@@ -1670,8 +1483,7 @@ public boolean isDefaultFetchGroup (String className, String fieldName)
* @return true if no errors or warnings occur,
* false otherwise.
*/
- public boolean parse (String className)
- {
+ public boolean parse(String className) {
return new ModelValidator(this, className, getMessages()).parseCheck();
}
@@ -1686,8 +1498,7 @@ public boolean parse (String className)
* errors or warnings encountered. If no errors or warnings were
* encountered, the collection will be empty, not null.
*/
- public Collection validate (String className, ResourceBundle bundle)
- {
+ public Collection validate(String className, ResourceBundle bundle) {
return validate(className, null, bundle);
}
@@ -1703,32 +1514,31 @@ public Collection validate (String className, ResourceBundle bundle)
* errors or warnings encountered. If no errors or warnings were
* encountered, the collection will be empty, not null.
*/
- public Collection validate (String className, ClassLoader classLoader,
- ResourceBundle bundle)
- {
- return new ModelValidator(this, className, classLoader,
- ((bundle == null) ? getMessages() : bundle)).fullValidationCheck();
+ public Collection validate(String className, ClassLoader classLoader, ResourceBundle bundle) {
+ return new ModelValidator(this, className, classLoader, bundle == null ? getMessages() : bundle)
+ .fullValidationCheck();
}
+
/** Standard set of arguments for comparison with readObject method.
*/
public static String[] getReadObjectArgs() {
// Creating and returning a new array every time to prevent returning a mutable array
- return new String[] {"java.io.ObjectInputStream"}; //NOI18N
+ return new String[] {"java.io.ObjectInputStream"};
}
/** Standard set of arguments for comparison with equals method.
*/
public static String[] getEqualsArgs() {
// Creating and returning a new array every time to prevent returning a mutable array
- return new String[] {"java.lang.Object"}; //NOI18N
+ return new String[] {"java.lang.Object"};
}
/** Standard set of arguments for comparison with writeObject method.
*/
public static String[] getWriteObjectArgs() {
// Creating and returning a new array every time to prevent returning a mutable array
- return new String[] {"java.io.ObjectOutputStream"}; //NOI18N
+ return new String[] {"java.io.ObjectOutputStream"};
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/RuntimeModel.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/RuntimeModel.java
index 04b473d25a5..1670c8abaeb 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/RuntimeModel.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/RuntimeModel.java
@@ -39,6 +39,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import org.glassfish.persistence.common.I18NHelper;
import org.netbeans.modules.dbschema.SchemaElement;
@@ -52,11 +53,11 @@ public class RuntimeModel extends Model {
/** Extension of the class file, used to figure out the path for handling
* the mapping file.
*/
- private static final String CLASS_EXTENSION = "class"; // NOI18N
+ private static final String CLASS_EXTENSION = "class";
/** Constant which represents the prefix of the java package.
*/
- private static final String JAVA_PACKAGE = "java."; // NOI18N
+ private static final String JAVA_PACKAGE = "java.";
/** Constant which represents the serializable interface.
*/
@@ -65,7 +66,7 @@ public class RuntimeModel extends Model {
/** Map of class loader used to find classes and mapping information. Keys
* are fully qualified class names.
*/
- private HashMap classLoaders = new HashMap();
+ private Map classLoaders = new HashMap<>();
/** Creates a new RuntimeModel. This constructor should not be called
* directly; instead, the static instance accesible from the Model class
@@ -83,11 +84,9 @@ protected RuntimeModel ()
* false otherwise.
*/
@Override
- public boolean isInterface (String className)
- {
- Class classElement = (Class)getClass(className);
-
- return ((classElement != null) ? classElement.isInterface() : false);
+ public boolean isInterface(String className) {
+ Class> classElement = getClass(className);
+ return classElement == null ? false : classElement.isInterface();
}
/** Returns the input stream with the supplied resource name found with
@@ -103,17 +102,14 @@ public boolean isInterface (String className)
* if an error occurs or none exists
*/
@Override
- protected BufferedInputStream getInputStreamForResource (String className,
- ClassLoader classLoader, String resourceName)
- {
- InputStream is = ((className != null) ?
- classLoader.getResourceAsStream(resourceName) : null);
-
- BufferedInputStream rc = null;
- if (is != null && !(is instanceof BufferedInputStream)) {
- rc = new BufferedInputStream(is);
+ protected BufferedInputStream getInputStreamForResource(String className, ClassLoader classLoader,
+ String resourceName) {
+ InputStream is = className == null ? null : classLoader.getResourceAsStream(resourceName);
+ BufferedInputStream rc;
+ if (is == null || is instanceof BufferedInputStream) {
+ rc = (BufferedInputStream) is;
} else {
- rc = (BufferedInputStream)is;
+ rc = new BufferedInputStream(is);
}
return rc;
}
@@ -124,9 +120,8 @@ protected BufferedInputStream getInputStreamForResource (String className,
* @return the class name (without package) for the supplied
* class name
*/
- private String getShortClassName (String className)
- {
- return JavaTypeHelper.getShortClassName(className);
+ private String getShortClassName(String className) {
+ return JavaTypeHelper.getShortClassName(className);
}
/** Returns the name of the second to top (top excluding java.lang.Object)
@@ -136,18 +131,15 @@ private String getShortClassName (String className)
* className if an error occurs or none exists
*/
@Override
- protected String findPenultimateSuperclass (String className)
- {
- Class classElement = (Class)getClass(className);
- Class objectClass = java.lang.Object.class;
- Class testClass = null;
-
+ protected String findPenultimateSuperclass(String className) {
+ Class> classElement = getClass(className);
if (classElement == null) {
return className;
}
- while ((testClass = classElement.getSuperclass()) != null)
- {
+ Class objectClass = java.lang.Object.class;
+ Class> testClass;
+ while ((testClass = classElement.getSuperclass()) != null) {
if (testClass.equals(objectClass)) {
break;
}
@@ -166,13 +158,13 @@ protected String findPenultimateSuperclass (String className)
@Override
protected String getSuperclass (String className)
{
- Class classElement = (Class)getClass(className);
+ Class> classElement = getClass(className);
if (classElement != null) {
classElement = classElement.getSuperclass();
}
- return ((classElement != null) ? classElement.getName() : null);
+ return classElement == null ? null : classElement.getName();
}
/** Returns the MappingClassElement created for the specified class name.
@@ -185,9 +177,7 @@ protected String getSuperclass (String className)
* @see com.sun.jdo.api.persistence.model.mapping.impl.MappingClassElementImpl#forName(String, Model)
*/
@Override
- public MappingClassElement getMappingClass (String className,
- ClassLoader classLoader)
- {
+ public MappingClassElement getMappingClass(String className, ClassLoader classLoader) {
MappingClassElement mappingClass = null;
// First check class loader. This has to be done before the super call!
@@ -196,8 +186,7 @@ public MappingClassElement getMappingClass (String className,
// same class name. So we have to check the multiple class loader first.
classLoader = findClassLoader(className, classLoader);
mappingClass = super.getMappingClass(className, classLoader);
- if ((mappingClass != null) && (classLoader != null))
- {
+ if (mappingClass != null && classLoader != null) {
// Lookup the SchemElement connected to mappingClass. This reads
// the .dbschema file using the specified classLoader and stores the
// SchemaElement in the SchemaElement cache. Any subsequent
@@ -210,12 +199,9 @@ public MappingClassElement getMappingClass (String className,
// (mapped once, unmapped now), but if the databaseRoot is
// not null or empty and we can't find the schema, throw a
// RuntimeException to notify the user that something is wrong.
- if (!StringHelper.isEmpty(databaseRoot) &&
- (SchemaElement.forName(databaseRoot, classLoader) == null))
- {
- throw new RuntimeException(I18NHelper.getMessage(
- getMessages(), "dbschema.not_found", // NOI18N
- databaseRoot, className));
+ if (!StringHelper.isEmpty(databaseRoot) && SchemaElement.forName(databaseRoot, classLoader) == null) {
+ throw new RuntimeException(
+ I18NHelper.getMessage(getMessages(), "dbschema.not_found", databaseRoot, className));
}
}
@@ -226,8 +212,7 @@ public MappingClassElement getMappingClass (String className,
* @return unmodifiable ClassLoader cache
*/
@Override
- public Map getClassLoaderCache ()
- {
+ public Map getClassLoaderCache() {
return Collections.unmodifiableMap(classLoaders);
}
@@ -240,19 +225,15 @@ public Map getClassLoaderCache ()
* @param classLoader used to determine the classes to be removed
*/
@Override
- public void removeResourcesFromCaches (ClassLoader classLoader)
- {
- Collection classNames = new HashSet();
+ public void removeResourcesFromCaches(ClassLoader classLoader) {
+ Collection classNames = new HashSet<>();
- synchronized(classLoaders)
- {
- for (Iterator i = classLoaders.entrySet().iterator(); i.hasNext();)
- {
- Map.Entry next = (Map.Entry)i.next();
+ synchronized (classLoaders) {
+ for (Iterator> i = classLoaders.entrySet().iterator(); i.hasNext();) {
+ Entry next = i.next();
// check the cached class loader
- if (next.getValue() == classLoader)
- {
+ if (next.getValue() == classLoader) {
// add className to the collection of classNames to be
// removed
classNames.add(next.getKey());
@@ -275,32 +256,24 @@ public void removeResourcesFromCaches (ClassLoader classLoader)
* @exception IOException if there is some error creating the file
*/
@Override
- protected BufferedOutputStream createFile (String className, String baseFileName,
- String extension) throws IOException
- {
+ protected BufferedOutputStream createFile(String className, String baseFileName, String extension)
+ throws IOException {
char extensionCharacter = '.';
- File file = getFile(className,
- baseFileName + extensionCharacter + extension);
-
- if (file == null)
- {
- Class classElement = (Class)getClass(className);
+ File file = getFile(className, baseFileName + extensionCharacter + extension);
- if (classElement != null)
- {
+ if (file == null) {
+ Class> classElement = getClass(className);
+ if (classElement != null) {
// need to find the path before the package name
- String path = classElement.getResource(
- getShortClassName(className) + extensionCharacter +
- CLASS_EXTENSION).getFile();
+ String path = classElement
+ .getResource(getShortClassName(className) + extensionCharacter + CLASS_EXTENSION).getFile();
int index = path.lastIndexOf(extensionCharacter) + 1;
file = new File(path.substring(0, index) + extension);
file.createNewFile();
}
}
- return ((file != null)
- ? (new BufferedOutputStream(new FileOutputStream(file)))
- : null);
+ return file == null ? null : new BufferedOutputStream(new FileOutputStream(file));
}
/** Deletes the file with the given file name which is parallel
@@ -310,9 +283,7 @@ protected BufferedOutputStream createFile (String className, String baseFileName
* @exception IOException if there is some error deleting the file
*/
@Override
- protected void deleteFile (String className, String fileName)
- throws IOException
- {
+ protected void deleteFile(String className, String fileName) throws IOException {
File file = getFile(className, fileName);
if ((file != null) && file.exists()) {
@@ -328,13 +299,10 @@ protected void deleteFile (String className, String fileName)
* if an error occurs
* @exception IOException if there is some error getting the file
*/
- protected File getFile (String className, String fileName)
- throws IOException
- {
- Class classElement = (Class)getClass(className);
+ protected File getFile(String className, String fileName) throws IOException {
+ Class> classElement = getClass(className);
- if (classElement != null)
- {
+ if (classElement != null) {
// need to find the path before the package name
URL path = classElement.getResource(fileName.substring(
fileName.lastIndexOf(getShortClassName(className))));
@@ -353,19 +321,14 @@ protected File getFile (String className, String fileName)
* if an error occurs or none exists
*/
@Override
- public Object getClass (String className, ClassLoader classLoader)
- {
+ public Class> getClass(String className, ClassLoader classLoader) {
if (className == null) {
return null;
}
-
- try
- {
+ try {
classLoader = findClassLoader(className, classLoader);
return Class.forName(className, true, classLoader);
- }
- catch (ClassNotFoundException e)
- {
+ } catch (ClassNotFoundException e) {
return null;
}
}
@@ -383,9 +346,7 @@ public Object getClass (String className, ClassLoader classLoader)
* specified className
* @exception IllegalArgumentException if there is class loader problem
*/
- protected ClassLoader findClassLoader (String className,
- ClassLoader classLoader) throws IllegalArgumentException
- {
+ protected ClassLoader findClassLoader(String className, ClassLoader classLoader) throws IllegalArgumentException {
ClassLoader cached = null;
if (className == null) {
@@ -397,36 +358,28 @@ protected ClassLoader findClassLoader (String className,
return getClass().getClassLoader();
}
- synchronized (classLoaders)
- {
- cached = (ClassLoader)classLoaders.get(className);
+ synchronized (classLoaders) {
+ cached = classLoaders.get(className);
- if (classLoader == null)
- {
+ if (classLoader == null) {
// Case 1: specified class loader is null =>
// return cached class loader if available, if not
// take current class loader
- classLoader =
- (cached != null) ? cached : getClass().getClassLoader();
- }
- else if (cached == null)
- {
+ classLoader = (cached != null) ? cached : getClass().getClassLoader();
+ } else if (cached == null) {
// Case 2: specified class loader is NOT null AND
// no class loader cached for the class name =>
// put specified class loader in cache
classLoaders.put(className, classLoader);
- }
- else if (classLoader != cached)
- {
+ } else if (classLoader != cached) {
// Case 3: specified class loader is NOT null AND
// cache contains class loader for this class name AND
// both class loaders are not identical =>
// pontential conflict
- Class clazz = null;
- Class cachedClazz = null;
+ Class> clazz = null;
+ Class> cachedClazz = null;
- try
- {
+ try {
String prop = ClassLoaderStrategy.getStrategy();
// Load the class using specified and cached class loader.
@@ -435,22 +388,17 @@ else if (classLoader != cached)
clazz = Class.forName(className, true, classLoader);
cachedClazz = Class.forName(className, true, cached);
- if (clazz.getClassLoader() == cachedClazz.getClassLoader())
- {
+ if (clazz.getClassLoader() == cachedClazz.getClassLoader()) {
// Case 3a: both class loaders are the same =>
// return it
return cached;
- }
- else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_IGNORE.equals(prop))
- {
+ } else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_IGNORE.equals(prop)) {
// Case 3b: both class loaders are different and
// the system property is defined as ignore =>
// ignore the specified class loader and return
// the cached class loader
return cached;
- }
- else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_RELOAD.equals(prop))
- {
+ } else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_RELOAD.equals(prop)) {
// Case 3c: both class loaders are different and
// the system property is defined as reload =>
// discard the cached class loader and replace it
@@ -458,24 +406,19 @@ else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_RELOAD.equals(prop))
removeResourcesFromCaches(cachedClazz.getClassLoader());
classLoaders.put(className, classLoader);
return classLoader;
- }
- else
- {
+ } else {
// Case 3d: both class loaders are different and
// the system property is defined as error or
// any other value =>
// throw exception
- throw new IllegalArgumentException(I18NHelper.getMessage(
- getMessages(), "classloader.multiple", // NOI18N
+ throw new IllegalArgumentException(I18NHelper.getMessage(getMessages(), "classloader.multiple",
className));
}
- }
- catch (ClassNotFoundException ex)
- {
+ } catch (ClassNotFoundException ex) {
// At least one of the class loader could not find the class.
// Update the classLoader map, if the specified class loader
// could find it, but the cached could not.
- if ((clazz != null) && (cachedClazz == null)) {
+ if (clazz != null) {
classLoaders.put(className, classLoader);
}
}
@@ -497,17 +440,12 @@ else if (ClassLoaderStrategy.MULTIPLE_CLASS_LOADERS_RELOAD.equals(prop))
* @see #getClass
*/
@Override
- public boolean implementsInterface (Object classElement,
- String interfaceName)
- {
- Class interfaceClass = (Class)getClass(interfaceName);
-
- if ((classElement == null) || !(classElement instanceof Class) ||
- (interfaceClass == null)) {
- return false;
+ public boolean implementsInterface(Object classElement, String interfaceName) {
+ Class> interfaceClass = getClass(interfaceName);
+ if (classElement != null && classElement instanceof Class && interfaceClass != null) {
+ return interfaceClass.isAssignableFrom((Class>) classElement);
}
-
- return interfaceClass.isAssignableFrom((Class)classElement);
+ return false;
}
/** Determines if the class with the specified name declares a constructor.
@@ -518,7 +456,7 @@ public boolean implementsInterface (Object classElement,
*/
@Override
public boolean hasConstructor(final String className) {
- final Class classElement = (Class)getClass(className);
+ final Class> classElement = getClass(className);
if (classElement != null) {
Boolean b = JavaTypeHelper.valueOf(classElement.getDeclaredConstructors().length != 0);
return b.booleanValue();
@@ -538,9 +476,9 @@ public boolean hasConstructor(final String className) {
*/
@Override
public Object getConstructor(final String className, String[] argTypeNames) {
- final Class classElement = (Class) getClass(className);
+ final Class> classElement = getClass(className);
if (classElement != null) {
- final Class[] argTypes = getTypesForNames(argTypeNames);
+ final Class>[] argTypes = getTypesForNames(argTypeNames);
try {
return classElement.getDeclaredConstructor(argTypes);
} catch (NoSuchMethodException ex) {
@@ -564,9 +502,9 @@ public Object getConstructor(final String className, String[] argTypeNames) {
*/
@Override
public Object getMethod(final String className, final String methodName, String[] argTypeNames) {
- final Class classElement = (Class) getClass(className);
+ final Class> classElement = getClass(className);
if (classElement != null) {
- final Class[] argTypes = getTypesForNames(argTypeNames);
+ final Class>[] argTypes = getTypesForNames(argTypeNames);
try {
return classElement.getDeclaredMethod(methodName, argTypes);
} catch (NoSuchMethodException ex) {
@@ -590,8 +528,7 @@ public Object getMethod(final String className, final String methodName, String[
* @see #getMethod
*/
@Override
- public String getType (Object element)
- {
+ public String getType(Object element) {
return getNameForType(getTypeObject(element));
}
@@ -601,9 +538,9 @@ public String getType (Object element)
* @return the names of the field elements for the specified class
*/
@Override
- public List getFields(String className) {
- List returnList = new ArrayList();
- final Class classElement = (Class) getClass(className);
+ public List getFields(String className) {
+ List returnList = new ArrayList<>();
+ final Class> classElement = getClass(className);
if (classElement != null) {
Field[] fields = classElement.getDeclaredFields();
@@ -626,7 +563,7 @@ public List getFields(String className) {
*/
@Override
public Object getField(String className, final String fieldName) {
- final Class classElement = (Class) getClass(className);
+ final Class> classElement = getClass(className);
if (classElement != null) {
try {
return classElement.getDeclaredField(fieldName);
@@ -652,9 +589,8 @@ public Object getField(String className, final String fieldName) {
* @see #getField
*/
@Override
- public boolean isSerializable (Object fieldElement)
- {
- Class type = getTypeObject(fieldElement);
+ public boolean isSerializable(Object fieldElement) {
+ Class> type = getTypeObject(fieldElement);
// check if the topmost element type is serializable
while ((type != null) && type.isArray()) {
@@ -700,15 +636,14 @@ public boolean isArray (String className, String fieldName)
* @see #getMethod
*/
@Override
- public String getDeclaringClass (Object memberElement)
- {
- Class classElement = null;
-
- if ((memberElement != null) && (memberElement instanceof Member)) {
- classElement = ((Member)memberElement).getDeclaringClass();
+ public String getDeclaringClass(Object memberElement) {
+ Class> classElement;
+ if (memberElement != null && memberElement instanceof Member) {
+ classElement = ((Member) memberElement).getDeclaringClass();
+ } else {
+ classElement = null;
}
-
- return ((classElement != null) ? classElement.getName() : null);
+ return classElement == null ? null : classElement.getName();
}
/** Returns the modifier mask for the specified member element.
@@ -726,19 +661,14 @@ public String getDeclaringClass (Object memberElement)
* @see #getMethod
*/
@Override
- public int getModifiers (Object memberElement)
- {
+ public int getModifiers(Object memberElement) {
int modifiers = 0;
- if (memberElement != null)
- {
- if (memberElement instanceof Class)
- {
- modifiers = ((Class)memberElement).getModifiers();
- }
- else if (memberElement instanceof Member)
- {
- modifiers = ((Member)memberElement).getModifiers();
+ if (memberElement != null) {
+ if (memberElement instanceof Class) {
+ modifiers = ((Class>) memberElement).getModifiers();
+ } else if (memberElement instanceof Member) {
+ modifiers = ((Member) memberElement).getModifiers();
}
}
@@ -756,32 +686,25 @@ else if (memberElement instanceof Member)
* @see #getField
* @see #getMethod
*/
- protected Class getTypeObject (Object element)
- {
- Class type = null;
-
- if (element != null)
- {
+ protected Class> getTypeObject(Object element) {
+ if (element != null) {
if (element instanceof Field) {
- type = ((Field)element).getType();
+ return ((Field) element).getType();
} else if (element instanceof Method) {
- type = ((Method)element).getReturnType();
+ return ((Method) element).getReturnType();
}
}
- return type;
+ return null;
}
- private String getNameForType (Class type)
- {
+
+ private String getNameForType(Class> type) {
String typeName = null;
- if (type != null)
- {
- if (type.isArray())
- {
- typeName = getNameForType(
- type.getComponentType()) + "[]"; // NOI18N
+ if (type != null) {
+ if (type.isArray()) {
+ typeName = getNameForType(type.getComponentType()) + "[]";
} else {
typeName = type.getName();
}
@@ -792,9 +715,8 @@ private String getNameForType (Class type)
/** Converts the array of type names into an array of Class objects.
*/
- private Class[] getTypesForNames (String[] typeNames)
- {
- Class[] classes = new Class[typeNames.length];
+ private Class>[] getTypesForNames(String[] typeNames) {
+ Class>[] classes = new Class[typeNames.length];
for (int i = 0; i < classes.length; i++) {
classes[i] = getTypeForName(typeNames[i]);
@@ -803,15 +725,16 @@ private Class[] getTypesForNames (String[] typeNames)
return classes;
}
- /** Converts the specified type name into its corresponding java.lang.Class
+
+ /**
+ * Converts the specified type name into its corresponding java.lang.Class
* representation.
*/
- private Class getTypeForName (String typeName)
- {
- Class clazz = JavaTypeHelper.getPrimitiveClass(typeName);
+ private Class> getTypeForName(String typeName) {
+ Class> clazz = JavaTypeHelper.getPrimitiveClass(typeName);
if (clazz == null) {
- clazz = (Class)getClass(typeName);
+ clazz = getClass(typeName);
}
return clazz;
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceClassElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceClassElement.java
index 553a33c3622..d2e20607769 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceClassElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceClassElement.java
@@ -30,6 +30,10 @@
import org.glassfish.persistence.common.I18NHelper;
+import static com.sun.jdo.api.persistence.model.jdo.PersistenceElement.Impl.ADD;
+import static com.sun.jdo.api.persistence.model.jdo.PersistenceElement.Impl.REMOVE;
+import static com.sun.jdo.api.persistence.model.jdo.PersistenceElement.Impl.SET;
+
/* TODO:
1. throw ModelException on add duplicate field or concurrency group (will
need I18N for message)
@@ -89,12 +93,11 @@ public static PersistenceClassElement forName (String name, Model model)
* @return the package
* @see PersistenceElement#getName
*/
- public String getPackage ()
- {
+ public String getPackage() {
String className = getName();
int index = className.lastIndexOf('.');
- return ((index != -1) ? className.substring(0, index) : ""); // NOI18N
+ return index != -1 ? className.substring(0, index) : "";
}
/** Gets the modified flag for this persistence class.
@@ -157,8 +160,9 @@ public void setKeyClass (String name) throws ModelException
{
boolean hasValue = (name != null);
- if (hasValue)
+ if (hasValue) {
name = name.trim();
+ }
if (hasValue && (name.length() > 0))
{
@@ -167,12 +171,12 @@ public void setKeyClass (String name) throws ModelException
String nameSuffix = ((hasPrefix) ?
name.substring(className.length()) : name);
- if (!hasPrefix || (!nameSuffix.equalsIgnoreCase("Key") && // NOI18N
- !nameSuffix.equalsIgnoreCase(".OID") // NOI18N
- && !nameSuffix.equalsIgnoreCase("$OID"))) // NOI18N
+ if (!hasPrefix || (!nameSuffix.equalsIgnoreCase("Key") &&
+ !nameSuffix.equalsIgnoreCase(".OID")
+ && !nameSuffix.equalsIgnoreCase("$OID")))
{
throw new ModelException(I18NHelper.getMessage(getMessages(),
- "jdo.class.key_class_invalid", // NOI18N
+ "jdo.class.key_class_invalid",
new Object[]{name, className}));
}
}
@@ -186,6 +190,7 @@ public void setKeyClass (String name) throws ModelException
* @param name the name
* @exception ModelException if impossible
*/
+ @Override
public void setName (String name) throws ModelException
{
String oldName = getName();
@@ -197,8 +202,9 @@ public void setName (String name) throws ModelException
String oldKeyClass = getKeyClass();
// a rename -- set the key class too
- if ((oldKeyClass != null) && oldKeyClass.startsWith(oldName))
+ if ((oldKeyClass != null) && oldKeyClass.startsWith(oldName)) {
setKeyClass(name + oldKeyClass.substring(oldName.length()));
+ }
}
}
@@ -210,6 +216,7 @@ public void setName (String name) throws ModelException
* @param field the field to be added
* @exception ModelException if impossible
*/
+ @Override
public void addField (PersistenceFieldElement field)
throws ModelException
{
@@ -221,10 +228,11 @@ public void addField (PersistenceFieldElement field)
* @param fields the array of fields to be added
* @exception ModelException if impossible
*/
+ @Override
public void addFields(PersistenceFieldElement[] fields)
throws ModelException
{
- getClassImpl().changeFields(fields, Impl.ADD);
+ getClassImpl().changeFields(fields, ADD);
}
/** Remove the supplied field from the collection of fields maintained by
@@ -232,9 +240,8 @@ public void addFields(PersistenceFieldElement[] fields)
* @param field the field to be removed
* @exception ModelException if impossible
*/
- public void removeField (PersistenceFieldElement field)
- throws ModelException
- {
+ @Override
+ public void removeField(PersistenceFieldElement field) throws ModelException {
removeFields(new PersistenceFieldElement[]{field});
}
@@ -243,23 +250,22 @@ public void removeField (PersistenceFieldElement field)
* @param fields the array of fields to be removed
* @exception ModelException if impossible
*/
- public void removeFields (PersistenceFieldElement[] fields)
- throws ModelException
- {
+ @Override
+ public void removeFields(PersistenceFieldElement[] fields) throws ModelException {
int i, count = ((fields != null) ? fields.length : 0);
// first remove the fields from this class
- getClassImpl().changeFields(fields, Impl.REMOVE);
+ getClassImpl().changeFields(fields, REMOVE);
// now remove the fields from any concurrency groups
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
PersistenceFieldElement field = fields[i];
ConcurrencyGroupElement[] groups = field.getConcurrencyGroups();
int j, groupCount = ((groups != null) ? groups.length : 0);
- for (j = 0; j < groupCount; j++)
+ for (j = 0; j < groupCount; j++) {
groups[j].removeField(field);
+ }
}
}
@@ -267,40 +273,46 @@ public void removeFields (PersistenceFieldElement[] fields)
* of an array.
* @return the fields maintained by this holder
*/
- public PersistenceFieldElement[] getFields ()
- {
+ @Override
+ public PersistenceFieldElement[] getFields() {
return getClassImpl().getFields();
}
+
/** Sets the collection of fields maintained by this holder to the contents
* of the supplied array.
* @param fields the fields maintained by this holder
* @exception ModelException if impossible
*/
- public void setFields (PersistenceFieldElement[] fields)
- throws ModelException
- {
- getClassImpl().changeFields(fields, Impl.SET);
+ @Override
+ public void setFields(PersistenceFieldElement[] fields) throws ModelException {
+ getClassImpl().changeFields(fields, SET);
}
- /** Returns the field with the supplied name from the collection of fields
+
+ /**
+ * Returns the field with the supplied name from the collection of fields
* maintained by this holder.
+ *
* @param name the name of the field to be found
* @return the field with the supplied name, null if none
- * exists
+ * exists
*/
- public PersistenceFieldElement getField (String name)
- {
+ @Override
+ public PersistenceFieldElement getField(String name) {
return getClassImpl().getField(name);
}
- /** Tests whether the supplied field is in the collection of fields
+
+ /**
+ * Tests whether the supplied field is in the collection of fields
* maintained by this holder.
+ *
* @param field the field to be tested
*/
- public boolean containsField (PersistenceFieldElement field)
- {
- return (getClassImpl().getField(field.getName()) != null);
+ @Override
+ public boolean containsField(PersistenceFieldElement field) {
+ return getClassImpl().getField(field.getName()) != null;
}
//================== Relationships ===============================
@@ -310,24 +322,20 @@ public boolean containsField (PersistenceFieldElement field)
* @return the relationship fields maintained by this holder
* @see PersistenceClassElement#getFields
*/
- public RelationshipElement[] getRelationships ()
- {
+ public RelationshipElement[] getRelationships() {
PersistenceFieldElement[] fields = getFields();
int i, count = ((fields != null) ? fields.length : 0);
- ArrayList relationships = new ArrayList(count);
-
- for (i = 0; i < count; i++)
- {
+ ArrayList relationships = new ArrayList<>(count);
+ for (i = 0; i < count; i++) {
PersistenceFieldElement field = fields[i];
-
- if (field instanceof RelationshipElement)
- relationships.add(field);
+ if (field instanceof RelationshipElement) {
+ relationships.add((RelationshipElement) field);
+ }
}
count = relationships.size();
- return ((RelationshipElement[])relationships.toArray(
- new RelationshipElement[count]));
+ return relationships.toArray(RelationshipElement[]::new);
}
/** Returns the relationship with the supplied name from the collection of
@@ -338,17 +346,16 @@ public RelationshipElement[] getRelationships ()
* @see PersistenceClassElement#getRelationships
* @see PersistenceClassElement#getField
*/
- public RelationshipElement getRelationship (String name)
- {
+ public RelationshipElement getRelationship(String name) {
RelationshipElement[] relationships = getRelationships();
int i, count = ((relationships != null) ? relationships.length : 0);
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
RelationshipElement relationship = relationships[i];
- if (name.equals(relationship.getName()))
+ if (name.equals(relationship.getName())) {
return relationship;
+ }
}
return null;
@@ -376,7 +383,7 @@ public void addConcurrencyGroup (ConcurrencyGroupElement group)
public void addConcurrencyGroups (ConcurrencyGroupElement[] groups)
throws ModelException
{
- getClassImpl().changeConcurrencyGroups(groups, Impl.ADD);
+ getClassImpl().changeConcurrencyGroups(groups, ADD);
}
/** Remove the supplied group from the collection of concurrency groups for
@@ -398,7 +405,7 @@ public void removeConcurrencyGroup (ConcurrencyGroupElement group)
public void removeConcurrencyGroups (ConcurrencyGroupElement[] groups)
throws ModelException
{
- getClassImpl().changeConcurrencyGroups(groups, Impl.REMOVE);
+ getClassImpl().changeConcurrencyGroups(groups, REMOVE);
}
/** Returns the collection of fields groups by this class in the form
@@ -418,7 +425,7 @@ public ConcurrencyGroupElement[] getConcurrencyGroups ()
public void setConcurrencyGroups (ConcurrencyGroupElement[] groups)
throws ModelException
{
- getClassImpl().changeConcurrencyGroups(groups, Impl.SET);
+ getClassImpl().changeConcurrencyGroups(groups, SET);
}
/** Returns the concurrency group with the supplied name from the
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceElement.java
index 764988bbdf7..4c2cbe4f5bc 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceElement.java
@@ -37,7 +37,7 @@
* @version %I%
*/
public abstract class PersistenceElement extends Object
- implements PersistenceElementProperties, Comparable
+ implements PersistenceElementProperties, Comparable
{
/** I18N message handler */
private static final ResourceBundle _messages = I18NHelper.loadBundle(
@@ -126,6 +126,7 @@ public void setName (String name) throws ModelException
* of this persistence element.
* @return a string representation of the object
*/
+ @Override
public String toString () { return getName(); }
/** Overrides Object's equals method by comparing the name of this persistence element
@@ -134,20 +135,24 @@ public void setName (String name) throws ModelException
* @return true if this object is the same as the obj argument; false otherwise.
* @param obj the reference object with which to compare.
*/
+ @Override
public boolean equals(Object obj)
{
- if (obj == null)
+ if (obj == null) {
return false;
- if (obj == this)
+ }
+ if (obj == this) {
return true;
+ }
// check for the right class and then do the name check by calling compareTo.
- return (getClass() == obj.getClass()) && (compareTo(obj) == 0);
+ return (getClass() == obj.getClass()) && (compareTo((PersistenceElement) obj) == 0);
}
/** Overrides Object's hashCode method to return the hashCode of this persistence element's name.
* @return a hash code value for this object.
*/
+ @Override
public int hashCode()
{
return (getName()==null) ? 0 : getName().hashCode();
@@ -166,30 +171,36 @@ public int hashCode()
* or greater than the specified object.
* @exception ClassCastException - if the specified object is null or is not an instance of PersistenceElement
*/
- public int compareTo(Object o)
+ @Override
+ public int compareTo(PersistenceElement o)
{
// null is not allowed
- if (o == null)
+ if (o == null) {
throw new ClassCastException();
- if (o == this)
+ }
+ if (o == this) {
return 0;
+ }
String thisName = getName();
// the following statement throws a ClassCastException if o is not a PersistenceElement
- String otherName = ((PersistenceElement)o).getName();
+ String otherName = o.getName();
// if this does not have a name it should compare less than any named object
- if (thisName == null)
+ if (thisName == null) {
return (otherName == null) ? 0 : -1;
+ }
// if this is named and o does not have a name it should compare greater
- if (otherName == null)
+ if (otherName == null) {
return 1;
+ }
// now we know that this and o are named persistence elements =>
// use locale-sensitive String comparison
int ret = Collator.getInstance().compare(thisName, otherName);
// if both names are equal, both objects might have different types.
// If so order both objects by their type names (necessary to be consistent with equals)
- if ((ret == 0) && (getClass() != o.getClass()))
+ if ((ret == 0) && (getClass() != o.getClass())) {
ret = getClass().getName().compareTo(o.getClass().getName());
+ }
return ret;
}
@@ -204,8 +215,9 @@ public void setImpl (PersistenceElement.Impl impl)
{
_impl = impl;
- if (_impl != null)
+ if (_impl != null) {
getImpl().attachToElement(this);
+ }
}
/** Pluggable implementation of the storage of element properties.
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceFieldElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceFieldElement.java
index 3a668f952e8..98a129788b5 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceFieldElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/PersistenceFieldElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * PersistenceFieldElement.java
- *
- * Created on February 29, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.jdo;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -35,8 +30,7 @@
/**
*
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
public class PersistenceFieldElement extends PersistenceMemberElement
{
@@ -180,53 +174,47 @@ public void setKey (boolean flag) throws ModelException
* @return the concurrency groups in which this field participates
* @see PersistenceClassElement#getConcurrencyGroups
*/
- public ConcurrencyGroupElement[] getConcurrencyGroups ()
- {
- ConcurrencyGroupElement[] groups = getDeclaringClass().
- getConcurrencyGroups();
- int i, count = ((groups != null) ? groups.length : 0);
- ArrayList myGroups = new ArrayList(count);
+ public ConcurrencyGroupElement[] getConcurrencyGroups() {
+ ConcurrencyGroupElement[] groups = getDeclaringClass().getConcurrencyGroups();
+ int i, count = groups != null ? groups.length : 0;
+ ArrayList myGroups = new ArrayList<>(count);
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
ConcurrencyGroupElement group = groups[i];
- if (group.containsField(this))
+ if (group.containsField(this)) {
myGroups.add(group);
+ }
}
count = myGroups.size();
- return ((ConcurrencyGroupElement[])myGroups.toArray(
- new ConcurrencyGroupElement[count]));
+ return ((ConcurrencyGroupElement[]) myGroups.toArray(new ConcurrencyGroupElement[count]));
}
/** Computes the field number of this field element.
* @return the field number of this field, -1 if it cannot be found
*/
- public int getFieldNumber ()
- {
+ public int getFieldNumber() {
// for later - take into account the class
// get/setFieldInheritanceFlag behavior (i.e. might need to climb
// inheritance hierarchy
PersistenceFieldElement[] fields = getDeclaringClass().getFields();
int i, count = ((fields != null) ? fields.length : 0);
- for (i = 0; i < count; i++)
- if (equals(fields[i]))
+ for (i = 0; i < count; i++) {
+ if (equals(fields[i])) {
return i;
+ }
+ }
return -1;
}
- /* won't be used now -- we will compute this number whenever it is requested
- public void setFieldNumber (int fieldNumber) {} */
-
/** Pluggable implementation of the storage of field element properties.
* @see PersistenceFieldElement#PersistenceFieldElement
*/
- public interface Impl extends PersistenceMemberElement.Impl
- {
+ public interface Impl extends PersistenceMemberElement.Impl {
/** Get the persistence type of this field element.
* @return the persistence type, one of {@link #PERSISTENT} or
* {@link #DERIVED}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/PersistenceElementCollection.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/PersistenceElementCollection.java
index b6444484d93..276cebc0827 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/PersistenceElementCollection.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/PersistenceElementCollection.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * PersistenceElementCollection.java
- *
- * Created on March 6, 2000, 2:20 PM
- */
-
package com.sun.jdo.api.persistence.model.jdo.impl;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -33,8 +28,7 @@
/**
*
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
public class PersistenceElementCollection
{
@@ -60,9 +54,7 @@ public PersistenceElementCollection ()
}
/** Creates new PersistenceElementCollection */
- public PersistenceElementCollection (PersistenceElementImpl owner,
- String propertyName, Object[] template)
- {
+ public PersistenceElementCollection(PersistenceElementImpl owner, String propertyName, Object[] template) {
_owner = owner;
_propertyName = propertyName;
_template = template;
@@ -75,9 +67,7 @@ public PersistenceElementCollection (PersistenceElementImpl owner,
* {@link com.sun.jdo.api.persistence.model.jdo.PersistenceElement.Impl#SET}
* @exception ModelException if impossible
*/
- public void changeElements (PersistenceElement[] elements, int action)
- throws ModelException
- {
+ public void changeElements(PersistenceElement[] elements, int action) throws ModelException {
changeElements(Arrays.asList(elements), action);
}
@@ -88,59 +78,47 @@ public void changeElements (PersistenceElement[] elements, int action)
* {@link com.sun.jdo.api.persistence.model.jdo.PersistenceElement.Impl#SET}
* @exception ModelException if impossible
*/
- public void changeElements (List elements, int action)
- throws ModelException
- {
+ public void changeElements(List elements, int action) throws ModelException {
boolean changed = false;
- try
- {
+ try {
PersistenceElement[] oldElements = getElements();
- int oldLength = (oldElements == null) ? 0 : oldElements.length;
- int newLength = (elements == null) ? 0 : elements.size();
- List list = null;
+ int oldLength = oldElements == null ? 0 : oldElements.length;
+ int newLength = elements == null ? 0 : elements.size();
+ List list = null;
- switch (action)
- {
+ switch (action) {
case PersistenceElement.Impl.SET:
list = elements;
changed = true;
break;
case PersistenceElement.Impl.ADD:
- if (newLength > 0)
- {
- list = ((oldLength == 0) ? new ArrayList() :
- new ArrayList(Arrays.asList(oldElements)));
+ if (newLength > 0) {
+ list = ((oldLength == 0) ? new ArrayList<>() : new ArrayList<>(Arrays.asList(oldElements)));
list.addAll(elements);
changed = true;
}
break;
case PersistenceElement.Impl.REMOVE:
- if ((newLength > 0) && (oldLength > 0))
- {
- list = new ArrayList(Arrays.asList(oldElements));
+ if ((newLength > 0) && (oldLength > 0)) {
+ list = new ArrayList<>(Arrays.asList(oldElements));
list.removeAll(elements);
changed = true;
}
break;
}
- if (changed)
- {
- try
- {
+ if (changed) {
+ try {
_owner.fireVetoableChange(_propertyName, null, null);
- _elements = (PersistenceElement[])list.toArray(_template);
- }
- catch (PropertyVetoException e)
- {
+ _elements = (PersistenceElement[]) list.toArray(_template);
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
- }
- finally
- {
- if (changed)
+ } finally {
+ if (changed) {
_owner.firePropertyChange(_propertyName, null, null);
+ }
}
}
@@ -165,8 +143,9 @@ public PersistenceElement getElement (String name)
{
PersistenceElement element = elements[i];
- if (name.equals(element.getName()))
+ if (name.equals(element.getName())) {
return element;
+ }
}
return null;
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/RelationshipElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/RelationshipElementImpl.java
index 7f796476595..11a039e6775 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/RelationshipElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/jdo/impl/RelationshipElementImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * RelationshipElementImpl.java
- *
- * Created on March 2, 2000, 6:21 PM
- */
-
package com.sun.jdo.api.persistence.model.jdo.impl;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -45,8 +40,7 @@
/**
*
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
public class RelationshipElementImpl extends PersistenceFieldElementImpl
implements RelationshipElement.Impl
@@ -105,6 +99,7 @@ public RelationshipElementImpl (String name)
* {@link RelationshipElement#AGGREGATE_ACTION}. The default is
* NONE_ACTION.
*/
+ @Override
public int getUpdateAction () { return _updateAction; }
/** Set the update action for this relationship element.
@@ -116,6 +111,7 @@ public RelationshipElementImpl (String name)
* {@link RelationshipElement#AGGREGATE_ACTION}
* @exception ModelException if impossible
*/
+ @Override
public void setUpdateAction (int action) throws ModelException
{
Integer old = new Integer(getUpdateAction());
@@ -142,6 +138,7 @@ public void setUpdateAction (int action) throws ModelException
* {@link RelationshipElement#AGGREGATE_ACTION}. The default is
* NONE_ACTION.
*/
+ @Override
public int getDeleteAction () { return _deleteAction; }
/** Set the delete action for this relationship element.
@@ -153,6 +150,7 @@ public void setUpdateAction (int action) throws ModelException
* {@link RelationshipElement#AGGREGATE_ACTION}
* @exception ModelException if impossible
*/
+ @Override
public void setDeleteAction (int action) throws ModelException
{
Integer old = new Integer(getDeleteAction());
@@ -174,6 +172,7 @@ public void setDeleteAction (int action) throws ModelException
* @return true if the relationship should prefetch,
* false otherwise. The default is false.
*/
+ @Override
public boolean isPrefetch () { return _isPrefetch; }
/** Set whether this relationship element should prefetch or not.
@@ -181,6 +180,7 @@ public void setDeleteAction (int action) throws ModelException
* prefetch; otherwise, it is not
* @exception ModelException if impossible
*/
+ @Override
public void setPrefetch (boolean flag) throws ModelException
{
Boolean old = JavaTypeHelper.valueOf(isPrefetch());
@@ -202,12 +202,14 @@ public void setPrefetch (boolean flag) throws ModelException
* default is 0.
* @return the lower cardinality bound
*/
+ @Override
public int getLowerBound () { return _lowerBound; }
/** Set the lower cardinality bound for this relationship element.
* @param lowerBound - an integer indicating the lower cardinality bound
* @exception ModelException if impossible
*/
+ @Override
public void setLowerBound (int lowerBound) throws ModelException
{
Integer old = new Integer(getLowerBound());
@@ -230,6 +232,7 @@ public void setLowerBound (int lowerBound) throws ModelException
* Returns {@link java.lang.Integer#MAX_VALUE} for n
* @return the upper cardinality bound
*/
+ @Override
public int getUpperBound () { return _upperBound; }
/** Set the upper cardinality bound for this relationship element.
@@ -237,6 +240,7 @@ public void setLowerBound (int lowerBound) throws ModelException
* (use {@link java.lang.Integer#MAX_VALUE} for n)
* @exception ModelException if impossible
*/
+ @Override
public void setUpperBound (int upperBound) throws ModelException
{
Integer old = new Integer(getUpperBound());
@@ -258,6 +262,7 @@ public void setUpperBound (int upperBound) throws ModelException
* for this relationship element.
* @return the collection class
*/
+ @Override
public String getCollectionClass () { return _collectionClass; }
/** Set the collection class for this relationship element.
@@ -265,6 +270,7 @@ public void setUpperBound (int upperBound) throws ModelException
* collection (for example Set, List, Vector, etc.)
* @exception ModelException if impossible
*/
+ @Override
public void setCollectionClass (String collectionClass)
throws ModelException
{
@@ -287,6 +293,7 @@ public void setCollectionClass (String collectionClass)
* wrapperclass .TYPE.toString() to specify them.
* @return the element class
*/
+ @Override
public String getElementClass () { return _elementClass; }
/** Set the element class for this relationship element.
@@ -295,6 +302,7 @@ public void setCollectionClass (String collectionClass)
* wrapperclass .TYPE.toString() to specify them.
* @exception ModelException if impossible
*/
+ @Override
public void setElementClass (String elementClass) throws ModelException
{
String old = getElementClass();
@@ -320,10 +328,10 @@ public void setElementClass (String elementClass) throws ModelException
* and lookup, there may be no corresponding RelationshipElement which can
* be found.
* @return the relative name of the inverse relationship element
- * @see #getInverseRelationship
+ * @see #getInverseRelationshipName()
*/
- public String getInverseRelationshipName ()
- {
+ @Override
+ public String getInverseRelationshipName() {
return _inverseRelationshipName;
}
@@ -337,6 +345,7 @@ public String getInverseRelationshipName ()
* relationship element does not participate in a two-way relationship.
* @exception ModelException if impossible
*/
+ @Override
public void changeInverseRelationship (
RelationshipElement inverseRelationship) throws ModelException
{
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingClassElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingClassElement.java
index c72e7f57e7c..199fc2faaaf 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingClassElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingClassElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,31 +15,22 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingClassElement.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping;
import com.sun.jdo.api.persistence.model.ModelException;
-import java.util.ArrayList;
import java.util.List;
import org.netbeans.modules.dbschema.SchemaElement;
import org.netbeans.modules.dbschema.TableElement;
/**
- *
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
public interface MappingClassElement extends MappingElement
{
/** Constant representing mapping file extension. */
- public static final String MAPPING_EXTENSION = "mapping"; // NOI18N
+ public static final String MAPPING_EXTENSION = "mapping";
/** Constant representing Consistency level.
* NONE_CONSISTENCY implies that no consistency semantics are enforced.
@@ -183,14 +175,14 @@ public interface MappingClassElement extends MappingElement
* class.
* @return the meta data tables for this mapping class
*/
- public ArrayList getTables ();
+ public List getTables();
/** Scans through this mapping class looking for a table whose
* name matches the name passed in.
* @param name name of the table to find.
* @return the meta data table whose name matches the name parameter
*/
- public MappingTableElement getTable (String name);
+ public MappingTableElement getTable(String name);
/** Convenience method which accepts a table element and attempts to add
* it as either a primary or secondary table depending on the existing list
@@ -232,7 +224,7 @@ public MappingReferenceKeyElement addSecondaryTable (MappingTableElement
* class. This list includes both local and relationship fields.
* @return the mapping fields in this mapping class
*/
- public ArrayList getFields ();
+ public List getFields ();
/** Scans through this mapping class looking for a field whose
* name matches the name passed in.
@@ -258,7 +250,7 @@ public MappingReferenceKeyElement addSecondaryTable (MappingTableElement
* level is {@link #VERSION_CONSISTENCY}.
* @return the version fields in this mapping class
*/
- public List getVersionFields ();
+ public List getVersionFields ();
/** Gets the navigable flag for this mapping class.
* @return true if lazy initialization will be used,
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingElement.java
index 7272cd62fc8..692c72fa1e7 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingElement.java
@@ -32,7 +32,7 @@
* @author raccah
* @version %I%
*/
-public interface MappingElement extends MappingElementProperties, Comparable
+public interface MappingElement extends MappingElementProperties, Comparable
{
/** Add a property change listener.
* @param l the listener to add
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingFieldElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingFieldElement.java
index d93e000338e..d540b0f788e 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingFieldElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingFieldElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,24 +15,16 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingFieldElement.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping;
import com.sun.jdo.api.persistence.model.ModelException;
-import java.util.ArrayList;
+import java.util.List;
import org.netbeans.modules.dbschema.DBMemberElement;
/**
- *
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
public interface MappingFieldElement extends MappingMemberElement
{
@@ -113,7 +106,7 @@ public interface MappingFieldElement extends MappingMemberElement
* mapped.
* @return the names of the columns mapped by this mapping field
*/
- public ArrayList getColumns ();
+ public List getColumns ();
/** Adds a column to the list of columns mapped by this mapping field.
* @param column column element to be added to the mapping
@@ -127,4 +120,10 @@ public interface MappingFieldElement extends MappingMemberElement
* @exception ModelException if impossible
*/
public void removeColumn (String columnName) throws ModelException;
+
+ public boolean isMappedToTable(MappingTableElement table);
+
+ public void stripSchemaName();
+
+ public List extends DBMemberElement> getColumnObjects();
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingReferenceKeyElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingReferenceKeyElement.java
index 1eaadc862c5..5b47f9b8bf3 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingReferenceKeyElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingReferenceKeyElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,17 +15,11 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingReferenceKeyElement.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping;
import com.sun.jdo.api.persistence.model.ModelException;
-import java.util.ArrayList;
+import java.util.List;
import org.netbeans.modules.dbschema.ColumnPairElement;
import org.netbeans.modules.dbschema.ReferenceKey;
@@ -49,81 +44,99 @@
* establishes the primary to secondary relationship via the reference keys,
* and puts the pair information into the "fake foreign key".
*
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public interface MappingReferenceKeyElement
- extends MappingMemberElement, ReferenceKey
-{
- //======================= table handling ===========================
+public interface MappingReferenceKeyElement extends MappingMemberElement, ReferenceKey {
+ // ======================= table handling ===========================
- /** Returns the mapping table element for this referencing key.
+ /**
+ * Returns the mapping table element for this referencing key.
+ *
* @return the meta data table for this referencing key
*/
- public MappingTableElement getTable ();
+ MappingTableElement getTable();
- /** Set the mapping table for this referencing key to the supplied table.
+ /**
+ * Set the mapping table for this referencing key to the supplied table.
+ *
* @param table mapping table element to be used with this key.
* @exception ModelException if impossible
*/
- public void setTable (MappingTableElement table) throws ModelException;
+ void setTable(MappingTableElement table) throws ModelException;
- //======================= column handling ===========================
+ // ======================= column handling ===========================
- /** Returns the list of relative column pair names in this referencing key.
+ /**
+ * Returns the list of relative column pair names in this referencing key.
+ *
* @return the names of the column pairs in this referencing key
*/
- public ArrayList getColumnPairNames ();
+ List getColumnPairNames();
- /** Remove a column pair from the holder. This method can be used to
+ /**
+ * Remove a column pair from the holder. This method can be used to
* remove a pair by name when it cannot be resolved to an actual pair.
+ *
* @param pairName the relative name of the column pair to remove
* @throws ModelException if impossible
*/
- public void removeColumnPair (String pairName) throws ModelException;
+ void removeColumnPair(String pairName) throws ModelException;
- /** Remove some column pairs from the holder. This method can be used to
+ /**
+ * Remove some column pairs from the holder. This method can be used to
* remove pairs by name when they cannot be resolved to actual pairs.
+ *
* @param pairNames the relative names of the column pairs to remove
* @throws ModelException if impossible
*/
- public void removeColumnPairs (ArrayList pairNames) throws ModelException;
+ void removeColumnPairs(List pairNames) throws ModelException;
- //==== redefined from ReferenceKey to narrow Exception->ModelException ===
+ // ==== redefined from ReferenceKey to narrow Exception->ModelException ===
- /** Add a new column pair to the holder.
+ /**
+ * Add a new column pair to the holder.
+ *
* @param pair the pair to add
* @throws ModelException if impossible
*/
- public void addColumnPair (ColumnPairElement pair) throws ModelException;
+ @Override
+ void addColumnPair(ColumnPairElement pair) throws ModelException;
- /** Add some new column pairs to the holder.
+ /**
+ * Add some new column pairs to the holder.
+ *
* @param pairs the column pairs to add
* @throws ModelException if impossible
*/
- public void addColumnPairs (ColumnPairElement[] pairs)
- throws ModelException;
+ @Override
+ void addColumnPairs(ColumnPairElement[] pairs) throws ModelException;
- /** Remove a column pair from the holder.
+ /**
+ * Remove a column pair from the holder.
+ *
* @param pair the column pair to remove
* @throws ModelException if impossible
*/
- public void removeColumnPair (ColumnPairElement pair)
- throws ModelException;
+ @Override
+ void removeColumnPair(ColumnPairElement pair) throws ModelException;
- /** Remove some column pairs from the holder.
+ /**
+ * Remove some column pairs from the holder.
+ *
* @param pairs the column pairs to remove
* @throws ModelException if impossible
*/
- public void removeColumnPairs (ColumnPairElement[] pairs)
- throws ModelException;
+ @Override
+ void removeColumnPairs(ColumnPairElement[] pairs) throws ModelException;
- /** Set the column pairs for this holder.
+ /**
+ * Set the column pairs for this holder.
* Previous column pairs are removed.
+ *
* @param pairs the new column pairs
* @throws ModelException if impossible
*/
- public void setColumnPairs (ColumnPairElement[] pairs)
- throws ModelException;
+ @Override
+ void setColumnPairs(ColumnPairElement[] pairs) throws ModelException;
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingRelationshipElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingRelationshipElement.java
index d0efef19870..5e47ab2ccb5 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingRelationshipElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingRelationshipElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,17 +15,11 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingRelationshipElement.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping;
import com.sun.jdo.api.persistence.model.ModelException;
-import java.util.ArrayList;
+import java.util.List;
import org.netbeans.modules.dbschema.ColumnPairElement;
@@ -41,43 +36,51 @@
* the order of adding them (local first or associated first) is not
* important.
*
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public interface MappingRelationshipElement extends MappingFieldElement
-{
+public interface MappingRelationshipElement extends MappingFieldElement {
//=================== column handling for join tables ====================
- /** Returns the list of associated column names to which this
- * mapping field is mapped. This is used for join tables.
+ /**
+ * Returns the list of associated column names to which this
+ * mapping field is mapped. This is used for join tables.
+ *
* @return the names of the columns mapped by this mapping field
* @see MappingFieldElement#getColumns
*/
- public ArrayList getAssociatedColumns ();
+ List getAssociatedColumns();
- /** Adds a column to the list of columns mapped by this mapping field.
+ /**
+ * Adds a column to the list of columns mapped by this mapping field.
* Call this method instead of addColumn when mapping join
- * tables. This method is used to map between the local column and the
+ * tables. This method is used to map between the local column and the
* join table, while addAssociatedColumn is used to
* map between the join table and the foreign table.
+ *
* @param column foreign column element to be added to the mapping
* @exception ModelException if impossible
* @see MappingFieldElement#addColumn
* @see #addAssociatedColumn
*/
- public void addLocalColumn (ColumnPairElement column) throws ModelException;
+ void addLocalColumn(ColumnPairElement column) throws ModelException;
- /** Adds a column to the list of associated columns mapped by this mapping
- * field. Call this method instead of addColumn when mapping
- * join tables. This method is used to map between the join table column
+ /**
+ * Adds a column to the list of associated columns mapped by this mapping
+ * field. Call this method instead of addColumn when mapping
+ * join tables. This method is used to map between the join table column
* and the foreign table column, while addLocalColumn is used
* to map between the local table and the join table.
+ *
* @param column foreign column element to be added to the mapping
* @exception ModelException if impossible
* @see MappingFieldElement#addColumn
* @see #addLocalColumn
*/
- public void addAssociatedColumn (ColumnPairElement column)
- throws ModelException;
+ void addAssociatedColumn(ColumnPairElement column) throws ModelException;
+
+ List getAssociatedColumnObjects();
+
+ @Override
+ List getColumnObjects();
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingTableElement.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingTableElement.java
index dc674b3acbc..e179ed7f124 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingTableElement.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/MappingTableElement.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,17 +15,11 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingTableElement.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping;
import com.sun.jdo.api.persistence.model.ModelException;
-import java.util.ArrayList;
+import java.util.List;
import org.netbeans.modules.dbschema.ColumnElement;
import org.netbeans.modules.dbschema.TableElement;
@@ -53,80 +48,98 @@
* the setup is automatically part of the pair definition which makes up the
* reference key.
*
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public interface MappingTableElement extends MappingMemberElement
-{
- //======================= table handling ===========================
+public interface MappingTableElement extends MappingMemberElement {
+ // ======================= table handling ===========================
- /** Returns the name of the table element used by this mapping table.
+ /**
+ * Returns the name of the table element used by this mapping table.
+ *
* @return the table name for this mapping table
*/
- public String getTable ();
+ String getTable();
- /** Set the table element for this mapping table to the supplied table.
+ /**
+ * Set the table element for this mapping table to the supplied table.
+ *
* @param table table element to be used by the mapping table.
* @exception ModelException if impossible
*/
- public void setTable (TableElement table) throws ModelException;
+ void setTable(TableElement table) throws ModelException;
- /** Returns true if the table element used by this mapping table is equal
+ /**
+ * Returns true if the table element used by this mapping table is equal
* to the supplied table.
+ *
* @return true if table elements are equal,
- * false otherwise.
+ * false otherwise.
*/
- public boolean isEqual (TableElement table);
+ boolean isEqual(TableElement table);
- //===================== primary key handling ===========================
+ // ===================== primary key handling ===========================
- /** Returns the list of column names in the primary key for this
+ /**
+ * Returns the list of column names in the primary key for this
* mapping table.
+ *
* @return the names of the columns in the primary key for this
- * mapping table
+ * mapping table
*/
- public ArrayList getKey ();
+ List getKey();
- /** Adds a column to the primary key of columns in this mapping table.
+ /**
+ * Adds a column to the primary key of columns in this mapping table.
* This method should only be used to manipulate the key columns of the
- * primary table. The secondary table key columns should be manipulated
+ * primary table. The secondary table key columns should be manipulated
* using MappingReferenceKeyElement methods for pairs.
+ *
* @param column column element to be added
* @exception ModelException if impossible
*/
- public void addKeyColumn (ColumnElement column) throws ModelException;
+ void addKeyColumn(ColumnElement column) throws ModelException;
- /** Removes a column from the primary key of columns in this mapping table.
+ /**
+ * Removes a column from the primary key of columns in this mapping table.
* This method should only be used to manipulate the key columns of the
- * primary table. The secondary table key columns should be manipulated
+ * primary table. The secondary table key columns should be manipulated
* using MappingReferenceKeyElement methods for pairs.
+ *
* @param columnName the relative name of the column to be removed
* @exception ModelException if impossible
*/
- public void removeKeyColumn (String columnName) throws ModelException;
+ void removeKeyColumn(String columnName) throws ModelException;
- //===================== reference key handling ===========================
+ // ===================== reference key handling ===========================
- /** Returns the list of keys (MappingReferenceKeyElements) for this
+ /**
+ * Returns the list of keys (MappingReferenceKeyElements) for this
* mapping table. There will be keys for foreign keys and "fake" foreign
* keys.
+ *
* @return the reference key elements for this mapping table
*/
- public ArrayList getReferencingKeys ();
+ List getReferencingKeys();
- /** Adds a referencing key to the list of keys in this mapping table.
+ /**
+ * Adds a referencing key to the list of keys in this mapping table.
+ *
* @param referencingKey referencing key element to be added
* @exception ModelException if impossible
*/
- public void addReferencingKey (MappingReferenceKeyElement referencingKey)
- throws ModelException;
+ void addReferencingKey(MappingReferenceKeyElement referencingKey) throws ModelException;
- /** Removes the referencing key for the supplied table element from list
+ /**
+ * Removes the referencing key for the supplied table element from list
* of keys in this mapping table.
+ *
* @param table mapping table element for which to remove referencing keys
* @exception ModelException if impossible
*/
- public void removeReference (MappingTableElement table)
- throws ModelException;
+ void removeReference(MappingTableElement table) throws ModelException;
+
+ void stripSchemaName();
+
+ TableElement getTableObject();
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingClassElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingClassElementImpl.java
index 9f88d3c7bef..035b1af2604 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingClassElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingClassElementImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingClassElementImpl.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping.impl;
import com.sun.jdo.api.persistence.model.Model;
@@ -34,7 +29,6 @@
import java.beans.PropertyVetoException;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -42,6 +36,7 @@
import org.glassfish.persistence.common.I18NHelper;
import org.netbeans.modules.dbschema.ColumnElement;
import org.netbeans.modules.dbschema.DBIdentifier;
+import org.netbeans.modules.dbschema.DBMemberElement;
import org.netbeans.modules.dbschema.ForeignKeyElement;
import org.netbeans.modules.dbschema.SchemaElement;
import org.netbeans.modules.dbschema.TableElement;
@@ -50,13 +45,11 @@
/**
*
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public class MappingClassElementImpl extends MappingElementImpl
- implements MappingClassElement
-{
+public class MappingClassElementImpl extends MappingElementImpl implements MappingClassElement {
+
// used in properties bitmask, jeff will check if used
public static final int CLONE_FIELDS = 1;
public static final int CLONE_DEEP = 2;
@@ -67,8 +60,8 @@ public class MappingClassElementImpl extends MappingElementImpl
private boolean _isModified;
private int _properties;
- private ArrayList _tables; // array of MappingTableElement
- private ArrayList _fields; // array of MappingFieldElement
+ private ArrayList _tables;
+ private ArrayList _fields;
/** The current version number.
* Note: Please increment this if there are any changes in the
@@ -141,6 +134,7 @@ public MappingClassElementImpl (PersistenceClassElement element)
* the last save, NOT the version number of the memory representation.
* @return version number
*/
+ @Override
public int getVersionNumber () { return versionNo; }
/** Set the version number of this MappingClassElement.
@@ -153,6 +147,7 @@ public MappingClassElementImpl (PersistenceClassElement element)
* @see #getVersionNumber
* @return true if it is in need of updating, false otherwise
*/
+ @Override
public boolean hasOldVersionNumber ()
{
return (getVersionNumber() < CURRENT_VERSION_NO);
@@ -176,6 +171,7 @@ public static MappingClassElement forName (String name, Model model)
* @param o old value
* @param n new value
*/
+ @Override
protected final void firePropertyChange (String name, Object o, Object n)
{
// even though o == null and n == null will signify a change, that
@@ -185,8 +181,9 @@ protected final void firePropertyChange (String name, Object o, Object n)
super.firePropertyChange(name, o, n);
- if (!(PROP_MODIFIED.equals(name)) && !noChange)
+ if (!(PROP_MODIFIED.equals(name)) && !noChange) {
setModified(true);
+ }
}
/** Fires vetoable change event. This method overrides that of
@@ -197,6 +194,7 @@ protected final void firePropertyChange (String name, Object o, Object n)
* @param n new value
* @exception PropertyVetoException when the change is vetoed by a listener
*/
+ @Override
protected final void fireVetoableChange (String name, Object o, Object n)
throws PropertyVetoException
{
@@ -207,8 +205,9 @@ protected final void fireVetoableChange (String name, Object o, Object n)
super.fireVetoableChange(name, o, n);
- if (!(PROP_MODIFIED.equals(name)) && !noChange)
+ if (!(PROP_MODIFIED.equals(name)) && !noChange) {
fireVetoableChange(PROP_MODIFIED, Boolean.FALSE, Boolean.TRUE);
+ }
}
/** @return persistence class element for this mapping class element
@@ -243,6 +242,7 @@ public void setPersistenceElement (PersistenceClassElement element)
* @return true if there have been (property) changes to this
* class, false otherwise.
*/
+ @Override
public boolean isModified () { return _isModified; }
/** Set the modified flag for this mapping class to flag. This is usually
@@ -251,6 +251,7 @@ public void setPersistenceElement (PersistenceClassElement element)
* @param flag if true, this class is marked as modified;
* if false, it is marked as unmodified.
*/
+ @Override
public void setModified (boolean flag)
{
boolean oldFlag = isModified();
@@ -273,6 +274,7 @@ public void setModified (boolean flag)
* {@link #VERSION_CONSISTENCY}.
* The default is {@link #NONE_CONSISTENCY}.
*/
+ @Override
public int getConsistencyLevel () { return _consistencyLevel; }
/** Set the consistency level of this mapping class.
@@ -285,6 +287,7 @@ public void setModified (boolean flag)
* {@link #VERSION_CONSISTENCY}.
* @exception ModelException if impossible.
*/
+ @Override
public void setConsistencyLevel (int level) throws ModelException
{
Integer old = new Integer(getConsistencyLevel());
@@ -306,6 +309,7 @@ public void setConsistencyLevel (int level) throws ModelException
* database used by the tables mapped to this mapping class.
* @return the name of the database root for this mapping class
*/
+ @Override
public String getDatabaseRoot () { return _databaseRoot; }
/** Set the database root for this MappingClassElement.
@@ -314,6 +318,7 @@ public void setConsistencyLevel (int level) throws ModelException
* @param root the new database root
* @exception ModelException if impossible
*/
+ @Override
public void setDatabaseRoot (SchemaElement root) throws ModelException
{
String old = getDatabaseRoot();
@@ -335,10 +340,12 @@ public void setDatabaseRoot (SchemaElement root) throws ModelException
* class.
* @return the meta data tables for this mapping class
*/
- public ArrayList getTables ()
+ @Override
+ public List getTables ()
{
- if (_tables == null)
- _tables = new ArrayList();
+ if (_tables == null) {
+ _tables = new ArrayList<>();
+ }
return _tables;
}
@@ -348,19 +355,15 @@ public ArrayList getTables ()
* @param name name of the table to find.
* @return the meta data table whose name matches the name parameter
*/
- public MappingTableElement getTable (String name)
- {
- Iterator tableIterator = getTables().iterator();
-
- while (tableIterator.hasNext())
- {
- MappingTableElement table =
- (MappingTableElement)tableIterator.next();
-
- if (table.getName().equals(name))
+ @Override
+ public MappingTableElement getTable(String name) {
+ Iterator tableIterator = getTables().iterator();
+ while (tableIterator.hasNext()) {
+ MappingTableElement table = tableIterator.next();
+ if (table.getName().equals(name)) {
return table;
+ }
}
-
return null;
}
@@ -371,84 +374,62 @@ public MappingTableElement getTable (String name)
* table.
* @exception ModelException if impossible
*/
- public void addTable (TableElement table) throws ModelException
- {
- if (table != null)
- {
- ArrayList tables = getTables();
-
- // If the table list is empty, this should be the primary table
- if (tables.isEmpty())
- setPrimaryTable(table);
- else
- {
- HashMap newSecondaryTables = new HashMap();
- Iterator iterator = tables.iterator();
- boolean found = false;
-
- // If this table has already been added just skip it and return
- while (iterator.hasNext())
- if (((MappingTableElement)iterator.next()).isEqual(table))
- return;
-
- // Add the table as a secondary table as long as there are
- // relevant fks setup. Otherwise, throw an exception
- iterator = tables.iterator();
- while (iterator.hasNext())
- {
- MappingTableElement mappingTable =
- (MappingTableElement)iterator.next();
- String absoluteTableName = NameUtil.getAbsoluteTableName(
- _databaseRoot, mappingTable.getTable());
- ForeignKeyElement[] foreignKeys = TableElement.forName(
- absoluteTableName).getForeignKeys();
- int i, count =
- ((foreignKeys != null) ? foreignKeys.length : 0);
-
- for (i = 0; i < count; i++)
- {
- ForeignKeyElement fk = foreignKeys[i];
-
- if (table == fk.getReferencedTable())
- {
- // store it so it can be added after we finish
- // iterating the array (can't now because of
- // concurrent modification restrictions)
- newSecondaryTables.put(mappingTable, fk);
- found = true;
- }
- }
- }
-
- if (found) // add the secondary tables now
- {
- iterator = newSecondaryTables.keySet().iterator();
-
- while (iterator.hasNext())
- {
- MappingTableElement mappingTable =
- (MappingTableElement)iterator.next();
- MappingReferenceKeyElement refKey =
- addSecondaryTable(mappingTable, table);
+ @Override
+ public void addTable(TableElement table) throws ModelException {
+ if (table == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.table.null_argument"));
+ }
+ List tables = getTables();
- refKey.addColumnPairs(((ForeignKeyElement)
- newSecondaryTables.get(mappingTable)).
- getColumnPairs());
- }
+ // If the table list is empty, this should be the primary table
+ if (tables.isEmpty()) {
+ setPrimaryTable(table);
+ return;
+ }
+ Iterator iterator = tables.iterator();
+ // If this table has already been added just skip it and return
+ while (iterator.hasNext()) {
+ if (iterator.next().isEqual(table)) {
+ return;
+ }
+ }
- }
- else
- {
- throw new ModelException(I18NHelper.getMessage(
- getMessages(),
- "mapping.table.foreign_key_not_found", table)); // NOI18N
+ HashMap newSecondaryTables = new HashMap<>();
+ boolean found = false;
+ // Add the table as a secondary table as long as there are
+ // relevant fks setup. Otherwise, throw an exception
+ iterator = tables.iterator();
+ while (iterator.hasNext()) {
+ MappingTableElement mappingTable = iterator.next();
+ String absoluteTableName = NameUtil.getAbsoluteTableName(_databaseRoot, mappingTable.getTable());
+ ForeignKeyElement[] foreignKeys = TableElement.forName(absoluteTableName).getForeignKeys();
+ int i, count = ((foreignKeys != null) ? foreignKeys.length : 0);
+
+ for (i = 0; i < count; i++) {
+ ForeignKeyElement fk = foreignKeys[i];
+
+ if (table == fk.getReferencedTable()) {
+ // store it so it can be added after we finish
+ // iterating the array (can't now because of
+ // concurrent modification restrictions)
+ newSecondaryTables.put(mappingTable, fk);
+ found = true;
}
}
}
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.table.null_argument")); // NOI18N
+
+ if (!found) {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.table.foreign_key_not_found", table));
+ }
+ // add the secondary tables now
+ iterator = newSecondaryTables.keySet().iterator();
+
+ while (iterator.hasNext()) {
+ MappingTableElement mappingTable = iterator.next();
+ MappingReferenceKeyElement refKey = addSecondaryTable(mappingTable, table);
+
+ refKey.addColumnPairs(newSecondaryTables.get(mappingTable).getColumnPairs());
}
}
@@ -456,66 +437,53 @@ public void addTable (TableElement table) throws ModelException
* @param table table element to be used as the primary table.
* @exception ModelException if impossible
*/
- public void setPrimaryTable (TableElement table) throws ModelException
- {
- ArrayList tables = getTables();
+ @Override
+ public void setPrimaryTable(TableElement table) throws ModelException {
+ List tables = getTables();
- if (!tables.isEmpty())
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.table.primary_table_defined", table)); // NOI18N
+ if (!tables.isEmpty()) {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.table.primary_table_defined", table));
+ }
+ UniqueKeyElement key = table.getPrimaryKey();
+ MappingTableElement mappingTable = new MappingTableElementImpl(table, this);
+ SchemaElement schema = table.getDeclaringSchema();
+ String currentRoot = getDatabaseRoot();
+
+ if (currentRoot == null) { // set database root
+ setDatabaseRoot(schema);
+ } else if (!currentRoot.equals(schema.getName().getFullName())) {
+ // if database root was set before, it must match
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.table.schema_mismatch", table.toString(), currentRoot));
}
- else
- {
- UniqueKeyElement key = table.getPrimaryKey();
- MappingTableElement mappingTable =
- new MappingTableElementImpl(table, this);
- SchemaElement schema = table.getDeclaringSchema();
- String currentRoot = getDatabaseRoot();
-
- if (currentRoot == null) // set database root
- setDatabaseRoot(schema);
- else if (!currentRoot.equals(schema.getName().getFullName()))
- {
- // if database root was set before, it must match
- throw new ModelException(I18NHelper.getMessage(
- getMessages(), "mapping.table.schema_mismatch", // NOI18N
- table.toString(), currentRoot));
- }
-
- try
- {
- fireVetoableChange(PROP_TABLES, null, null);
- tables.add(mappingTable);
- firePropertyChange(PROP_TABLES, null, null);
- }
- catch (PropertyVetoException e)
- {
- throw new ModelVetoException(e);
- }
- // If can't find a primary key, settle for first unique key.
- if (key == null)
- {
- UniqueKeyElement[] uniqueKeys = table.getUniqueKeys();
+ try {
+ fireVetoableChange(PROP_TABLES, null, null);
+ tables.add(mappingTable);
+ firePropertyChange(PROP_TABLES, null, null);
+ } catch (PropertyVetoException e) {
+ throw new ModelVetoException(e);
+ }
- if ((uniqueKeys != null) && (uniqueKeys.length > 0))
- key = uniqueKeys[0];
+ // If can't find a primary key, settle for first unique key.
+ if (key == null) {
+ UniqueKeyElement[] uniqueKeys = table.getUniqueKeys();
+ if ((uniqueKeys != null) && (uniqueKeys.length > 0)) {
+ key = uniqueKeys[0];
}
+ }
- if (key == null)
- {
- // This is a warning -- we can still use the table but we
- // cannot perform update operations on it. Also the user
- // may define the key later.
- }
- else
- {
- ColumnElement[] columns = key.getColumns();
- int i, count = ((columns != null) ? columns.length : 0);
+ if (key == null) {
+ // This is a warning -- we can still use the table but we
+ // cannot perform update operations on it. Also the user
+ // may define the key later.
+ } else {
+ ColumnElement[] columns = key.getColumns();
+ int i, count = ((columns != null) ? columns.length : 0);
- for (i = 0; i < count; i++)
- mappingTable.addKeyColumn(columns[i]);
+ for (i = 0; i < count; i++) {
+ mappingTable.addKeyColumn(columns[i]);
}
}
}
@@ -528,56 +496,41 @@ else if (!currentRoot.equals(schema.getName().getFullName()))
* @param table table element to be used as a secondary table.
* @exception ModelException if impossible
*/
+ @Override
public MappingReferenceKeyElement addSecondaryTable (MappingTableElement
parentTable, TableElement table) throws ModelException
{
- ArrayList tables = getTables();
+ List tables = getTables();
- if ((parentTable == null) || (table == null))
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
- }
- else if (!tables.contains(parentTable))
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.table.parent_table_not_found", // NOI18N
+ if ((parentTable == null) || (table == null)) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
+ } else if (!tables.contains(parentTable)) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.table.parent_table_not_found",
parentTable.getTable()));
- }
- else
- {
+ } else {
// Check the parent table's reference keys to make sure that this
// secondary table has not already been added to this parent table.
// If it has, throw an exception
- Iterator iterator = parentTable.getReferencingKeys().iterator();
- MappingTableElement mappingTable =
- new MappingTableElementImpl(table, this);
- MappingReferenceKeyElement key =
- new MappingReferenceKeyElementImpl(mappingTable);
+ Iterator iterator = parentTable.getReferencingKeys().iterator();
+ MappingTableElement mappingTable = new MappingTableElementImpl(table, this);
+ MappingReferenceKeyElement key = new MappingReferenceKeyElementImpl(mappingTable);
- while (iterator.hasNext())
- {
- MappingTableElement compareTable =
- ((MappingReferenceKeyElement)iterator.next()).getTable();
+ while (iterator.hasNext()) {
+ MappingTableElement compareTable = iterator.next().getTable();
- if (compareTable.isEqual(table))
- {
- throw new ModelException(I18NHelper.getMessage(
- getMessages(),
- "mapping.table.secondary_table_defined", // NOI18N
- new Object[]{table, parentTable.getTable()}));
+ if (compareTable.isEqual(table)) {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.table.secondary_table_defined",
+ new Object[] {table, parentTable.getTable()}));
}
}
- try
- {
+ try {
fireVetoableChange(PROP_TABLES, null, null);
parentTable.addReferencingKey(key);
tables.add(mappingTable);
firePropertyChange(PROP_TABLES, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
@@ -591,90 +544,63 @@ else if (!tables.contains(parentTable))
* @param table mapping table element to be removed from this mapping class.
* @exception ModelException if impossible
*/
- public void removeTable (MappingTableElement table) throws ModelException
- {
- if (table != null)
- {
- Collection tables = getTables();
- Iterator iterator = null;
- boolean found = false;
-
- try
- {
- fireVetoableChange(PROP_TABLES, null, null);
- found = tables.remove(table);
- firePropertyChange(PROP_TABLES, null, null);
- }
- catch (PropertyVetoException e)
- {
- throw new ModelVetoException(e);
- }
+ @Override
+ public void removeTable(MappingTableElement table) throws ModelException {
+ if (table == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
+ }
+ List tables = getTables();
+ boolean found = false;
+
+ try {
+ fireVetoableChange(PROP_TABLES, null, null);
+ found = tables.remove(table);
+ firePropertyChange(PROP_TABLES, null, null);
+ } catch (PropertyVetoException e) {
+ throw new ModelVetoException(e);
+ }
- // remove all references to this table
- iterator = tables.iterator();
- while (iterator.hasNext())
- {
- MappingTableElement nextTable =
- (MappingTableElement)iterator.next();
+ // remove all references to this table
+ for (MappingTableElement element : tables) {
+ element.removeReference(table);
+ }
- nextTable.removeReference(table);
+ // remove any fields mapped to that table
+ if (!found) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(),
+ "mapping.element.element_not_removed", table));
+ }
+ List fieldsToRemove = new ArrayList<>();
+ for (MappingFieldElement mappingField : getFields()) {
+ if (mappingField.isMappedToTable(table)) {
+ fieldsToRemove.add(mappingField);
}
+ }
- if (found) // remove any fields mapped to that table
- {
- ArrayList fieldsToRemove = new ArrayList();
-
- iterator = getFields().iterator();
- while (iterator.hasNext())
- {
- MappingFieldElementImpl mappingField =
- (MappingFieldElementImpl)iterator.next();
-
- if (mappingField.isMappedToTable(table))
- fieldsToRemove.add(mappingField);
- }
+ for (MappingFieldElement mappingField : fieldsToRemove) {
+ boolean versionField = mappingField.isVersion();
+ removeField(mappingField);
- iterator = fieldsToRemove.iterator();
- while (iterator.hasNext())
- {
- MappingFieldElement mappingField =
- (MappingFieldElement)iterator.next();
- boolean versionField = mappingField.isVersion();
-
- removeField(mappingField);
-
- // if it is a version field, add back an unmapped
- // field which retains the version flag setting
- if (versionField)
- {
- mappingField = new MappingFieldElementImpl(
- mappingField.getName(), this);
- mappingField.setVersion(true);
- addField(mappingField);
- }
- }
- }
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.element_not_removed", table)); // NOI18N
+ // if it is a version field, add back an unmapped
+ // field which retains the version flag setting
+ if (versionField) {
+ mappingField = new MappingFieldElementImpl(mappingField.getName(), this);
+ mappingField.setVersion(true);
+ addField(mappingField);
}
}
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
- }
}
/** Returns the list of fields (MappingFieldElements) in this mapping
* class. This list includes both local and relationship fields.
* @return the mapping fields in this mapping class
*/
- public ArrayList getFields ()
+ @Override
+ public List getFields ()
{
- if (_fields == null)
- _fields = new ArrayList();
+ if (_fields == null) {
+ _fields = new ArrayList<>();
+ }
return _fields;
}
@@ -684,17 +610,16 @@ public ArrayList getFields ()
* @param name name of the field to find.
* @return the mapping field whose name matches the name parameter
*/
- public MappingFieldElement getField (String name)
- {
- Iterator fieldIterator = getFields().iterator();
+ @Override
+ public MappingFieldElement getField(String name) {
+ Iterator fieldIterator = getFields().iterator();
- while (fieldIterator.hasNext())
- {
- MappingFieldElement field =
- (MappingFieldElement)fieldIterator.next();
+ while (fieldIterator.hasNext()) {
+ MappingFieldElement field = fieldIterator.next();
- if (name.equals(field.getName()))
+ if (name.equals(field.getName())) {
return field;
+ }
}
return null;
@@ -704,20 +629,16 @@ public MappingFieldElement getField (String name)
* @param field field element to be added
* @exception ModelException if impossible
*/
- public void addField (MappingFieldElement field) throws ModelException
- {
- ArrayList fields = getFields();
+ @Override
+ public void addField(MappingFieldElement field) throws ModelException {
+ List fields = getFields();
- if (!fields.contains(field))
- {
- try
- {
+ if (!fields.contains(field)) {
+ try {
fireVetoableChange(PROP_FIELDS, null, null);
fields.add(field);
firePropertyChange(PROP_FIELDS, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -727,22 +648,18 @@ public void addField (MappingFieldElement field) throws ModelException
* @param field field element to be removed
* @exception ModelException if impossible
*/
- public void removeField (MappingFieldElement field) throws ModelException
- {
- try
- {
+ @Override
+ public void removeField(MappingFieldElement field) throws ModelException {
+ try {
fireVetoableChange(PROP_FIELDS, null, null);
- if (!getFields().remove(field))
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.element_not_removed", field)); // NOI18N
+ if (!getFields().remove(field)) {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.element.element_not_removed", field));
}
firePropertyChange(PROP_FIELDS, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -752,21 +669,19 @@ public void removeField (MappingFieldElement field) throws ModelException
* level is {@link #VERSION_CONSISTENCY}.
* @return the version fields in this mapping class
*/
- public List getVersionFields ()
- {
- List versionFields = new ArrayList();
+ @Override
+ public List getVersionFields() {
+ List versionFields = new ArrayList<>();
- if (VERSION_CONSISTENCY == getConsistencyLevel())
- {
- Iterator iterator = getFields().iterator();
+ if (VERSION_CONSISTENCY == getConsistencyLevel()) {
+ Iterator iterator = getFields().iterator();
- while (iterator.hasNext())
- {
- MappingFieldElement fieldCandidate =
- (MappingFieldElement)iterator.next();
+ while (iterator.hasNext()) {
+ MappingFieldElement fieldCandidate = iterator.next();
- if (fieldCandidate.isVersion())
+ if (fieldCandidate.isVersion()) {
versionFields.add(fieldCandidate);
+ }
}
}
@@ -778,6 +693,7 @@ public List getVersionFields ()
* false if access to a non-fetched field will result in an
* exception. The default is true.
*/
+ @Override
public boolean isNavigable () { return ((_properties & NAVIGABLE) > 0); }
/** Set the navigable flag for this mapping class to flag.
@@ -786,20 +702,15 @@ public List getVersionFields ()
* exception.
* @exception ModelException if impossible
*/
- public void setNavigable (boolean flag) throws ModelException
- {
+ @Override
+ public void setNavigable(boolean flag) throws ModelException {
Boolean old = JavaTypeHelper.valueOf(isNavigable());
Boolean newFlag = JavaTypeHelper.valueOf(flag);
-
- try
- {
+ try {
fireVetoableChange(PROP_NAVIGABLE, old, newFlag);
- _properties = (flag) ?
- (_properties | NAVIGABLE) : (_properties & ~NAVIGABLE);
+ _properties = (flag) ? (_properties | NAVIGABLE) : (_properties & ~NAVIGABLE);
firePropertyChange(PROP_NAVIGABLE, old, newFlag);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -814,22 +725,15 @@ public void setNavigable (boolean flag) throws ModelException
* @see org.netbeans.modules.dbschema.TableElement#forName
* @see org.netbeans.modules.dbschema.TableElement#getMember
*/
- protected static ArrayList toColumnObjects (String schemaName,
- ArrayList columnNames)
- {
- Iterator iterator = columnNames.iterator();
- ArrayList objects = new ArrayList();
-
- while (iterator.hasNext())
- {
- String columnName = (String)iterator.next();
- String absoluteColumnName =
- NameUtil.getAbsoluteMemberName(schemaName, columnName);
- final TableElement table =
- TableElement.forName(NameUtil.getTableName(absoluteColumnName));
-
- objects.add(table.getMember(
- DBIdentifier.create(absoluteColumnName)));
+ protected static List toColumnObjects(String schemaName, List columnNames) {
+ List objects = new ArrayList<>();
+ Iterator iterator = columnNames.iterator();
+ while (iterator.hasNext()) {
+ String columnName = iterator.next();
+ String absoluteColumnName = NameUtil.getAbsoluteMemberName(schemaName, columnName);
+ final TableElement table = TableElement.forName(NameUtil.getTableName(absoluteColumnName));
+
+ objects.add((T) table.getMember(DBIdentifier.create(absoluteColumnName)));
}
return objects;
@@ -846,8 +750,7 @@ protected static ArrayList toColumnObjects (String schemaName,
* @see PersistenceClassElement#APPLICATION_IDENTITY
*
*/
- public String getKeyClass ()
- {
+ public String getKeyClass() {
return getPersistenceElement().getKeyClass();
}
@@ -868,9 +771,13 @@ public String getKeyClass ()
* and archiving.
* @param fields the list of mapping fields in this mapping class
*/
- public void setFields (ArrayList fields) { _fields = fields; }
+ public void setFields(ArrayList fields) {
+ _fields = fields;
+ }
- public int getProperties () { return _properties; }
+ public int getProperties() {
+ return _properties;
+ }
//======== to be used for reference in best guess implementation ==========
// configure methods
@@ -1048,6 +955,7 @@ else if ( finderClassName.equals(this.DEFAULT_JAVA_FINDERCLASS) )
* (version number checking) and conversion after unarchiving.
* @exception ModelException if impossible
*/
+ @Override
public void postUnarchive () throws ModelException
{
// check version number
@@ -1079,6 +987,7 @@ public void postUnarchive () throws ModelException
* includes a throws clause (ModelException), but the actual implementation
* does not throw an exception.
*/
+ @Override
public void preArchive ()
{
// update version number
@@ -1102,7 +1011,7 @@ protected void stripSchemaName ()
if (_tables != null && !_tables.isEmpty())
{
schemaName = NameUtil.getSchemaName(
- ((MappingTableElement)_tables.get(0)).getTable());
+ _tables.get(0).getTable());
}
// set the schemaName as database root
@@ -1113,17 +1022,19 @@ protected void stripSchemaName ()
// handle _tables
if (_tables != null)
{
- Iterator i = _tables.iterator();
- while (i.hasNext())
- ((MappingTableElementImpl)i.next()).stripSchemaName();
+ Iterator i = _tables.iterator();
+ while (i.hasNext()) {
+ i.next().stripSchemaName();
+ }
}
// handle _fields
if (_fields != null)
{
- Iterator i = _fields.iterator();
- while (i.hasNext())
- ((MappingFieldElementImpl)i.next()).stripSchemaName();
+ Iterator i = _fields.iterator();
+ while (i.hasNext()) {
+ i.next().stripSchemaName();
+ }
}
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingElementImpl.java
index 6dfc27fb9d2..63062748e15 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingElementImpl.java
@@ -81,6 +81,7 @@ public MappingElementImpl (String name)
* of this mapping element.
* @return a string representation of the object
*/
+ @Override
public String toString () { return getName(); }
/** Overrides Object's equals method by comparing the name of this mapping element
@@ -89,20 +90,24 @@ public MappingElementImpl (String name)
* @return true if this object is the same as the obj argument; false otherwise.
* @param obj the reference object with which to compare.
*/
+ @Override
public boolean equals(Object obj)
{
- if (obj == null)
+ if (obj == null) {
return false;
- if (obj == this)
+ }
+ if (obj == this) {
return true;
+ }
// check for the right class and then do the name check by calling compareTo.
- return (getClass() == obj.getClass()) && (compareTo(obj) == 0);
+ return (getClass() == obj.getClass()) && (compareTo((MappingElement) obj) == 0);
}
/** Overrides Object's hashCode method to return the hashCode of this mapping element's name.
* @return a hash code value for this object.
*/
+ @Override
public int hashCode()
{
return (getName()==null) ? 0 : getName().hashCode();
@@ -115,8 +120,9 @@ public int hashCode()
*/
protected void firePropertyChange (String name, Object o, Object n)
{
- if (_support != null)
+ if (_support != null) {
_support.firePropertyChange(name, o, n);
+ }
}
/** Fires vetoable change event.
@@ -128,8 +134,9 @@ protected void firePropertyChange (String name, Object o, Object n)
protected void fireVetoableChange (String name, Object o, Object n)
throws PropertyVetoException
{
- if (_vetoableSupport != null)
+ if (_vetoableSupport != null) {
_vetoableSupport.fireVetoableChange(name, o, n);
+ }
}
//================= implementation of MappingElement ================
@@ -137,12 +144,14 @@ protected void fireVetoableChange (String name, Object o, Object n)
/** Add a property change listener.
* @param l the listener to add
*/
+ @Override
public synchronized void addPropertyChangeListener
(PropertyChangeListener l)
{
// new test under synchronized block
- if (_support == null)
+ if (_support == null) {
_support = new PropertyChangeSupport(this);
+ }
_support.addPropertyChangeListener(l);
@@ -151,20 +160,24 @@ protected void fireVetoableChange (String name, Object o, Object n)
/** Remove a property change listener.
* @param l the listener to remove
*/
+ @Override
public void removePropertyChangeListener (PropertyChangeListener l)
{
- if (_support != null)
+ if (_support != null) {
_support.removePropertyChangeListener(l);
+ }
}
/** Add a vetoable change listener.
* @param l the listener to add
*/
+ @Override
public synchronized void addVetoableChangeListener
(VetoableChangeListener l)
{
- if (_vetoableSupport == null)
+ if (_vetoableSupport == null) {
_vetoableSupport = new VetoableChangeSupport(this);
+ }
_vetoableSupport.addVetoableChangeListener(l);
}
@@ -172,22 +185,26 @@ public void removePropertyChangeListener (PropertyChangeListener l)
/** Remove a vetoable change listener.
* @param l the listener to remove
*/
+ @Override
public synchronized void removeVetoableChangeListener (
VetoableChangeListener l)
{
- if (_vetoableSupport != null)
+ if (_vetoableSupport != null) {
_vetoableSupport.removeVetoableChangeListener(l);
+ }
}
/** Get the name of this mapping element.
* @return the name
*/
+ @Override
public String getName () { return _name; }
/** Set the name of this mapping element.
* @param name the name
* @exception ModelException if impossible
*/
+ @Override
public void setName (String name) throws ModelException
{
String old = getName();
@@ -217,30 +234,36 @@ public void setName (String name) throws ModelException
* or greater than the specified object.
* @exception ClassCastException - if the specified object is null or is not an instance of MappingElementImpl
*/
- public int compareTo(Object o)
+ @Override
+ public int compareTo(MappingElement o)
{
// null is not allowed
- if (o == null)
+ if (o == null) {
throw new ClassCastException();
- if (o == this)
+ }
+ if (o == this) {
return 0;
+ }
String thisName = getName();
// the following statement throws a ClassCastException if o is not a MappingElementImpl
String otherName = ((MappingElementImpl)o).getName();
// if this does not have a name it should compare less than any named object
- if (thisName == null)
+ if (thisName == null) {
return (otherName == null) ? 0 : -1;
+ }
// if this is named and o does not have a name it should compare greater
- if (otherName == null)
+ if (otherName == null) {
return 1;
+ }
// now we know that this and o are named mapping elements =>
// use locale-sensitive String comparison
int ret = Collator.getInstance().compare(thisName, otherName);
// if both names are equal, both objects might have different types.
// If so order both objects by their type names (necessary to be consistent with equals)
- if ((ret == 0) && (getClass() != o.getClass()))
+ if ((ret == 0) && (getClass() != o.getClass())) {
ret = getClass().getName().compareTo(o.getClass().getName());
+ }
return ret;
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingFieldElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingFieldElementImpl.java
index 72ee4d15074..38820de906c 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingFieldElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingFieldElementImpl.java
@@ -35,25 +35,24 @@
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
-import java.util.ListIterator;
+import java.util.List;
import org.glassfish.persistence.common.I18NHelper;
import org.netbeans.modules.dbschema.DBMemberElement;
import org.netbeans.modules.dbschema.util.NameUtil;
/**
- *
* @author Mark Munro
* @author Rochelle Raccah
* @version %I%
*/
-public class MappingFieldElementImpl extends MappingMemberElementImpl
- implements MappingFieldElement
-{
- private ArrayList _columns; // array of member names (columns or pairs)
+public class MappingFieldElementImpl extends MappingMemberElementImpl implements MappingFieldElement {
+ // array of member names (columns or pairs)
+ private List _columns;
- //@olsen: made transient to prevent from serializing into mapping files
- private transient ArrayList _columnObjects; // array of DBMemberElement (for runtime)
+ // transient to prevent from serializing into mapping files
+ // array of DBMemberElement (for runtime)
+ private transient List extends DBMemberElement> _columnObjects;
private int _fetchGroup;
private int _properties;
@@ -81,60 +80,52 @@ public class MappingFieldElementImpl extends MappingMemberElementImpl
* declaring class. This constructor should only be used for cloning and
* archiving.
*/
- public MappingFieldElementImpl ()
- {
+ public MappingFieldElementImpl() {
this(null, null);
}
- /** Create new MappingFieldElementImpl with the corresponding name and
+
+ /**
+ * Create new MappingFieldElementImpl with the corresponding name and
* declaring class.
+ *
* @param name the name of the element
* @param declaringClass the class to attach to
*/
- public MappingFieldElementImpl (String name,
- MappingClassElement declaringClass)
- {
+ public MappingFieldElementImpl(String name, MappingClassElement declaringClass) {
super(name, declaringClass);
setFetchGroupInternal(GROUP_DEFAULT);
}
-// TBD?
-/* public boolean mapped ()
- {
- ArrayList columns = getColumns();
-
- return ((columns != null) && (columns.size() > 0));
- }
-
- public void clear () { _columns = null; }*/
-// end TBD
-
- //=================== properties exposed in interface ==================
-
- /** Determines whether this field element is read only or not.
+ /**
+ * Determines whether this field element is read only or not.
+ *
* @return true if the field is read only,
- * false otherwise
+ * false otherwise
*/
- public boolean isReadOnly () { return getProperty(READ_ONLY); }
+ @Override
+ public boolean isReadOnly() {
+ return getProperty(READ_ONLY);
+ }
- /** Set whether this field element is read only or not.
+
+ /**
+ * Set whether this field element is read only or not.
+ *
* @param flag - if true, the field element is marked as
- * read only; otherwise, it is not
+ * read only; otherwise, it is not
* @exception ModelException if impossible
*/
- public void setReadOnly (boolean flag) throws ModelException
- {
+ @Override
+ public void setReadOnly(boolean flag) throws ModelException {
Boolean old = JavaTypeHelper.valueOf(isReadOnly());
Boolean newFlag = JavaTypeHelper.valueOf(flag);
- try
- {
+ try {
fireVetoableChange(PROP_READ_ONLY, old, newFlag);
setProperty(flag, READ_ONLY);
firePropertyChange(PROP_READ_ONLY, old, newFlag);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -143,8 +134,8 @@ public void setReadOnly (boolean flag) throws ModelException
* @return true if the field is in a concurrency check,
* false otherwise
*/
- public boolean isInConcurrencyCheck ()
- {
+ @Override
+ public boolean isInConcurrencyCheck() {
return getProperty(IN_CONCURRENCY_CHECK);
}
@@ -153,59 +144,67 @@ public boolean isInConcurrencyCheck ()
* being in a concurrency check; otherwise, it is not
* @exception ModelException if impossible
*/
- public void setInConcurrencyCheck (boolean flag) throws ModelException
- {
+ @Override
+ public void setInConcurrencyCheck(boolean flag) throws ModelException {
Boolean old = JavaTypeHelper.valueOf(isInConcurrencyCheck());
Boolean newFlag = JavaTypeHelper.valueOf(flag);
- try
- {
+ try {
fireVetoableChange(PROP_IN_CONCURRENCY_CHECK, old, newFlag);
setProperty(flag, IN_CONCURRENCY_CHECK);
firePropertyChange(PROP_IN_CONCURRENCY_CHECK, old, newFlag);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
- /** Determines whether this field element is a version field or not.
+
+ /**
+ * Determines whether this field element is a version field or not.
+ *
* @return true if the field is a version field,
- * false otherwise
+ * false otherwise
*/
- public boolean isVersion () { return _isVersion; }
+ @Override
+ public boolean isVersion() {
+ return _isVersion;
+ }
+
- /** Set whether this field element is a version field or not.
+ /**
+ * Set whether this field element is a version field or not.
+ *
* @param flag - if true, the field element is marked
- * as a version field; otherwise, it is not
+ * as a version field; otherwise, it is not
* @exception ModelException if impossible
*/
- public void setVersion (boolean flag) throws ModelException
- {
+ @Override
+ public void setVersion(boolean flag) throws ModelException {
Boolean old = JavaTypeHelper.valueOf(isVersion());
Boolean newFlag = JavaTypeHelper.valueOf(flag);
- try
- {
+ try {
fireVetoableChange(PROP_VERSION_FIELD, old, newFlag);
_isVersion = flag;
firePropertyChange(PROP_VERSION_FIELD, old, newFlag);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
- //======================= fetch group handling ======================
+ // ======================= fetch group handling ======================
+
/** Get the fetch group of this field element.
* @return the fetch group, one of {@link #GROUP_DEFAULT},
* {@link #GROUP_NONE}, or anything less than or equal to
* {@link #GROUP_INDEPENDENT}
*/
- public int getFetchGroup () { return _fetchGroup; }
+ @Override
+ public int getFetchGroup() {
+ return _fetchGroup;
+ }
+
/** Set the fetch group of this field element.
* @param group - an integer indicating the fetch group, one of:
@@ -213,19 +212,16 @@ public void setVersion (boolean flag) throws ModelException
* equal to {@link #GROUP_INDEPENDENT}
* @exception ModelException if impossible
*/
- public void setFetchGroup (int group) throws ModelException
- {
- Integer old = new Integer(getFetchGroup());
- Integer newGroup = new Integer(group);
+ @Override
+ public void setFetchGroup(int group) throws ModelException {
+ Integer old = Integer.valueOf(getFetchGroup());
+ Integer newGroup = Integer.valueOf(group);
- try
- {
+ try {
fireVetoableChange(PROP_FETCH_GROUP, old, newGroup);
setFetchGroupInternal(group);
firePropertyChange(PROP_FETCH_GROUP, old, newGroup);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -237,62 +233,55 @@ public void setFetchGroup (int group) throws ModelException
* {@link #GROUP_DEFAULT}, {@link #GROUP_NONE}, or anything less than or
* equal to {@link #GROUP_INDEPENDENT}
*/
- protected void setFetchGroupInternal (int group)
- {
+ protected void setFetchGroupInternal(int group) {
_fetchGroup = group;
}
- //========================== column handling ==========================
+ // ========================== column handling ==========================
- /** Returns the list of column names to which this mapping field is
+
+ /**
+ * Returns the list of column names to which this mapping field is
* mapped.
+ *
* @return the names of the columns mapped by this mapping field
*/
- public ArrayList getColumns ()
- {
- if (_columns == null)
- _columns = new ArrayList();
+ @Override
+ public List getColumns() {
+ if (_columns == null) {
+ _columns = new ArrayList<>();
+ }
return _columns;
}
+
/** Adds a column to the list of columns mapped by this mapping field.
* @param column column element to be added to the mapping
* @exception ModelException if impossible
*/
- public void addColumn (DBMemberElement column) throws ModelException
- {
- if (column != null)
- {
- ArrayList columns = getColumns();
- String columnName = NameUtil.getRelativeMemberName(
- column.getName().getFullName());
-
- if (!columns.contains(columnName))
- {
- try
- {
+ @Override
+ public void addColumn(DBMemberElement column) throws ModelException {
+ if (column != null) {
+ List columns = getColumns();
+ String columnName = NameUtil.getRelativeMemberName(column.getName().getFullName());
+
+ if (!columns.contains(columnName)) {
+ try {
fireVetoableChange(PROP_COLUMNS, null, null);
columns.add(columnName);
firePropertyChange(PROP_COLUMNS, null, null);
// sync up runtime's object list too
_columnObjects = null;
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
- }
- else
- {
+ } else {
// this part was blank -- do we want an error or skip here?
}
- }
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
+ } else {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
}
}
@@ -303,45 +292,38 @@ public void addColumn (DBMemberElement column) throws ModelException
* the mapping
* @exception ModelException if impossible
*/
- public void removeColumn (String columnName) throws ModelException
- {
- if (columnName != null)
- {
- try
- {
+ @Override
+ public void removeColumn(String columnName) throws ModelException {
+ if (columnName != null) {
+ try {
fireVetoableChange(PROP_COLUMNS, null, null);
- if (!getColumns().remove(columnName))
- {
+ if (!getColumns().remove(columnName)) {
throw new ModelException(
- I18NHelper.getMessage(getMessages(),
- "mapping.element.element_not_removed", // NOI18N
- columnName));
+ I18NHelper.getMessage(getMessages(), "mapping.element.element_not_removed", columnName));
}
firePropertyChange(PROP_COLUMNS, null, null);
// sync up runtime's object list too
_columnObjects = null;
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
}
- protected boolean isMappedToTable (MappingTableElement table)
- {
+ @Override
+ public boolean isMappedToTable(MappingTableElement table) {
String tableName = table.getName();
- Iterator iterator = getColumns().iterator();
+ Iterator iterator = getColumns().iterator();
- while (iterator.hasNext())
- {
+ while (iterator.hasNext()) {
String columnName = iterator.next().toString();
- if (NameUtil.getTableName(columnName).equals(tableName))
+ if (NameUtil.getTableName(columnName).equals(tableName)) {
return true;
+ }
}
return false;
@@ -353,134 +335,138 @@ protected boolean isMappedToTable (MappingTableElement table)
* field is mapped. This method should only be used by the runtime.
* @return the columns mapped by this mapping field
*/
- public ArrayList getColumnObjects ()
- {
- //@olsen: compute objects on access
- if (_columnObjects == null)
- {
- //@olsen: calculate the column objects based on
- // the column names as stored in _columns
- //_columnObjects = new ArrayList();
- _columnObjects = MappingClassElementImpl.toColumnObjects(
- getDeclaringClass().getDatabaseRoot(), getColumns());
+ @Override
+ public List extends DBMemberElement> getColumnObjects() {
+ // @olsen: compute objects on access
+ if (_columnObjects == null) {
+ // @olsen: calculate the column objects based on
+ // the column names as stored in _columns
+ // _columnObjects = new ArrayList();
+ String databaseRoot = getDeclaringClass().getDatabaseRoot();
+ _columnObjects = MappingClassElementImpl.toColumnObjects(databaseRoot, getColumns());
}
return _columnObjects;
}
- //============= delegation to PersistenceFieldElement ===========
-
- final PersistenceFieldElement getPersistenceFieldElement ()
- {
- return ((MappingClassElementImpl)getDeclaringClass()).
- getPersistenceElement().getField(getName());
+ final PersistenceFieldElement getPersistenceFieldElement() {
+ return ((MappingClassElementImpl) getDeclaringClass()).getPersistenceElement().getField(getName());
}
- /** Computes the field number of this field element.
+
+ /**
+ * Computes the field number of this field element.
+ *
* @return the field number of this field
*/
- public int getFieldNumber ()
- {
+ public int getFieldNumber() {
return getPersistenceFieldElement().getFieldNumber();
}
- /** Returns the array of concurrency groups to which this field belongs.
+
+ /**
+ * Returns the array of concurrency groups to which this field belongs.
+ *
* @return the concurrency groups in which this field participates
* @see PersistenceClassElement#getConcurrencyGroups
*/
- public ConcurrencyGroupElement[] getConcurrencyGroups ()
- {
+ public ConcurrencyGroupElement[] getConcurrencyGroups() {
return getPersistenceFieldElement().getConcurrencyGroups();
}
- //================ convenience methods for properties bits ===============
+ private boolean getProperty(int propertyBit) {
+ return (getProperties() & propertyBit) > 0;
+ }
+
- private boolean getProperty (int propertyBit)
- {
- return ((getProperties() & propertyBit) > 0);
+ public void setProperty(boolean flag, int propertyBit) {
+ _properties = (flag) ? (_properties | propertyBit) : (_properties & ~propertyBit);
}
- public void setProperty (boolean flag, int propertyBit)
- {
- _properties =
- (flag) ? (_properties | propertyBit) : (_properties & ~propertyBit);
+ // ================= properties not available in interface ================
+
+
+ public int getProperties() {
+ return _properties;
}
- //================= properties not available in interface ================
- public int getProperties () { return _properties;}
+ public boolean getLogOnAccess() {
+ return getProperty(LOG_ON_ACCESS);
+ }
- public boolean getLogOnAccess () { return getProperty(LOG_ON_ACCESS); }
- public void setLogOnAccess (boolean flag)
- {
+ public void setLogOnAccess(boolean flag) {
setProperty(flag, LOG_ON_ACCESS);
}
- public boolean getLogOnUpdate () { return getProperty(LOG_ON_UPDATE); }
- public void setLogOnUpdate (boolean flag)
- {
+ public boolean getLogOnUpdate() {
+ return getProperty(LOG_ON_UPDATE);
+ }
+
+
+ public void setLogOnUpdate(boolean flag) {
setProperty(flag, LOG_ON_UPDATE);
}
- public boolean getObserveOnAccess ()
- {
+
+ public boolean getObserveOnAccess() {
return getProperty(OBSERVE_ON_ACCESS);
}
- public void setObserveOnAccess (boolean flag)
- {
+
+ public void setObserveOnAccess(boolean flag) {
setProperty(flag, OBSERVE_ON_ACCESS);
}
- public boolean getRecordOnUpdate ()
- {
+
+ public boolean getRecordOnUpdate() {
return getProperty(RECORD_ON_UPDATE);
}
- public void setRecordOnUpdate (boolean flag)
- {
+
+ public void setRecordOnUpdate(boolean flag) {
setProperty(flag, RECORD_ON_UPDATE);
}
- public boolean getModifyBeforeImageOnUpdate ()
- {
+
+ public boolean getModifyBeforeImageOnUpdate() {
return getProperty(MOD_BI_ON_UPDATE);
}
- public void setModifyBeforeImageOnUpdate (boolean flag)
- {
+
+ public void setModifyBeforeImageOnUpdate(boolean flag) {
setProperty(flag, MOD_BI_ON_UPDATE);
}
- public boolean getReferentialIntegrityUpdates ()
- {
+
+ public boolean getReferentialIntegrityUpdates() {
return getProperty(REF_INTEGRITY_UPDATES);
}
- public void setReferentialIntegrityUpdates (boolean flag)
- {
+
+ public void setReferentialIntegrityUpdates(boolean flag) {
setProperty(flag, REF_INTEGRITY_UPDATES);
}
- public boolean getSendBeforeImage ()
- {
+
+ public boolean getSendBeforeImage() {
return getProperty(SEND_BEFORE_IMAGE);
}
- public void setSendBeforeImage (boolean flag)
- {
+
+
+ public void setSendBeforeImage(boolean flag) {
setProperty(flag, SEND_BEFORE_IMAGE);
}
- public int getCloneDepth () { return (_properties & CLONE_MASK); }
- public void setCloneDepth (int cloneDepth)
- {
- if (cloneDepth < CLONE_FIELD || cloneDepth > CLONE_DEEP)
- {
- }
+ public int getCloneDepth() {
+ return (_properties & CLONE_MASK);
+ }
+
+ public void setCloneDepth(int cloneDepth) {
_properties = _properties & ~CLONE_MASK | cloneDepth;
}
@@ -489,17 +475,15 @@ public void setCloneDepth (int cloneDepth)
/** Boston to Pilsen conversion.
* This method converts the absolute column names to relative names.
*/
- protected void stripSchemaName ()
- {
- if (_columns != null) // handle _columns
- {
+ @Override
+ public void stripSchemaName() {
+ if (_columns != null) {
// Use ListIterator here, because I want to replace the value
- // stored in the ArrayList. The ListIterator returned by
+ // stored in the ArrayList. The ListIterator returned by
// ArrayList.listIterator() supports the set method.
- ListIterator i = _columns.listIterator();
-
- while (i.hasNext())
- i.set(NameUtil.getRelativeMemberName((String)i.next()));
+ while (_columns.listIterator().hasNext()) {
+ _columns.listIterator().set(NameUtil.getRelativeMemberName(_columns.listIterator().next()));
+ }
}
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingReferenceKeyElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingReferenceKeyElementImpl.java
index 798958abbed..fe3cf9630a5 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingReferenceKeyElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingReferenceKeyElementImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingReferenceKeyElementImpl.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping.impl;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -29,6 +24,7 @@
import java.beans.PropertyVetoException;
import java.util.ArrayList;
+import java.util.List;
import java.util.ListIterator;
import org.glassfish.persistence.common.I18NHelper;
@@ -39,106 +35,121 @@
import org.netbeans.modules.dbschema.util.NameUtil;
/**
- *
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public class MappingReferenceKeyElementImpl extends MappingMemberElementImpl
- implements MappingReferenceKeyElement
-{
- private ArrayList _referencingKey; // array of column names
+public class MappingReferenceKeyElementImpl extends MappingMemberElementImpl implements MappingReferenceKeyElement {
+
+ // array of column names
+ private List _referencingKey;
private MappingTableElement _table;
- /** Create new MappingReferenceKeyElementImpl with no corresponding name.
+ /**
+ * Create new MappingReferenceKeyElementImpl with no corresponding name.
* This constructor should only be used for cloning and archiving.
*/
- public MappingReferenceKeyElementImpl ()
- {
- this((String)null);
+ public MappingReferenceKeyElementImpl() {
+ this((String) null);
}
- /** Creates new MappingReferenceKeyElementImpl with the corresponding name
+
+ /**
+ * Creates new MappingReferenceKeyElementImpl with the corresponding name
+ *
* @param name the name of the element
*/
- public MappingReferenceKeyElementImpl (String name)
- {
+ public MappingReferenceKeyElementImpl(String name) {
super(name, null);
}
- /** Creates new MappingReferenceKeyElementImpl with a corresponding
+
+ /**
+ * Creates new MappingReferenceKeyElementImpl with a corresponding
* mapping table.
+ *
* @param table mapping table element to be used with this key.
*/
- public MappingReferenceKeyElementImpl (MappingTableElement table)
- throws ModelException
- {
+ public MappingReferenceKeyElementImpl(MappingTableElement table) throws ModelException {
super(table.getName(), table.getDeclaringClass());
setTableInternal(table);
}
- /** Get the name of this element.
+
+ /**
+ * Get the name of this element.
+ *
* @return the name
*/
- public String getKeyName () { return getName(); }
+ @Override
+ public String getKeyName() {
+ return getName();
+ }
+
- /** Set the name of this element.
+ /**
+ * Set the name of this element.
+ *
* @param name the name
* @throws ModelException if impossible
*/
- public void setKeyName (String name) throws ModelException
- {
+ @Override
+ public void setKeyName(String name) throws ModelException {
setName(name.toString());
}
//======================= table handling ===========================
- /** Returns the mapping table element for this referencing key.
+
+ /**
+ * Returns the mapping table element for this referencing key.
+ *
* @return the meta data table for this referencing key
*/
- public MappingTableElement getTable () { return _table; }
+ @Override
+ public MappingTableElement getTable() {
+ return _table;
+ }
- /** Set the mapping table for this referencing key to the supplied table.
+
+ /**
+ * Set the mapping table for this referencing key to the supplied table.
+ *
* @param table mapping table element to be used with this key.
* @exception ModelException if impossible
*/
- public void setTable (MappingTableElement table) throws ModelException
- {
+ @Override
+ public void setTable(MappingTableElement table) throws ModelException {
MappingTableElement old = getTable();
- try
- {
+ try {
fireVetoableChange(PROP_TABLE, old, table);
setTableInternal(table);
firePropertyChange(PROP_TABLE, old, table);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
+
/** Set the mapping table for this referencing key to the supplied table
* without firing any property change events.
* @param table mapping table element to be used with this key.
* @exception ModelException if impossible
*/
- private void setTableInternal (MappingTableElement table)
- throws ModelException
- {
- if (table == null)
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
+ private void setTableInternal(MappingTableElement table) throws ModelException {
+ if (table == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
}
_table = table;
- if (null == getDeclaringClass())
+ if (null == getDeclaringClass()) {
_declaringClass = table.getDeclaringClass();
+ }
- if (null == getName())
+ if (null == getName()) {
_name = table.getName();
+ }
}
/** Get the declaring table. This method is provided as part of
@@ -147,30 +158,25 @@ private void setTableInternal (MappingTableElement table)
* @return the table that owns this reference key element, or
* null if the element is not attached to any table
*/
- public TableElement getDeclaringTable ()
- {
- ArrayList locals = getReferencingKey();
-
- if ((locals != null) && (locals.size() > 0))
- {
- String absoluteName = NameUtil.getAbsoluteMemberName(
- getDeclaringClass().getDatabaseRoot(),
- locals.get(0).toString());
-
- return TableElement.forName(NameUtil.getTableName(absoluteName));
+ @Override
+ public TableElement getDeclaringTable() {
+ List locals = getReferencingKey();
+ if (locals == null || locals.isEmpty()) {
+ return null;
}
-
- return null;
+ String absoluteName = NameUtil.getAbsoluteMemberName(getDeclaringClass().getDatabaseRoot(), locals.get(0));
+ return TableElement.forName(NameUtil.getTableName(absoluteName));
}
+
/** Set the mapping table for this referencing key to the mapping table
* based on the name of the supplied table. This method is provided as
* part of the implementation of the ReferenceKey interface but should
* only be used when a ReferenceKey object is used or by the runtime.
* @param tableElement mapping table element to be used with this key.
*/
- public void setDeclaringTable (TableElement tableElement)
- {
+ @Override
+ public void setDeclaringTable(TableElement tableElement) {
throw new UnsupportedOperationException();
}
@@ -180,12 +186,13 @@ public void setDeclaringTable (TableElement tableElement)
* the runtime.
* @return the referenced table
*/
- public TableElement getReferencedTable ()
- {
+ @Override
+ public TableElement getReferencedTable() {
ColumnPairElement[] columnPairs = getColumnPairs();
- if ((columnPairs != null) && (columnPairs.length > 0))
+ if ((columnPairs != null) && (columnPairs.length > 0)) {
return columnPairs[0].getReferencedColumn().getDeclaringTable();
+ }
return null;
}
@@ -197,26 +204,30 @@ public TableElement getReferencedTable ()
* getColumnPairNames method.
* @return the names of the columns in this referencing key
*/
- private ArrayList getReferencingKey ()
- {
- if (_referencingKey == null)
- _referencingKey = new ArrayList();
+ private List getReferencingKey() {
+ if (_referencingKey == null) {
+ _referencingKey = new ArrayList<>();
+ }
return _referencingKey;
}
- /** Returns the list of relative column pair names in this referencing key.
+
+ /**
+ * Returns the list of relative column pair names in this referencing key.
+ *
* @return the names of the column pairs in this referencing key
*/
- public ArrayList getColumnPairNames ()
- {
- ArrayList locals = getReferencingKey();
- ArrayList foreigns = getTable().getKey();
+ @Override
+ public List getColumnPairNames() {
+ List locals = getReferencingKey();
+ List foreigns = getTable().getKey();
int i, count = ((locals != null) ? locals.size() : 0);
- ArrayList pairs = new ArrayList();
+ List pairs = new ArrayList<>();
- for (i = 0; i < count; i++)
- pairs.add(locals.get(i) + ";" + foreigns.get(i)); // NOI18N
+ for (i = 0; i < count; i++) {
+ pairs.add(locals.get(i) + ";" + foreigns.get(i));
+ }
return pairs;
}
@@ -226,45 +237,40 @@ public ArrayList getColumnPairNames ()
* which to look
* @return the index of the column pair or -1 if not found
*/
- private int getIndexOfColumnPair (String searchPairName)
- {
- ArrayList myPairs = getColumnPairNames();
- int count = ((myPairs != null) ? myPairs.size() : 0);
-
- if (count > 0)
- {
+ private int getIndexOfColumnPair(String searchPairName) {
+ List myPairs = getColumnPairNames();
+ int count = myPairs == null ? 0 : myPairs.size();
+ if (count > 0) {
int i;
- for (i = 0; i < count; i++)
- {
- if (myPairs.get(i).equals(searchPairName))
+ for (i = 0; i < count; i++) {
+ if (myPairs.get(i).equals(searchPairName)) {
return i;
+ }
}
}
return -1;
}
- /** Adds a column to the list of key columns in this referencing key.
+
+ /**
+ * Adds a column to the list of key columns in this referencing key.
* This method is only called privately from addColumnPairs and assumes
* that the column is not null.
+ *
* @param column column element to be added
* @exception ModelException if impossible
*/
- private void addKeyColumn (ColumnElement column) throws ModelException
- {
- ArrayList referencingKey = getReferencingKey();
- String columnName = NameUtil.getRelativeMemberName(
- column.getName().getFullName());
+ private void addKeyColumn(ColumnElement column) throws ModelException {
+ List referencingKey = getReferencingKey();
+ String columnName = NameUtil.getRelativeMemberName(column.getName().getFullName());
- try
- {
+ try {
fireVetoableChange(PROP_KEY_COLUMNS, null, null);
referencingKey.add(columnName);
firePropertyChange(PROP_KEY_COLUMNS, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -275,15 +281,14 @@ private void addKeyColumn (ColumnElement column) throws ModelException
* the runtime.
* @return the columns
*/
- public ColumnElement[] getLocalColumns ()
- {
+ @Override
+ public ColumnElement[] getLocalColumns() {
ColumnPairElement[] columnPairs = getColumnPairs();
- int i, count = ((columnPairs != null) ? columnPairs.length : 0);
+ int i, count = columnPairs == null ? 0 : columnPairs.length;
ColumnElement[] columns = new ColumnElement[count];
-
- for (i = 0; i < count ; i++)
+ for (i = 0; i < count; i++) {
columns[i] = columnPairs[i].getLocalColumn();
-
+ }
return columns;
}
@@ -293,14 +298,16 @@ public ColumnElement[] getLocalColumns ()
* the runtime.
* @return the columns
*/
+ @Override
public ColumnElement[] getReferencedColumns ()
{
ColumnPairElement[] columnPairs = getColumnPairs();
int i, count = ((columnPairs != null) ? columnPairs.length : 0);
ColumnElement[] columns = new ColumnElement[count];
- for (i = 0; i < count ; i++)
+ for (i = 0; i < count ; i++) {
columns[i] = columnPairs[i].getReferencedColumn();
+ }
return columns;
}
@@ -310,10 +317,9 @@ public ColumnElement[] getReferencedColumns ()
* @param pairName the relative name of the column pair to remove
* @throws ModelException if impossible
*/
- public void removeColumnPair (String pairName) throws ModelException
- {
- ArrayList pairNames = new ArrayList(1);
-
+ @Override
+ public void removeColumnPair(String pairName) throws ModelException {
+ List pairNames = new ArrayList<>(1);
pairNames.add(pairName);
removeColumnPairs(pairNames);
}
@@ -323,46 +329,40 @@ public void removeColumnPair (String pairName) throws ModelException
* @param pairNames the relative names of the column pairs to remove
* @throws ModelException if impossible
*/
- public void removeColumnPairs (ArrayList pairNames) throws ModelException
- {
- ArrayList refKey = getReferencingKey();
- ArrayList key = getTable().getKey();
+ @Override
+ public void removeColumnPairs(List pairNames) throws ModelException {
+ List refKey = getReferencingKey();
+ List key = getTable().getKey();
int i, count = ((pairNames != null) ? pairNames.size() : 0);
- for (i = 0; i < count ; i++)
- {
- String pairName = (String)pairNames.get(i);
+ for (i = 0; i < count; i++) {
+ String pairName = pairNames.get(i);
int index = getIndexOfColumnPair(pairName);
- if (pairName != null)
- {
- try
- {
- Object remove1 = null, remove2 = null;
+ if (pairName != null) {
+ try {
+ String remove1 = null;
+ String remove2 = null;
fireVetoableChange(PROP_KEY_COLUMNS, null, null);
remove1 = key.remove(index);
remove2 = refKey.remove(index);
- if ((remove1 == null) || (remove2 == null))
- {
+ if ((remove1 == null) || (remove2 == null)) {
// if only 1 failed, put the other one back
- if (remove1 != null)
+ if (remove1 != null) {
key.add(index, remove1);
- else if (remove2 != null)
+ } else if (remove2 != null) {
refKey.add(index, remove2);
+ }
- throw new ModelException(I18NHelper.getMessage(
- getMessages(),
- "mapping.element.element_not_removed", // NOI18N
- pairName));
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.element.element_not_removed", pairName));
}
firePropertyChange(PROP_KEY_COLUMNS, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -375,6 +375,7 @@ else if (remove2 != null)
* @param pair the pair to add
* @throws ModelException if impossible
*/
+ @Override
public void addColumnPair (ColumnPairElement pair) throws ModelException
{
addColumnPairs(new ColumnPairElement[]{pair});
@@ -384,6 +385,7 @@ public void addColumnPair (ColumnPairElement pair) throws ModelException
* @param pairs the column pairs to add
* @throws ModelException if impossible
*/
+ @Override
public void addColumnPairs (ColumnPairElement[] pairs) throws ModelException
{
MappingTableElementImpl table = (MappingTableElementImpl)getTable();
@@ -391,7 +393,7 @@ public void addColumnPairs (ColumnPairElement[] pairs) throws ModelException
for (i = 0; i < count; i++)
{
- ColumnPairElement pair = (ColumnPairElement)pairs[i];
+ ColumnPairElement pair = pairs[i];
if (pair != null)
{
@@ -411,7 +413,7 @@ public void addColumnPairs (ColumnPairElement[] pairs) throws ModelException
else
{
throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
+ "mapping.element.null_argument"));
}
}
}
@@ -420,6 +422,7 @@ public void addColumnPairs (ColumnPairElement[] pairs) throws ModelException
* @param pair the column pair to remove
* @throws ModelException if impossible
*/
+ @Override
public void removeColumnPair (ColumnPairElement pair) throws ModelException
{
removeColumnPairs(new ColumnPairElement[]{pair});
@@ -429,18 +432,11 @@ public void removeColumnPair (ColumnPairElement pair) throws ModelException
* @param pairs the column pairs to remove
* @throws ModelException if impossible
*/
- public void removeColumnPairs (ColumnPairElement[] pairs)
- throws ModelException
- {
- ArrayList pairNames = new ArrayList();
- int i, count = ((pairs != null) ? pairs.length : 0);
-
- for (i = 0; i < count ; i++)
- {
- ColumnPairElement pair = (ColumnPairElement)pairs[i];
-
- pairNames.add(NameUtil.getRelativeMemberName(
- pair.getName().getFullName()));
+ @Override
+ public void removeColumnPairs(ColumnPairElement[] pairs) throws ModelException {
+ ArrayList pairNames = new ArrayList<>();
+ for (ColumnPairElement pair : pairs) {
+ pairNames.add(NameUtil.getRelativeMemberName(pair.getName().getFullName()));
}
removeColumnPairs(pairNames);
@@ -451,30 +447,28 @@ public void removeColumnPairs (ColumnPairElement[] pairs)
* @param pairs the new column pairs
* @throws ModelException if impossible
*/
- public void setColumnPairs (ColumnPairElement[] pairs) throws ModelException
- {
- removeColumnPairs(getColumnPairNames()); // remove the old ones
- addColumnPairs(pairs); // add the new ones
+ @Override
+ public void setColumnPairs(ColumnPairElement[] pairs) throws ModelException {
+ // remove the old ones
+ removeColumnPairs(getColumnPairNames());
+ // add the new ones
+ addColumnPairs(pairs);
}
/** Get all column pairs in this holder.
* @return the column pairs
*/
- public ColumnPairElement[] getColumnPairs ()
- {
- ArrayList pairNames = getColumnPairNames();
+ @Override
+ public ColumnPairElement[] getColumnPairs() {
+ List pairNames = getColumnPairNames();
TableElement table = getDeclaringTable();
int i, count = ((pairNames != null) ? pairNames.size() : 0);
ColumnPairElement[] pairs = new ColumnPairElement[count];
String databaseRoot = getDeclaringClass().getDatabaseRoot();
- for (i = 0; i < count; i++)
- {
- String absoluteName = NameUtil.getAbsoluteMemberName(
- databaseRoot, (String)pairNames.get(i));
-
- pairs[i] = (ColumnPairElement)table.getMember(
- DBIdentifier.create(absoluteName));
+ for (i = 0; i < count; i++) {
+ String absoluteName = NameUtil.getAbsoluteMemberName(databaseRoot, pairNames.get(i));
+ pairs[i] = (ColumnPairElement) table.getMember(DBIdentifier.create(absoluteName));
}
return pairs;
@@ -484,24 +478,21 @@ public ColumnPairElement[] getColumnPairs ()
* @param name the name of the column pair for which to look
* @return the column pair or null if not found
*/
- public ColumnPairElement getColumnPair (DBIdentifier name)
- {
+ @Override
+ public ColumnPairElement getColumnPair(DBIdentifier name) {
ColumnPairElement[] myPairs = getColumnPairs();
int count = ((myPairs != null) ? myPairs.length : 0);
String databaseRoot = getDeclaringClass().getDatabaseRoot();
- if (count > 0)
- {
- String absoluteTableName = NameUtil.getAbsoluteTableName(
- databaseRoot, getTable().getName());
- ColumnPairElement searchPair = (ColumnPairElement)
- TableElement.forName(absoluteTableName).getMember(name);
+ if (count > 0) {
+ String absoluteTableName = NameUtil.getAbsoluteTableName(databaseRoot, getTable().getName());
+ ColumnPairElement searchPair = (ColumnPairElement) TableElement.forName(absoluteTableName).getMember(name);
int i;
- for (i = 0; i < count; i++)
- {
- if (myPairs[i].equals(searchPair))
+ for (i = 0; i < count; i++) {
+ if (myPairs[i].equals(searchPair)) {
return searchPair;
+ }
}
}
@@ -515,33 +506,33 @@ public ColumnPairElement getColumnPair (DBIdentifier name)
* @param referencingKey the list of names of the columns in this
* referencing key
*/
- public void setReferencingKey (ArrayList referencingKey)
- {
+ public void setReferencingKey(List referencingKey) {
_referencingKey = referencingKey;
}
//============== extra methods for Boston -> Pilsen conversion ============
- /** Boston to Pilsen conversion.
+
+ /**
+ * Boston to Pilsen conversion.
* This method converts the name of this MappingReferenceKeyElement and
* the absolute column names stored in _referencingKey to relative names.
*/
- protected void stripSchemaName ()
- {
+ protected void stripSchemaName() {
// handle _name (use getRelativeTableName since the name is derived
// from the name of the participating table)
_name = NameUtil.getRelativeTableName(_name);
// handle _referencingKey
- if (_referencingKey != null)
- {
+ if (_referencingKey != null) {
// Use ListIterator here, because I want to replace the value
- // stored in the ArrayList. The ListIterator returned by
+ // stored in the ArrayList. The ListIterator returned by
// ArrayList.listIterator() supports the set method.
- ListIterator i = _referencingKey.listIterator();
+ ListIterator i = _referencingKey.listIterator();
- while (i.hasNext())
- i.set(NameUtil.getRelativeMemberName((String)i.next()));
+ while (i.hasNext()) {
+ i.set(NameUtil.getRelativeMemberName(i.next()));
+ }
}
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingRelationshipElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingRelationshipElementImpl.java
index f56cd54e6af..e68aa82655b 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingRelationshipElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingRelationshipElementImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingRelationshipElementImpl.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping.impl;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -31,6 +26,7 @@
import java.beans.PropertyVetoException;
import java.util.ArrayList;
+import java.util.List;
import java.util.ListIterator;
import org.glassfish.persistence.common.I18NHelper;
@@ -40,54 +36,36 @@
/**
*
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
-public class MappingRelationshipElementImpl extends MappingFieldElementImpl
- implements MappingRelationshipElement
-{
+public class MappingRelationshipElementImpl extends MappingFieldElementImpl implements MappingRelationshipElement {
// for join tables -- traverse through the middle table
- private ArrayList _associatedColumns; // of column pair names
- //@olsen: made transient to prevent from serializing into mapping files
- private transient ArrayList _associatedColumnObjects;// of ColumnPairElement (for runtime)
-
- /*
- // possibly for EJB use later
- // private String EJBType;
- // public String EJBReference;
- // end possibly for EJB use later
- */
+ // of column pair names
+ private List _associatedColumns;
+ // transient to prevent from serializing into mapping files
+ private transient List _associatedColumnObjects;
/** Create new MappingRelationshipElementImpl with no corresponding name or
* declaring class. This constructor should only be used for cloning and
* archiving.
*/
- public MappingRelationshipElementImpl ()
- {
+ public MappingRelationshipElementImpl() {
this(null, null);
}
- /** Create new MappingRelationshipElementImpl with the corresponding name
+ /**
+ * Create new MappingRelationshipElementImpl with the corresponding name
* and declaring class.
+ *
* @param name the name of the element
* @param declaringClass the class to attach to
*/
- public MappingRelationshipElementImpl (String name,
- MappingClassElement declaringClass)
- {
+ public MappingRelationshipElementImpl(String name, MappingClassElement declaringClass) {
super(name, declaringClass);
setFetchGroupInternal(GROUP_NONE);
}
-// TBD?
-/* public void clear ()
- {
- super.clear();
- _associatedColumns = null;
- }*/
-// end TBD
-
//=================== column handling for join tables ====================
/** Returns the list of associated column names to which this
@@ -95,10 +73,11 @@ public MappingRelationshipElementImpl (String name,
* @return the names of the columns mapped by this mapping field
* @see MappingFieldElement#getColumns
*/
- public ArrayList getAssociatedColumns ()
- {
- if (_associatedColumns == null)
- _associatedColumns = new ArrayList();
+ @Override
+ public List getAssociatedColumns() {
+ if (_associatedColumns == null) {
+ _associatedColumns = new ArrayList<>();
+ }
return _associatedColumns;
}
@@ -113,60 +92,48 @@ public ArrayList getAssociatedColumns ()
* @see MappingFieldElement#addColumn
* @see #addAssociatedColumn
*/
- public void addLocalColumn (ColumnPairElement column)
- throws ModelException
- {
+ @Override
+ public void addLocalColumn(ColumnPairElement column) throws ModelException {
// can't call addColumn in this class because there will be an
// exception since the associated columns will be (legally) populated
super.addColumn(column);
}
- /** Adds a column to the list of associated columns mapped by this mapping
- * field. Call this method instead of addColumn when mapping
- * join tables. This method is used to map between the join table column
+ /**
+ * Adds a column to the list of associated columns mapped by this mapping
+ * field. Call this method instead of addColumn when mapping
+ * join tables. This method is used to map between the join table column
* and the foreign table column, while addLocalColumn is used
* to map between the local table and the join table.
+ *
* @param column column pair element to be added to the mapping
* @exception ModelException if impossible
* @see MappingFieldElement#addColumn
* @see #addLocalColumn
*/
- public void addAssociatedColumn (ColumnPairElement column)
- throws ModelException
- {
- if (column != null)
- {
- ArrayList columns = getAssociatedColumns();
- String columnName = NameUtil.getRelativeMemberName(
- column.getName().getFullName());
-
- // double check that this pair is not already in the column list
- if (!columns.contains(columnName))
- {
- try
- {
- fireVetoableChange(PROP_ASSOCIATED_COLUMNS, null, null);
- columns.add(columnName);
- firePropertyChange(PROP_ASSOCIATED_COLUMNS, null, null);
-
- // sync up runtime's object list too
- _associatedColumnObjects = null;
- }
- catch (PropertyVetoException e)
- {
- throw new ModelVetoException(e);
- }
- }
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.column.column_defined", columnName)); // NOI18N
- }
+ @Override
+ public void addAssociatedColumn(ColumnPairElement column) throws ModelException {
+ if (column == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
}
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
+ List columns = getAssociatedColumns();
+ String columnName = NameUtil.getRelativeMemberName(column.getName().getFullName());
+
+ // double check that this pair is not already in the column list
+ if (!columns.contains(columnName)) {
+ try {
+ fireVetoableChange(PROP_ASSOCIATED_COLUMNS, null, null);
+ columns.add(columnName);
+ firePropertyChange(PROP_ASSOCIATED_COLUMNS, null, null);
+
+ // sync up runtime's object list too
+ _associatedColumnObjects = null;
+ } catch (PropertyVetoException e) {
+ throw new ModelVetoException(e);
+ }
+ } else {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.column.column_defined", columnName));
}
}
@@ -178,26 +145,19 @@ public void addAssociatedColumn (ColumnPairElement column)
* @param column column element to be added to the mapping
* @exception ModelException if impossible
*/
- public void addColumn (DBMemberElement column) throws ModelException
- {
- if (column instanceof ColumnPairElement)
- {
- if (!getAssociatedColumns().isEmpty())
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.column.associated_columns_defined", // NOI18N
- NameUtil.getRelativeMemberName(
- column.getName().getFullName())));
+ @Override
+ public void addColumn(DBMemberElement column) throws ModelException {
+ if (column instanceof ColumnPairElement) {
+ if (!getAssociatedColumns().isEmpty()) {
+ throw new ModelException(
+ I18NHelper.getMessage(getMessages(), "mapping.column.associated_columns_defined",
+ NameUtil.getRelativeMemberName(column.getName().getFullName())));
}
super.addColumn(column);
- }
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.column.column_invalid", // NOI18N
- NameUtil.getRelativeMemberName(
- column.getName().getFullName())));
+ } else {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.column.column_invalid",
+ NameUtil.getRelativeMemberName(column.getName().getFullName())));
}
}
@@ -208,33 +168,25 @@ public void addColumn (DBMemberElement column) throws ModelException
* the mapping
* @exception ModelException if impossible
*/
- public void removeColumn (String columnName) throws ModelException
- {
- try
- {
+ @Override
+ public void removeColumn(String columnName) throws ModelException {
+ try {
super.removeColumn(columnName);
- }
- catch (ModelException e) // not found in regular columns
- {
- try
- {
+ } catch (ModelException e) {
+ // not found in regular columns
+ try {
fireVetoableChange(PROP_ASSOCIATED_COLUMNS, null, null);
- if (!getAssociatedColumns().remove(columnName))
- {
+ if (!getAssociatedColumns().remove(columnName)) {
throw new ModelException(
- I18NHelper.getMessage(getMessages(),
- "mapping.element.element_not_removed", // NOI18N
- columnName));
+ I18NHelper.getMessage(getMessages(), "mapping.element.element_not_removed", columnName));
}
firePropertyChange(PROP_ASSOCIATED_COLUMNS, null, null);
// sync up runtime's object list too
_associatedColumnObjects = null;
- }
- catch (PropertyVetoException ve)
- {
+ } catch (PropertyVetoException ve) {
throw new ModelVetoException(ve);
}
}
@@ -248,13 +200,10 @@ public void removeColumn (String columnName) throws ModelException
* @return the columns mapped by this mapping field
* @see MappingFieldElement#getColumns
*/
- public ArrayList getAssociatedColumnObjects ()
- {
- if (_associatedColumnObjects == null)
- {
- _associatedColumnObjects = MappingClassElementImpl.
- toColumnObjects(getDeclaringClass().getDatabaseRoot(),
- getAssociatedColumns());
+ @Override
+ public List getAssociatedColumnObjects() {
+ if (_associatedColumnObjects == null) {
+ _associatedColumnObjects = MappingClassElementImpl.toColumnObjects(getDeclaringClass().getDatabaseRoot(), getAssociatedColumns());
}
return _associatedColumnObjects;
@@ -262,75 +211,96 @@ public ArrayList getAssociatedColumnObjects ()
//============= delegation to RelationshipElement ===========
- final RelationshipElement getRelationshipElement ()
- {
- return ((MappingClassElementImpl)getDeclaringClass()).
- getPersistenceElement().getRelationship(getName());
+
+ final RelationshipElement getRelationshipElement() {
+ return ((MappingClassElementImpl) getDeclaringClass()).getPersistenceElement().getRelationship(getName());
}
- /** Get the element class for this relationship element. If primitive
+ @Override
+ public List getColumnObjects() {
+ List extends DBMemberElement> objects = super.getColumnObjects();
+ if (objects.isEmpty()) {
+ return new ArrayList<>();
+ }
+ List columns = new ArrayList<>();
+ columns.addAll(objects.stream().map(ColumnPairElement.class::cast).toList());
+ return columns;
+ }
+
+ /**
+ * Get the element class for this relationship element. If primitive
* types are supported, you can use wrapperclass .TYPE
* to specify them.
+ *
* @return the element class
*/
- public String getElementClass ()
- {
+ public String getElementClass() {
return getRelationshipElement().getElementClass();
}
- /** Get the update action for this relationship element.
+
+ /**
+ * Get the update action for this relationship element.
+ *
* @return the update action, one of
- * {@link RelationshipElement#NONE_ACTION},
- * {@link RelationshipElement#NULLIFY_ACTION},
- * {@link RelationshipElement#RESTRICT_ACTION},
- * {@link RelationshipElement#CASCADE_ACTION}, or
- * {@link RelationshipElement#AGGREGATE_ACTION}
+ * {@link RelationshipElement#NONE_ACTION},
+ * {@link RelationshipElement#NULLIFY_ACTION},
+ * {@link RelationshipElement#RESTRICT_ACTION},
+ * {@link RelationshipElement#CASCADE_ACTION}, or
+ * {@link RelationshipElement#AGGREGATE_ACTION}
*/
- public int getUpdateAction ()
- {
+ public int getUpdateAction() {
return getRelationshipElement().getUpdateAction();
}
- /** Get the delete action for this relationship element.
+
+ /**
+ * Get the delete action for this relationship element.
+ *
* @return the delete action, one of
- * {@link RelationshipElement#NONE_ACTION},
- * {@link RelationshipElement#NULLIFY_ACTION},
- * {@link RelationshipElement#RESTRICT_ACTION},
- * {@link RelationshipElement#CASCADE_ACTION}, or
- * {@link RelationshipElement#AGGREGATE_ACTION}
+ * {@link RelationshipElement#NONE_ACTION},
+ * {@link RelationshipElement#NULLIFY_ACTION},
+ * {@link RelationshipElement#RESTRICT_ACTION},
+ * {@link RelationshipElement#CASCADE_ACTION}, or
+ * {@link RelationshipElement#AGGREGATE_ACTION}
*/
- public int getDeleteAction ()
- {
+ public int getDeleteAction() {
return getRelationshipElement().getDeleteAction();
}
- /** Get the upper cardinality bound for this relationship element. Returns
+
+ /**
+ * Get the upper cardinality bound for this relationship element. Returns
* {@link java.lang.Integer#MAX_VALUE} for n
+ *
* @return the upper cardinality bound
*/
- public int getUpperBound ()
- {
+ public int getUpperBound() {
return getRelationshipElement().getUpperBound();
}
- /** Get the lower cardinality bound for this relationship element.
+
+ /**
+ * Get the lower cardinality bound for this relationship element.
+ *
* @return the lower cardinality bound
*/
- public int getLowerBound ()
- {
+ public int getLowerBound() {
return getRelationshipElement().getLowerBound();
}
- //=============== extra set methods needed for xml archiver ==============
+ // =============== extra set methods needed for xml archiver ==============
+
- /** Set the list of associated column names to which this mapping field is
- * mapped. This method should only be used internally and for cloning
+ /**
+ * Set the list of associated column names to which this mapping field is
+ * mapped. This method should only be used internally and for cloning
* and archiving.
+ *
* @param associatedColumns the list of names of the columns mapped by
- * this mapping field
+ * this mapping field
*/
- public void setAssociatedColumns (ArrayList associatedColumns)
- {
+ public void setAssociatedColumns(List associatedColumns) {
_associatedColumns = associatedColumns;
}
@@ -343,21 +313,21 @@ public void setAssociatedColumns (ArrayList associatedColumns)
/** Boston to Pilsen conversion.
* This method converts the absolute column names to relative names.
*/
- protected void stripSchemaName ()
- {
+ @Override
+ public void stripSchemaName() {
// call super to handle the columns stored in _columns
super.stripSchemaName();
// handle _associatedColumns
- if (_associatedColumns != null)
- {
+ if (_associatedColumns != null) {
// Use ListIterator here, because I want to replace the value
- // stored in the ArrayList. The ListIterator returned by
+ // stored in the ArrayList. The ListIterator returned by
// ArrayList.listIterator() supports the set method.
- ListIterator i = _associatedColumns.listIterator();
+ ListIterator i = _associatedColumns.listIterator();
- while (i.hasNext())
- i.set(NameUtil.getRelativeMemberName((String)i.next()));
+ while (i.hasNext()) {
+ i.set(NameUtil.getRelativeMemberName(i.next()));
+ }
}
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingTableElementImpl.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingTableElementImpl.java
index 8a4a7cdf23b..258c3a05655 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingTableElementImpl.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/mapping/impl/MappingTableElementImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * MappingTableElementImpl.java
- *
- * Created on March 3, 2000, 1:11 PM
- */
-
package com.sun.jdo.api.persistence.model.mapping.impl;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -31,6 +26,7 @@
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.Iterator;
+import java.util.List;
import java.util.ListIterator;
import org.glassfish.persistence.common.I18NHelper;
@@ -39,50 +35,50 @@
import org.netbeans.modules.dbschema.util.NameUtil;
/**
- *
- * @author Mark Munro
- * @author Rochelle Raccah
- * @version %I%
+ * @author Mark Munro 2000
+ * @author Rochelle Raccah 2000
*/
public class MappingTableElementImpl extends MappingMemberElementImpl
implements MappingTableElement
{
- private ArrayList _key; // array of column names
+ private List _key; // array of column names
//@olsen: made transient to prevent from serializing into mapping files
- private transient ArrayList _keyObjects; // array of ColumnElement (for runtime)
- private ArrayList _referencingKeys; // array of MappingReferenceKeyElement
+ private transient List _keyObjects; // array of ColumnElement (for runtime)
+ private List _referencingKeys; // array of MappingReferenceKeyElement
private String _table;
//@olsen: made transient to prevent from serializing into mapping files
private transient TableElement _tableObject; // for runtime
- /** Create new MappingTableElementImpl with no corresponding name or
- * declaring class. This constructor should only be used for cloning and
+ /**
+ * Create new MappingTableElementImpl with no corresponding name or
+ * declaring class. This constructor should only be used for cloning and
* archiving.
*/
- public MappingTableElementImpl ()
- {
- this((String)null, null);
+ public MappingTableElementImpl() {
+ this((String) null, null);
}
- /** Create new MappingTableElementImpl with the corresponding name and
+
+ /**
+ * Create new MappingTableElementImpl with the corresponding name and
* declaring class.
+ *
* @param name the name of the element
* @param declaringClass the class to attach to
*/
- public MappingTableElementImpl (String name,
- MappingClassElement declaringClass)
- {
+ public MappingTableElementImpl(String name, MappingClassElement declaringClass) {
super(name, declaringClass);
}
- /** Creates new MappingTableElementImpl with a corresponding
+
+ /**
+ * Creates new MappingTableElementImpl with a corresponding
* table and declaring class.
+ *
* @param table table element to be used by the mapping table.
* @param declaringClass the class to attach to
*/
- public MappingTableElementImpl (TableElement table,
- MappingClassElement declaringClass) throws ModelException
- {
+ public MappingTableElementImpl(TableElement table, MappingClassElement declaringClass) {
this(table.toString(), declaringClass);
// don't use setTable so as not to fire property change events
@@ -94,19 +90,21 @@ public MappingTableElementImpl (TableElement table,
/** Returns the name of the table element used by this mapping table.
* @return the table name for this mapping table
*/
- public String getTable () { return _table; }
+ @Override
+ public String getTable() {
+ return _table;
+ }
/** Set the table element for this mapping table to the supplied table.
* @param table table element to be used by the mapping table.
* @exception ModelException if impossible
*/
- public void setTable (TableElement table) throws ModelException
- {
+ @Override
+ public void setTable(TableElement table) throws ModelException {
String old = getTable();
String newName = table.toString();
- try
- {
+ try {
fireVetoableChange(PROP_TABLE, old, newName);
_table = newName;
firePropertyChange(PROP_TABLE, old, newName);
@@ -115,9 +113,7 @@ public void setTable (TableElement table) throws ModelException
// sync up runtime's object too: force next
// access to getTableObject to recompute it
_tableObject = null;
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -127,12 +123,12 @@ public void setTable (TableElement table) throws ModelException
* @param name the name
* @exception ModelException if impossible
*/
- public void setName (String name) throws ModelException
- {
+ @Override
+ public void setName(String name) throws ModelException {
super.setName(name);
-
- if (getTable() == null)
+ if (getTable() == null) {
_table = name;
+ }
}
/** Returns true if the table element used by this mapping table is equal
@@ -140,8 +136,8 @@ public void setName (String name) throws ModelException
* @return true if table elements are equal,
* false otherwise.
*/
- public boolean isEqual (TableElement table)
- {
+ @Override
+ public boolean isEqual(TableElement table) {
return ((table != null) ? getTable().equals(table.toString()) : false);
}
@@ -152,10 +148,11 @@ public boolean isEqual (TableElement table)
* @return the names of the columns in the primary key for this mapping
* table
*/
- public ArrayList getKey ()
- {
- if (_key == null)
- _key = new ArrayList();
+ @Override
+ public List getKey() {
+ if (_key == null) {
+ _key = new ArrayList<>();
+ }
return _key;
}
@@ -167,24 +164,17 @@ public ArrayList getKey ()
* @param column column element to be added
* @exception ModelException if impossible
*/
- public void addKeyColumn (ColumnElement column) throws ModelException
- {
- if (column != null)
- {
- String columnName = NameUtil.getRelativeMemberName(
- column.getName().getFullName());
-
- if (!getKey().contains(columnName))
- addKeyColumnInternal(column);
- else
- {
- // this part was blank -- do we want an error or skip here?
- }
+ @Override
+ public void addKeyColumn(ColumnElement column) throws ModelException {
+ if (column == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
}
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
+ String columnName = NameUtil.getRelativeMemberName(column.getName().getFullName());
+
+ if (!getKey().contains(columnName)) {
+ addKeyColumnInternal(column);
+ } else {
+ // this part was blank -- do we want an error or skip here?
}
}
@@ -196,25 +186,20 @@ public void addKeyColumn (ColumnElement column) throws ModelException
* @param column column element to be added
* @exception ModelException if impossible
*/
- protected void addKeyColumnInternal (ColumnElement column) throws ModelException
- {
- ArrayList key = getKey();
- String columnName = NameUtil.getRelativeMemberName(
- column.getName().getFullName());
+ protected void addKeyColumnInternal(ColumnElement column) throws ModelException {
+ List key = getKey();
+ String columnName = NameUtil.getRelativeMemberName(column.getName().getFullName());
- try
- {
+ try {
fireVetoableChange(PROP_KEY_COLUMNS, null, null);
key.add(columnName);
firePropertyChange(PROP_KEY_COLUMNS, null, null);
// sync up runtime's object list too
- //@olsen: rather clear objects instead of maintaining them
- //getKeyObjects().add(column);
+ // @olsen: rather clear objects instead of maintaining them
+ // getKeyObjects().add(column);
_keyObjects = null;
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -226,31 +211,24 @@ protected void addKeyColumnInternal (ColumnElement column) throws ModelException
* @param columnName the relative name of the column to be removed
* @exception ModelException if impossible
*/
- public void removeKeyColumn (String columnName) throws ModelException
- {
- if (columnName != null)
- {
- try
- {
+ @Override
+ public void removeKeyColumn(String columnName) throws ModelException {
+ if (columnName != null) {
+ try {
fireVetoableChange(PROP_KEY_COLUMNS, null, null);
- if (!getKey().remove(columnName))
- {
+ if (!getKey().remove(columnName)) {
throw new ModelException(
- I18NHelper.getMessage(getMessages(),
- "mapping.element.element_not_removed", // NOI18N
- columnName));
+ I18NHelper.getMessage(getMessages(), "mapping.element.element_not_removed", columnName));
}
firePropertyChange(PROP_KEY_COLUMNS, null, null);
// sync up runtime's object list too
- //@olsen: rather clear objects instead of maintaining them
- //getKeyObjects().remove(column);
+ // @olsen: rather clear objects instead of maintaining them
+ // getKeyObjects().remove(column);
_keyObjects = null;
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -263,29 +241,29 @@ public void removeKeyColumn (String columnName) throws ModelException
* keys.
* @return the reference key elements for this mapping table
*/
- public ArrayList getReferencingKeys ()
- {
- if (_referencingKeys == null)
- _referencingKeys = new ArrayList();
+ @Override
+ public List getReferencingKeys() {
+ if (_referencingKeys == null) {
+ _referencingKeys = new ArrayList<>();
+ }
return _referencingKeys;
}
- /** Adds a referencing key to the list of keys in this mapping table.
+
+ /**
+ * Adds a referencing key to the list of keys in this mapping table.
+ *
* @param referencingKey referencing key element to be added
* @exception ModelException if impossible
*/
- public void addReferencingKey (MappingReferenceKeyElement referencingKey)
- throws ModelException
- {
- try
- {
+ @Override
+ public void addReferencingKey(MappingReferenceKeyElement referencingKey) throws ModelException {
+ try {
fireVetoableChange(PROP_REFERENCING_KEYS, null, null);
getReferencingKeys().add(referencingKey);
firePropertyChange(PROP_REFERENCING_KEYS, null, null);
- }
- catch (PropertyVetoException e)
- {
+ } catch (PropertyVetoException e) {
throw new ModelVetoException(e);
}
}
@@ -295,38 +273,24 @@ public void addReferencingKey (MappingReferenceKeyElement referencingKey)
* @param table mapping table element for which to remove referencing keys
* @exception ModelException if impossible
*/
- public void removeReference (MappingTableElement table)
- throws ModelException
- {
- if (table != null)
- {
- Iterator keyIterator = getReferencingKeys().iterator();
-
- while (keyIterator.hasNext())
- {
- MappingReferenceKeyElement nextKey =
- (MappingReferenceKeyElement)keyIterator.next();
-
- if (nextKey.getTable().equals(table))
- {
- try
- {
- fireVetoableChange(PROP_REFERENCING_KEYS, null, null);
- keyIterator.remove();
- firePropertyChange(PROP_REFERENCING_KEYS, null, null);
- }
- catch (PropertyVetoException e)
- {
- throw new ModelVetoException(e);
- }
+ @Override
+ public void removeReference(MappingTableElement table) throws ModelException {
+ if (table == null) {
+ throw new ModelException(I18NHelper.getMessage(getMessages(), "mapping.element.null_argument"));
+ }
+ Iterator keyIterator = getReferencingKeys().iterator();
+ while (keyIterator.hasNext()) {
+ MappingReferenceKeyElement nextKey = keyIterator.next();
+ if (nextKey.getTable().equals(table)) {
+ try {
+ fireVetoableChange(PROP_REFERENCING_KEYS, null, null);
+ keyIterator.remove();
+ firePropertyChange(PROP_REFERENCING_KEYS, null, null);
+ } catch (PropertyVetoException e) {
+ throw new ModelVetoException(e);
}
}
}
- else
- {
- throw new ModelException(I18NHelper.getMessage(getMessages(),
- "mapping.element.null_argument")); // NOI18N
- }
}
//============= extra object support for runtime ========================
@@ -335,6 +299,7 @@ public void removeReference (MappingTableElement table)
* table. This method should only be used by the runtime.
* @return the table element for this mapping table
*/
+ @Override
public TableElement getTableObject ()
{
if (_tableObject == null)
@@ -352,15 +317,12 @@ public TableElement getTableObject ()
* this mapping table. This method should only be used by the runtime.
* @return the column elements in the primary key for this mapping table
*/
- public ArrayList getKeyObjects ()
- {
- if (_keyObjects == null)
- {
- //@olsen: calculate the key objects based on
- // the key names as stored in _key
- //_keyObjects = new ArrayList();
- _keyObjects = MappingClassElementImpl.toColumnObjects(
- getDeclaringClass().getDatabaseRoot(), getKey());
+ public List getKeyObjects() {
+ if (_keyObjects == null) {
+ // @olsen: calculate the key objects based on
+ // the key names as stored in _key
+ // _keyObjects = new ArrayList();
+ _keyObjects = MappingClassElementImpl.toColumnObjects(getDeclaringClass().getDatabaseRoot(), getKey());
}
return _keyObjects;
@@ -372,27 +334,32 @@ public ArrayList getKeyObjects ()
* method should only be used internally and for cloning and archiving.
* @param table the table name for this mapping table
*/
- public void setTable (String table)
- {
+ public void setTable(String table) {
_table = table;
}
- /** Set the list of column names in the primary key for this mapping
- * table. This method should only be used internally and for cloning
+
+ /**
+ * Set the list of column names in the primary key for this mapping
+ * table. This method should only be used internally and for cloning
* and archiving.
+ *
* @param key the list of names of the columns in the primary key for
- * this mapping table
+ * this mapping table
*/
- public void setKey (ArrayList key) { _key = key; }
+ public void setKey(ArrayList key) {
+ _key = key;
+ }
- /** Set the list of keys (MappingReferenceKeyElements) for this mapping
- * table. This method should only be used internally and for cloning
+
+ /**
+ * Set the list of keys (MappingReferenceKeyElements) for this mapping
+ * table. This method should only be used internally and for cloning
* and archiving.
- * @param referencingKeys the list of reference key elements for this
- * mapping table
+ *
+ * @param referencingKeys the list of reference key elements for this mapping table
*/
- public void setReferencingKeys (ArrayList referencingKeys)
- {
+ public void setReferencingKeys(List referencingKeys) {
_referencingKeys = referencingKeys;
}
@@ -404,8 +371,8 @@ public void setReferencingKeys (ArrayList referencingKeys)
* The method is recursively called for all MappingReferenceKeyElements
* attached to this MappingTableElement.
*/
- protected void stripSchemaName ()
- {
+ @Override
+ public void stripSchemaName() {
// handle _name
_name = NameUtil.getRelativeTableName(_name);
@@ -415,29 +382,25 @@ protected void stripSchemaName ()
// handle _referencingKeys
// call method stripSchemaName on the MappingReferenceKeyElementImpl
// objects
- if (_referencingKeys != null)
- {
- Iterator i = _referencingKeys.iterator();
-
- while (i.hasNext())
- {
- MappingReferenceKeyElementImpl refKey =
- (MappingReferenceKeyElementImpl)i.next();
+ if (_referencingKeys != null) {
+ Iterator i = _referencingKeys.iterator();
+ while (i.hasNext()) {
+ MappingReferenceKeyElementImpl refKey = (MappingReferenceKeyElementImpl) i.next();
refKey.stripSchemaName();
}
}
// handle _key
- if (_key != null)
- {
+ if (_key != null) {
// Use ListIterator here, because I want to replace the value
- // stored in the ArrayList. The ListIterator returned by
+ // stored in the ArrayList. The ListIterator returned by
// ArrayList.listIterator() supports the set method.
- ListIterator i = _key.listIterator();
+ ListIterator i = _key.listIterator();
- while (i.hasNext())
- i.set(NameUtil.getRelativeMemberName((String)i.next()));
+ while (i.hasNext()) {
+ i.set(NameUtil.getRelativeMemberName(i.next()));
+ }
}
}
}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/DumpMapping.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/DumpMapping.java
deleted file mode 100644
index 2417b358302..00000000000
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/DumpMapping.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v. 2.0, which is available at
- * http://www.eclipse.org/legal/epl-2.0.
- *
- * This Source Code may also be made available under the following Secondary
- * Licenses when the conditions for such availability set forth in the
- * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
- * version 2 with the GNU Classpath Exception, which is available at
- * https://www.gnu.org/software/classpath/license.html.
- *
- * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
- */
-
-/**
- * DumpMapping.java
- *
- */
-
-package com.sun.jdo.api.persistence.model.util;
-
-import com.sun.jdo.api.persistence.model.Model;
-import com.sun.jdo.api.persistence.model.jdo.ConcurrencyGroupElement;
-import com.sun.jdo.api.persistence.model.jdo.PersistenceClassElement;
-import com.sun.jdo.api.persistence.model.jdo.PersistenceFieldElement;
-import com.sun.jdo.api.persistence.model.jdo.RelationshipElement;
-import com.sun.jdo.api.persistence.model.mapping.MappingClassElement;
-import com.sun.jdo.api.persistence.model.mapping.MappingReferenceKeyElement;
-import com.sun.jdo.api.persistence.model.mapping.MappingRelationshipElement;
-import com.sun.jdo.api.persistence.model.mapping.impl.MappingClassElementImpl;
-import com.sun.jdo.api.persistence.model.mapping.impl.MappingFieldElementImpl;
-import com.sun.jdo.api.persistence.model.mapping.impl.MappingRelationshipElementImpl;
-import com.sun.jdo.api.persistence.model.mapping.impl.MappingTableElementImpl;
-
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.netbeans.modules.dbschema.ColumnElement;
-import org.netbeans.modules.dbschema.ColumnPairElement;
-
-public class DumpMapping
-{
- private static Model model;
-
- static
- {
- // initialize the model reference
- setModel(Model.RUNTIME);
- }
-
- /** Print out the cache of MappingClassElements to the specified PrintStream.
- * @param stream PrintStream used to dump the info
- */
- public static void dumpMappingCache (PrintStream stream)
- {
- stream.println("Mapping cache (class names -> MappingClassElements)"); // NOI18N
- for (Iterator i = model.getMappingCache().entrySet().iterator();
- i.hasNext();)
- {
- Map.Entry entry = (Map.Entry)i.next();
- String className = (String)entry.getKey();
- MappingClassElement mce = (MappingClassElement)entry.getValue();
- String mceRepr = mce.getClass() + "@" + // NOI18N
- Integer.toHexString(System.identityHashCode(mce));
- stream.println("\t" + className + " ->\t" + mceRepr); //NOI18N
- }
- }
-
- /** Print out the cache of classLoaders to the specified PrintStream.
- * @param stream PrintStream used to dump the info
- */
- public static void dumpClassLoaderCache (PrintStream stream)
- {
- stream.println("ClassLoader cache (class names -> ClassLoaders)"); //NOI18N
- for (Iterator i = model.getClassLoaderCache().entrySet().iterator();
- i.hasNext();)
- {
- Map.Entry entry = (Map.Entry)i.next();
- String className = (String)entry.getKey();
- ClassLoader classLoader = (ClassLoader)entry.getValue();
- stream.println("\t" + className + " ->\t" + classLoader); //NOI18N
- }
- }
-
- public static void main(String[] args)
- {
- for (int i = 0; i < args.length; i++)
- {
- String className = args[i];
- println(0, "\nClass " + className + ":"); //NOI18N
-
- try
- {
- MappingClassElementImpl mce = (MappingClassElementImpl)model.getMappingClass(className);
- if (mce != null)
- {
- printPersistenceClassElement(mce.getPersistenceElement());
- printMappingClassElement(mce);
- }
- else
- {
- println(0, "Cannot find mapping info for class " + className + " (getMappingClass returns null)"); //NOI18N
- }
- }
- catch (Exception e)
- {
- println(0, "Problems during accessing mapping info for class " + className); //NOI18N
- e.printStackTrace();
- }
- }
- }
-
- /** Sets the internal model reference used by the DumpMapping methods
- * to the specified Model instance.
- * @param newModel the Model instance to be used by DumpMapping
- */
- public static void setModel(Model newModel)
- {
- model = newModel;
- }
-
- // ----- JDO model ------
-
- public static void printPersistenceClassElement(PersistenceClassElement pce)
- {
- println(0, "\n--> PersistenceClassElement "); //NOI18N
- println(1, "package = " + pce.getPackage()); //NOI18N
- println(1, "name = " + pce.getName()); //NOI18N
- println(1, "identity = " + getObjectIdentityTypeRepr(pce.getObjectIdentityType())); //NOI18N
- println(1, "keyClass = " + pce.getKeyClass()); //NOI18N
-
- printPersistenceFieldElements(1, pce.getFields());
- printConcurrencyGroupElements(1, pce.getConcurrencyGroups());
-
- println(0, "<-- PersistenceClassElement\n "); //NOI18N
- }
-
-
- public static void printPersistenceFieldElements(int tabs, PersistenceFieldElement[] fields)
- {
- if ((fields != null) && (fields.length > 0))
- {
- println(tabs, "--> fields "); //NOI18N
- for (int i = 0; i < fields.length; i++)
- {
- PersistenceFieldElement pfe = fields[i];
-
- println(tabs, "[" + i + "] " + pfe.getClass()); //NOI18N
- println(tabs+1, "name = " + pfe.getName()); //NOI18N
- println(tabs+1, "declaringClass = " + pfe.getDeclaringClass()); //NOI18N
- println(tabs+1, "fieldNumber = " + pfe.getFieldNumber()); //NOI18N
- println(tabs+1, "persistenceType = " + getPersistenceTypeRepr(pfe.getPersistenceType())); //NOI18N
- println(tabs+1, "read / write = " + pfe.isReadSensitive() + " / " + pfe.isWriteSensitive()); //NOI18N
- println(tabs+1, "isKey = " + pfe.isKey()); //NOI18N
-
- if (pfe instanceof RelationshipElement)
- {
- RelationshipElement re = (RelationshipElement) pfe;
-
- println(tabs+1, "bounds = " + re.getLowerBound() + " / " + re.getUpperBound()); //NOI18N
- println(tabs+1, "deleteAction = " + re.getDeleteAction()); //NOI18N
- println(tabs+1, "updateAction = " + re.getUpdateAction()); //NOI18N
- println(tabs+1, "collectionClass = " + re.getCollectionClass()); //NOI18N
- println(tabs+1, "elementClass = " + re.getElementClass()); //NOI18N
- println(tabs+1, "isPrefetch = " + re.isPrefetch()); //NOI18N
- }
- printConcurrencyGroupElements(tabs+1, pfe.getConcurrencyGroups());
- }
- println(tabs, "<-- fields "); //NOI18N
- }
- }
-
- public static void printConcurrencyGroupElements(int tabs, ConcurrencyGroupElement[] groups)
- {
- if ((groups != null) && (groups.length > 0))
- {
- println(tabs, "--> concurrency groups"); //NOI18N
- for (int i = 0; i < groups.length; i++)
- {
- ConcurrencyGroupElement cg = groups[i];
- println(tabs, "[" + i + "] " + cg.getClass()); //NOI18N
- println(tabs+1, "name = " + cg.getName()); //NOI18N
- println(tabs+1, "declaringClass = " + cg.getDeclaringClass()); //NOI18N
- }
- println(tabs, "<-- concurrency groups"); //NOI18N
- }
- }
-
- // ----- Mapping model ------
-
- public static void printMappingClassElement(MappingClassElement mce)
- {
- println(0, "\n--> MappingClassElement"); //NOI18N
-
- println(1, "databaseRoot = " + mce.getDatabaseRoot()); //NOI18N
- printMappingTableElements(1, mce.getTables());
- printMappingFieldElements(1, mce.getFields());
-
- println(0, "<-- MappingClassElement"); //NOI18N
- }
-
- public static void printMappingTableElements(int tabs, ArrayList tables)
- {
- final int count = ((tables != null) ? tables.size() : 0);
-
- if (count > 0)
- {
- println(tabs, "--> tables "); //NOI18N
- for (int i = 0; i < count; i++)
- {
- MappingTableElementImpl mte = (MappingTableElementImpl) tables.get(i);
-
- println(tabs, "[" + i + "] " + mte.getClass()); //NOI18N
-
- println(tabs+1, "table = " + mte.getTable()); //NOI18N
- println(tabs+1, "tableObject = " + mte.getTableObject()); //NOI18N
- println(tabs+1, "key = " + mte.getKey()); //NOI18N
- println(tabs+1, "keyObjects = " + mte.getKeyObjects()); //NOI18N
- printMappingRefKeyElements(tabs+1, mte.getReferencingKeys());
- }
- println(tabs, "<-- tables "); //NOI18N
- }
- }
-
- public static void printMappingRefKeyElements(int tabs, ArrayList refKeys)
- {
- final int count = ((refKeys != null) ? refKeys.size() : 0);
-
- if (count > 0)
- {
- println(tabs, "--> tables "); //NOI18N
- for (int i = 0; i < count; i++)
- {
- MappingReferenceKeyElement mrke = (MappingReferenceKeyElement)refKeys.get(i);
-
- println(tabs, "[" + i + "] " + mrke.getClass()); //NOI18N
-
- println(tabs+1, "table = " + mrke.getDeclaringTable()); //NOI18N
- println(tabs+1, "pairs = " + mrke.getColumnPairNames()); //NOI18N
- }
- println(tabs, "<-- tables "); //NOI18N
- }
- }
-
- public static void printMappingFieldElements(int tabs, ArrayList fields)
- {
- final int count = ((fields != null) ? fields.size() : 0);
-
- if (count > 0)
- {
- println(tabs, "--> fields "); //NOI18N
- for (int i = 0; i < count; i++)
- {
- MappingFieldElementImpl mfe = (MappingFieldElementImpl) fields.get(i);
-
- println(tabs, "[" + i + "] " + mfe.getClass()); //NOI18N
- println(tabs+1, "name = " + mfe.getName()); //NOI18N
- println(tabs+1, "fetchGroup = " + mfe.getFetchGroup()); //NOI18N
- println(tabs+1, "columns = " + mfe.getColumns()); //NOI18N
-
- if (!(mfe instanceof MappingRelationshipElement))
- {
- println(tabs+1, "columnObjects = " + mfe.getColumnObjects()); //NOI18N
- }
- else
- {
- MappingRelationshipElementImpl mre = (MappingRelationshipElementImpl) mfe;
-
- ArrayList columnObjects = mre.getColumnObjects();
- int colCount =
- ((columnObjects != null) ? columnObjects.size() : 0);
- if (colCount > 0)
- {
- println(tabs+1, "--> columnsObjects "); //NOI18N
- for (int j = 0; j < colCount; j++)
- {
- ColumnPairElement fce = (ColumnPairElement) columnObjects.get(j);
- ColumnElement rce = (fce!=null)?fce.getReferencedColumn():null;
- println(tabs+1, "[" + j + "] " + fce + " -> " + rce); //NOI18N
- }
- println(tabs+1, "<-- columnsObjects "); //NOI18N
- }
-
- println(tabs+1, "associatedColumns = " + mre.getAssociatedColumns()); //NOI18N
-
- ArrayList associatedColumnObjects = mre.getAssociatedColumnObjects();
- colCount = ((associatedColumnObjects != null) ?
- associatedColumnObjects.size() : 0);
- if (colCount > 0)
- {
- println(tabs+1, "--> associatedColumnObjects "); //NOI18N
- for (int j = 0; j < colCount; j++)
- {
- ColumnPairElement fce = (ColumnPairElement) associatedColumnObjects.get(j);
- ColumnElement rce = (fce!=null)?fce.getReferencedColumn():null;
- println(tabs+1, "[" + j + "] " + fce + " -> " + rce); //NOI18N
- }
- println(tabs+1, "<-- associatedColumnObjects "); //NOI18N
- }
- }
- }
- println(tabs, "<-- fields "); //NOI18N
- }
-
- }
-
- // ----- helper methods -----
-
- static String getObjectIdentityTypeRepr(int objectIdentityType)
- {
- switch (objectIdentityType)
- {
- case PersistenceClassElement.APPLICATION_IDENTITY:
- return "APPLICATION_IDENTITY"; //NOI18N
- case PersistenceClassElement.DATABASE_IDENTITY:
- return "DATABASE_IDENTITY_IDENTITY"; //NOI18N
- case PersistenceClassElement.UNMANAGED_IDENTITY:
- return "UNMANAGED_IDENTITY"; //NOI18N
- default:
- return "UNKNOWN"; //NOI18N
- }
- }
-
- static String getPersistenceTypeRepr(int persistenceType)
- {
- switch (persistenceType)
- {
- case PersistenceFieldElement.PERSISTENT:
- return "PERSISTENT"; //NOI18N
- case PersistenceFieldElement.DERIVED:
- return "DERIVED"; //NOI18N
- case PersistenceFieldElement.TRANSIENT:
- return "TRANSIENT"; //NOI18N
- default:
- return "UNKNOWN"; //NOI18N
- }
- }
-
- static void println(int indent, String text)
- {
- for (int i = 0; i < indent; i++)
- {
- System.out.print("\t"); //NOI18N
- }
-
- System.out.println(text);
- }
-}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/LogHelperModel.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/LogHelperModel.java
deleted file mode 100644
index 0978eef502e..00000000000
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/LogHelperModel.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v. 2.0, which is available at
- * http://www.eclipse.org/legal/epl-2.0.
- *
- * This Source Code may also be made available under the following Secondary
- * Licenses when the conditions for such availability set forth in the
- * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
- * version 2 with the GNU Classpath Exception, which is available at
- * https://www.gnu.org/software/classpath/license.html.
- *
- * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
- */
-
-/*
- * LogHelperModel.java
- *
- * Created on May 28, 2002, 5:00 PM
- */
-
-package com.sun.jdo.api.persistence.model.util;
-
-import com.sun.jdo.api.persistence.model.Model;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
-/**
- *
- * @author Rochelle Raccah
- * @version %I%
- */
-public class LogHelperModel
-{
- /** The component name for this component
- */
- private static final String _componentName = "model"; // NOI18N
-
- /** The class loader for this component
- */
- private static final ClassLoader _loader =
- LogHelperModel.class.getClassLoader();
-
- /** Return the logger for the model component
- */
- public static Logger getLogger ()
- {
- return LogHelper.getLogger (_componentName, Model.messageBase, _loader);
- }
-
-}
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidationException.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidationException.java
index 3fb1b9266a0..a6a1e83797e 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidationException.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidationException.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * ModelValidationException.java
- *
- * Created on September 22, 2000, 1:05 PM
- */
-
package com.sun.jdo.api.persistence.model.util;
import com.sun.jdo.api.persistence.model.ModelException;
@@ -30,12 +25,12 @@
import org.glassfish.persistence.common.I18NHelper;
/**
- *
- * @author raccah
- * @version %I%
+ * @author raccah 2000
*/
-public class ModelValidationException extends ModelException
-{
+public class ModelValidationException extends ModelException {
+
+ private static final long serialVersionUID = -8958451369308923338L;
+
/** Constant representing an error. */
public static final int ERROR = 0;
@@ -44,7 +39,7 @@ public class ModelValidationException extends ModelException
/** I18N message handler */
private static final ResourceBundle _messages = I18NHelper.loadBundle(
- "com.sun.jdo.api.persistence.model.Bundle", // NOI18N
+ "com.sun.jdo.api.persistence.model.Bundle",
ModelValidationException.class.getClassLoader());
/** This field holds the type -- one of {@link #ERROR} or {@link #WARNING}
@@ -58,96 +53,103 @@ public class ModelValidationException extends ModelException
/** @return I18N message handler for this element
*/
- protected static final ResourceBundle getMessages ()
- {
+ protected static final ResourceBundle getMessages() {
return _messages;
}
+
/**
* Creates new ModelValidationException of type {@link #ERROR}
* without a detail message and with null as the
* offending object.
*/
- public ModelValidationException ()
- {
+ public ModelValidationException() {
}
+
/**
* Constructs a ModelValidationException of type
* {@link #ERROR} with the specified detail message and
* null as the offending object.
+ *
* @param msg the detail message.
*/
- public ModelValidationException (String msg)
- {
+ public ModelValidationException(String msg) {
super(msg);
}
+
/**
* Constructs a ModelValidationException of type
* {@link #ERROR} with the specified offending object and no
* detail message.
+ *
* @param offendingObject the offending object.
*/
- public ModelValidationException (Object offendingObject)
- {
+ public ModelValidationException(Object offendingObject) {
super();
_offendingObject = offendingObject;
}
+
/**
* Constructs a ModelValidationException of type
* {@link #ERROR} with the specified detail message and offending
* object.
+ *
* @param offendingObject the offending object.
* @param msg the detail message.
*/
- public ModelValidationException (Object offendingObject, String msg)
- {
+ public ModelValidationException(Object offendingObject, String msg) {
this(ERROR, offendingObject, msg);
}
+
/**
* Constructs a ModelValidationException of the specified
- * type with the specified detail message and offending object.
+ * type with the specified detail message and offending object.
+ *
* @param errorType the type -- one of {@link #ERROR} or {@link #WARNING}.
* @param offendingObject the offending object.
* @param msg the detail message.
*/
- public ModelValidationException (int errorType, Object offendingObject,
- String msg)
- {
+ public ModelValidationException(int errorType, Object offendingObject, String msg) {
super(msg);
_type = errorType;
_offendingObject = offendingObject;
}
+
/**
* Get the offending object -- the one being validated when the problem
* occurred.
*/
- public Object getOffendingObject () { return _offendingObject; }
+ public Object getOffendingObject() {
+ return _offendingObject;
+ }
+
/**
* Get the type -- one of {@link #ERROR} or {@link #WARNING}.
*/
- public int getType () { return _type; }
+ public int getType() {
+ return _type;
+ }
+
/**
- * Returns the error message string of this throwable object.
- * @return the error message string of this
- * ModelValidationException, prepended with the warning string
- * if the type is {@link #WARNING}
- *
- */
- public String getMessage ()
- {
+ * Returns the error message string of this throwable object.
+ *
+ * @return the error message string of this
+ * ModelValidationException, prepended with the warning string
+ * if the type is {@link #WARNING}
+ */
+ @Override
+ public String getMessage() {
String message = super.getMessage();
- if ((WARNING == getType()) && !StringHelper.isEmpty(message))
- {
- message = I18NHelper.getMessage(getMessages(),
- "util.validation.warning") + message; //NOI18N
+ if ((WARNING == getType()) && !StringHelper.isEmpty(message)) {
+ message = I18NHelper.getMessage(getMessages(), "util.validation.warning") + message;
}
return message;
diff --git a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidator.java b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidator.java
index 678e289e067..92ef59114ab 100644
--- a/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidator.java
+++ b/appserver/persistence/cmp/model/src/main/java/com/sun/jdo/api/persistence/model/util/ModelValidator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * ModelValidator.java
- *
- * Created on September 22, 2000, 12:49 PM
- */
-
package com.sun.jdo.api.persistence.model.util;
import com.sun.jdo.api.persistence.model.Model;
@@ -33,8 +28,8 @@
import com.sun.jdo.api.persistence.model.mapping.MappingTableElement;
import com.sun.jdo.spi.persistence.utility.JavaTypeHelper;
import com.sun.jdo.spi.persistence.utility.StringHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
+import java.lang.System.Logger;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
@@ -59,13 +54,16 @@
import org.netbeans.modules.dbschema.util.NameUtil;
import org.netbeans.modules.dbschema.util.SQLTypeUtil;
+import static java.lang.System.Logger.Level.DEBUG;
+
/**
*
- * @author Rochelle Raccah
- * @version %I%
+ * @author Rochelle Raccah 2000
*/
-public class ModelValidator
-{
+public class ModelValidator {
+
+ private static final Logger LOG = System.getLogger(ModelValidator.class.getName());
+
/** This field holds the model object used for validation */
private Model _model;
@@ -80,18 +78,18 @@ public class ModelValidator
/** I18N message handler */
private ResourceBundle _messages;
- public ModelValidator (Model model, String className, ResourceBundle bundle)
- {
+ public ModelValidator(Model model, String className, ResourceBundle bundle) {
this(model, className, null, bundle);
}
- /** Create a new model validator object.
+
+ /**
+ * Create a new model validator object.
+ *
* @param model model object used for validation
* @param className the name of the class being validated
*/
- public ModelValidator (Model model, String className,
- ClassLoader classLoader, ResourceBundle bundle)
- {
+ public ModelValidator(Model model, String className, ClassLoader classLoader, ResourceBundle bundle) {
_model = model;
_className = className;
_classLoader = classLoader;
@@ -128,20 +126,15 @@ public ModelValidator (Model model, String className,
* false otherwise.
* @see #getBasicValidationList
*/
- public boolean parseCheck ()
- {
- Iterator iterator = getBasicValidationList().iterator();
-
- try
- {
- while (iterator.hasNext())
- ((ValidationComponent)iterator.next()).validate();
- }
- catch (ModelValidationException e)
- {
- LogHelperModel.getLogger().log(Logger.FINER,
- "model.parse_error", e); // NOI18N
+ public boolean parseCheck() {
+ Iterator iterator = getBasicValidationList().iterator();
+ try {
+ while (iterator.hasNext()) {
+ iterator.next().validate();
+ }
+ } catch (ModelValidationException e) {
+ LOG.log(DEBUG, "Errors during persistence validation", e);
return false;
}
@@ -157,19 +150,14 @@ public boolean parseCheck ()
* encountered, the collection will be empty, not null.
* @see #getFullValidationList
*/
- public Collection fullValidationCheck ()
- {
- ArrayList list = new ArrayList();
- Iterator iterator = getFullValidationList().iterator();
-
- while (iterator.hasNext())
- {
- try
- {
- ((ValidationComponent)iterator.next()).validate();
- }
- catch (ModelValidationException e)
- {
+ public Collection fullValidationCheck() {
+ ArrayList list = new ArrayList<>();
+ Iterator iterator = getFullValidationList().iterator();
+
+ while (iterator.hasNext()) {
+ try {
+ iterator.next().validate();
+ } catch (ModelValidationException e) {
list.add(e);
}
}
@@ -187,9 +175,8 @@ public Collection fullValidationCheck ()
* @see #getFieldsValidationList
* @see #getFullValidationList
*/
- public Collection getBasicValidationList ()
- {
- ArrayList list = new ArrayList();
+ public Collection getBasicValidationList() {
+ ArrayList list = new ArrayList<>();
String className = getClassName();
list.add(createClassExistenceComponent(className));
@@ -210,15 +197,12 @@ public Collection getBasicValidationList ()
* @see #getRelatedClassValidationList
* @see #getBasicValidationList
*/
- public Collection getFullValidationList ()
- {
- ArrayList list = new ArrayList(getBasicValidationList());
+ public Collection getFullValidationList() {
+ ArrayList list = new ArrayList<>(getBasicValidationList());
String className = getClassName();
- PersistenceClassElement persistenceClass =
- getPersistenceClass(className);
+ PersistenceClassElement persistenceClass = getPersistenceClass(className);
- if (persistenceClass != null)
- {
+ if (persistenceClass != null) {
PersistenceFieldElement[] fields = persistenceClass.getFields();
int i, count = ((fields != null) ? fields.length : 0);
@@ -227,8 +211,7 @@ public Collection getFullValidationList ()
list.add(createClassMappingComponent(persistenceClass));
list.add(createKeyColumnMappingComponent(persistenceClass));
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
PersistenceFieldElement field = fields[i];
list.add(createFieldCardinalityComponent(field));
@@ -241,52 +224,38 @@ public Collection getFullValidationList ()
return Collections.unmodifiableCollection(list);
}
- // ============= Validation list construction suppport methods ============
-
/** Computes and returns a collection of ValidationComponents
* representing the database tests to be performed.
* @return a collection of ValidationComponents representing the
* database tests to be performed.
*/
- private Collection getDatabaseValidationList ()
- {
- ArrayList list = new ArrayList();
+ private Collection getDatabaseValidationList() {
+ ArrayList list = new ArrayList<>();
String className = getClassName();
MappingClassElement mappingClass = getMappingClass(className);
- if (mappingClass != null)
- {
- ArrayList tables = mappingClass.getTables();
- int i, count = ((tables != null) ? tables.size() : 0);
+ if (mappingClass != null) {
+ List tables = mappingClass.getTables();
+ int i, count = tables == null ? 0 : tables.size();
MappingTableElement primaryTable = null;
- Iterator iterator = null;
list.add(createSchemaExistenceComponent(className));
- for (i = 0; i < count; i++)
- {
- MappingTableElement nextTable =
- (MappingTableElement)tables.get(i);
+ for (i = 0; i < count; i++) {
+ MappingTableElement nextTable = tables.get(i);
list.add(createTableExistenceComponent(nextTable.getTable()));
- if (i == 0)
- {
+ if (i == 0) {
primaryTable = nextTable;
list.add(createPrimaryTableComponent(primaryTable));
- }
- else
- {
- MappingReferenceKeyElement referenceKey =
- findReferenceKey(primaryTable, nextTable);
+ } else {
+ MappingReferenceKeyElement referenceKey = findReferenceKey(primaryTable, nextTable);
- if (referenceKey != null)
- {
- iterator = referenceKey.getColumnPairNames().iterator();
- while (iterator.hasNext())
- {
- list.add(createColumnExistenceComponent(
- (String)iterator.next()));
+ if (referenceKey != null) {
+ Iterator iterator = referenceKey.getColumnPairNames().iterator();
+ while (iterator.hasNext()) {
+ list.add(createColumnExistenceComponent(iterator.next()));
}
}
}
@@ -294,27 +263,20 @@ private Collection getDatabaseValidationList ()
list.add(createVersionConsistencyComponent(mappingClass));
- iterator = mappingClass.getFields().iterator();
- while (iterator.hasNext())
- {
- MappingFieldElement nextField =
- (MappingFieldElement)iterator.next();
- ArrayList allColumns = new ArrayList();
- Iterator columnIterator = null;
+ Iterator iterator = mappingClass.getFields().iterator();
+ while (iterator.hasNext()) {
+ MappingFieldElement nextField = iterator.next();
+ ArrayList allColumns = new ArrayList<>();
- if (isRelationship(nextField))
- {
- allColumns.addAll(((MappingRelationshipElement)nextField).
- getAssociatedColumns());
+ if (isRelationship(nextField)) {
+ allColumns.addAll(((MappingRelationshipElement) nextField).getAssociatedColumns());
}
allColumns.addAll(nextField.getColumns());
- columnIterator = allColumns.iterator();
- while (columnIterator.hasNext())
- {
- list.add(createColumnExistenceComponent(
- (String)columnIterator.next(), nextField));
+ Iterator columnIterator = allColumns.iterator();
+ while (columnIterator.hasNext()) {
+ list.add(createColumnExistenceComponent(columnIterator.next(), nextField));
}
}
}
@@ -327,78 +289,69 @@ private Collection getDatabaseValidationList ()
* @return a collection of ValidationComponents representing the
* field and relationship tests to be performed.
*/
- private Collection getFieldsValidationList ()
- {
- ArrayList list = new ArrayList();
+ private Collection getFieldsValidationList() {
+ ArrayList list = new ArrayList<>();
Model model = getModel();
String className = getClassName();
- PersistenceClassElement persistenceClass =
- getPersistenceClass(className);
-
- if (persistenceClass != null)
- {
- PersistenceFieldElement[] fields = persistenceClass.getFields();
- int i, count = ((fields != null) ? fields.length : 0);
- Iterator iterator =
- getMappingClass(className).getFields().iterator();
+ PersistenceClassElement persistenceClass = getPersistenceClass(className);
+ if (persistenceClass == null) {
+ return list;
+ }
+ PersistenceFieldElement[] fields = persistenceClass.getFields();
+ int i, count = ((fields != null) ? fields.length : 0);
+ Iterator iterator = getMappingClass(className).getFields().iterator();
- for (i = 0; i < count; i++)
- {
- PersistenceFieldElement field = fields[i];
+ for (i = 0; i < count; i++) {
+ PersistenceFieldElement field = fields[i];
- list.add(createFieldExistenceComponent(field));
+ list.add(createFieldExistenceComponent(field));
- // even though this is really the validation step, we
- // only want to add the others if the field exists
- if (model.hasField(className, field.getName()))
- {
- list.add(createFieldPersistenceComponent(field));
- list.add(createFieldPersistenceTypeComponent(field));
- list.add(createFieldConsistencyComponent(field));
+ // even though this is really the validation step, we
+ // only want to add the others if the field exists
+ if (model.hasField(className, field.getName())) {
+ list.add(createFieldPersistenceComponent(field));
+ list.add(createFieldPersistenceTypeComponent(field));
+ list.add(createFieldConsistencyComponent(field));
- if (isLegalRelationship(field))
- {
- RelationshipElement rel = (RelationshipElement)field;
+ if (isLegalRelationship(field)) {
+ RelationshipElement rel = (RelationshipElement) field;
- /* user modifiable collection class not yet supported
- list.add(createCollectionClassComponent(rel));*/
- list.add(createElementClassComponent(rel));
- list.add(createRelatedClassMatchesComponent(rel));
- }
+ /*
+ * user modifiable collection class not yet supported
+ * list.add(createCollectionClassComponent(rel));
+ */
+ list.add(createElementClassComponent(rel));
+ list.add(createRelatedClassMatchesComponent(rel));
}
}
+ }
- while (iterator.hasNext())
- {
- MappingFieldElement field =
- (MappingFieldElement)iterator.next();
- String fieldName = field.getName();
+ while (iterator.hasNext()) {
+ MappingFieldElement field = iterator.next();
+ String fieldName = field.getName();
- // only check this if it is not in the jdo model
- if (persistenceClass.getField(fieldName) == null)
- {
- list.add(createFieldExistenceComponent(field));
+ // only check this if it is not in the jdo model
+ if (persistenceClass.getField(fieldName) == null) {
+ list.add(createFieldExistenceComponent(field));
- // even though this is really the validation step, we
- // only want to add the others if the field exists
- if (model.hasField(className, fieldName))
- list.add(createFieldConsistencyComponent(field));
+ // even though this is really the validation step, we
+ // only want to add the others if the field exists
+ if (model.hasField(className, fieldName)) {
+ list.add(createFieldConsistencyComponent(field));
}
+ }
- if (!isRelationship(field))
- list.add(createColumnOverlapComponent(field));
+ if (!isRelationship(field)) {
+ list.add(createColumnOverlapComponent(field));
+ }
- // preliminary fix for CR6239630
- if (Boolean.getBoolean("AllowManagedFieldsInDefaultFetchGroup")) // NOI18N
- {
- // Do nothing - AllowManagedFieldsInDefaultFetchGroup:
- // disabled single model validation test;
- // may use checked read/write access to managed fields
- }
- else
- {
- list.add(createFieldDefaultFetchGroupComponent(field));
- }
+ // preliminary fix for CR6239630
+ if (Boolean.getBoolean("AllowManagedFieldsInDefaultFetchGroup")) {
+ // Do nothing - AllowManagedFieldsInDefaultFetchGroup:
+ // disabled single model validation test;
+ // may use checked read/write access to managed fields
+ } else {
+ list.add(createFieldDefaultFetchGroupComponent(field));
}
}
@@ -413,88 +366,68 @@ private Collection getFieldsValidationList ()
* @return a collection of ValidationComponents representing the
* related class tests to be performed.
*/
- private Collection getRelatedClassValidationList (
- PersistenceFieldElement field)
- {
+ private Collection getRelatedClassValidationList (
+ PersistenceFieldElement field) {
String relatedClass = getRelatedClass(field);
- ArrayList list = new ArrayList();
+ ArrayList list = new ArrayList<>();
// even though this is really already included in the validation
// step, we only want to add the extra steps if the field exists
- if ((relatedClass != null) &&
- getModel().hasField(getClassName(), field.getName()))
- {
- MappingClassElement relatedClassElement =
- getMappingClass(relatedClass);
-
- list.add(createClassExistenceComponent(relatedClass, field));
- list.add(createClassPersistenceComponent(relatedClass, field));
- list.add(createSchemaExistenceComponent(relatedClass, field));
- list.add(createRelatedSchemaMatchesComponent(relatedClass, field));
-
- if (relatedClassElement != null)
- {
- ArrayList tables = relatedClassElement.getTables();
- MappingTableElement primaryTable = null;
- boolean hasTables = ((tables != null) && (tables.size() > 0));
-
- if (hasTables)
- {
- primaryTable = (MappingTableElement)tables.get(0);
- list.add(createTableExistenceComponent(
- primaryTable.getTable(), field));
- }
-
- if (isRelationship(field))
- {
- RelationshipElement relElement = (RelationshipElement)field;
- Object rel = getMappingClass(getClassName()).
- getField(field.getName());
-
- list.add(createInverseFieldComponent(relElement));
- list.add(createInverseMappingComponent(relElement));
-
- // verify that the columns from the primary table
- // of the related class are actually from that table
- // since it could have been changed
- if ((rel != null) && isRelationship(rel))
- {
- MappingRelationshipElement relationship =
- (MappingRelationshipElement)rel;
- ArrayList columns =
- relationship.getAssociatedColumns();
- Iterator iterator = null;
+ if (relatedClass == null || !getModel().hasField(getClassName(), field.getName())) {
+ return list;
+ }
+ MappingClassElement relatedClassElement = getMappingClass(relatedClass);
- if ((columns == null) || (columns.size() == 0))
- columns = relationship.getColumns();
+ list.add(createClassExistenceComponent(relatedClass, field));
+ list.add(createClassPersistenceComponent(relatedClass, field));
+ list.add(createSchemaExistenceComponent(relatedClass, field));
+ list.add(createRelatedSchemaMatchesComponent(relatedClass, field));
- if (columns != null)
- {
- List tableNames = new ArrayList();
+ if (relatedClassElement != null) {
+ List tables = relatedClassElement.getTables();
+ MappingTableElement primaryTable = null;
+ boolean hasTables = tables != null && !tables.isEmpty();
+ if (hasTables) {
+ primaryTable = tables.get(0);
+ list.add(createTableExistenceComponent(primaryTable.getTable(), field));
+ }
- if (hasTables)
- {
- Iterator tableIterator = tables.iterator();
+ if (!isRelationship(field)) {
+ return list;
+ }
- while (tableIterator.hasNext())
- {
- tableNames.add(((MappingTableElement)
- tableIterator.next()).getName());
- }
- }
+ RelationshipElement relElement = (RelationshipElement) field;
+ Object rel = getMappingClass(getClassName()).getField(field.getName());
- iterator = columns.iterator();
+ list.add(createInverseFieldComponent(relElement));
+ list.add(createInverseMappingComponent(relElement));
- while (iterator.hasNext())
- {
- list.add(createRelatedTableMatchesComponent(
- relatedClass, field, tableNames,
- (String)iterator.next()));
- }
- }
- }
+ // verify that the columns from the primary table
+ // of the related class are actually from that table
+ // since it could have been changed
+ if (rel == null || !isRelationship(rel)) {
+ return list;
+ }
+ MappingRelationshipElement relationship = (MappingRelationshipElement) rel;
+ List columns = relationship.getAssociatedColumns();
+ if (columns == null || columns.isEmpty()) {
+ columns = relationship.getColumns();
+ }
+ if (columns == null) {
+ return list;
+ }
+ List tableNames = new ArrayList<>();
+ if (hasTables) {
+ Iterator tableIterator = tables.iterator();
+ while (tableIterator.hasNext()) {
+ tableNames.add(tableIterator.next().getName());
}
}
+ Iterator iterator = columns.iterator();
+ while (iterator.hasNext()) {
+ list.add(
+ createRelatedTableMatchesComponent(relatedClass, field, tableNames, iterator.next()));
+ }
}
return list;
@@ -509,18 +442,14 @@ private Collection getRelatedClassValidationList (
* same class as the validator is checking overall
* @return the validation component
*/
- protected ValidationComponent createClassExistenceComponent (
- final String className, final PersistenceFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if ((className == null) ||
- !getModel().hasClass(className, getClassLoader()))
- {
- throw constructClassException(className, relatedField,
- "util.validation.class_not_found"); //NOI18N
+ protected ValidationComponent createClassExistenceComponent(final String className,
+ final PersistenceFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if ((className == null) || !getModel().hasClass(className, getClassLoader())) {
+ throw constructClassException(className, relatedField, "util.validation.class_not_found");
}
}
};
@@ -530,9 +459,7 @@ public void validate () throws ModelValidationException
* @param className the class whose existence is being checked
* @return the validation component
*/
- protected ValidationComponent createClassExistenceComponent (
- final String className)
- {
+ protected ValidationComponent createClassExistenceComponent(final String className) {
return createClassExistenceComponent(className, null);
}
@@ -543,29 +470,25 @@ protected ValidationComponent createClassExistenceComponent (
* same class as the validator is checking overall
* @return the validation component
*/
- protected ValidationComponent createClassPersistenceComponent (
- final String className, final PersistenceFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createClassPersistenceComponent(final String className,
+ final PersistenceFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
Model model = getModel();
- if ((className != null) &&
- model.hasClass(className, getClassLoader()))
- {
+ if ((className != null) && model.hasClass(className, getClassLoader())) {
String key = null;
- if (!isPersistent(className))
- key = "util.validation.class_not_persistence_capable";//NOI18N
- else if (!model.isPersistenceCapableAllowed(className))
- key = "util.validation.class_not_allowed";//NOI18N
+ if (!isPersistent(className)) {
+ key = "util.validation.class_not_persistence_capable";
+ } else if (!model.isPersistenceCapableAllowed(className)) {
+ key = "util.validation.class_not_allowed";
+ }
- if (key != null)
- {
- throw constructClassException(
- className, relatedField, key);
+ if (key != null) {
+ throw constructClassException(className, relatedField, key);
}
}
}
@@ -576,38 +499,37 @@ else if (!model.isPersistenceCapableAllowed(className))
* @param className the class whose persistence is being checked
* @return the validation component
*/
- protected ValidationComponent createClassPersistenceComponent (
- final String className)
- {
+ protected ValidationComponent createClassPersistenceComponent(final String className) {
return createClassPersistenceComponent(className, null);
}
- /** Create a validation component which can check whether the field exists.
+
+ /**
+ * Create a validation component which can check whether the field exists.
+ *
* @param fieldName the field whose existence is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldExistenceComponent (
- final String fieldName)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (!getModel().hasField(getClassName(), fieldName))
- {
- throw constructFieldException(fieldName,
- "util.validation.field_not_found"); //NOI18N
+ protected ValidationComponent createFieldExistenceComponent(final String fieldName) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (!getModel().hasField(getClassName(), fieldName)) {
+ throw constructFieldException(fieldName, "util.validation.field_not_found");
}
}
};
}
- /** Create a validation component which can check whether the field exists.
+
+ /**
+ * Create a validation component which can check whether the field exists.
+ *
* @param field the field whose existence is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldExistenceComponent (Object field)
- {
+ protected ValidationComponent createFieldExistenceComponent(Object field) {
return createFieldExistenceComponent(field.toString());
}
@@ -616,22 +538,16 @@ protected ValidationComponent createFieldExistenceComponent (Object field)
* @param field the field whose persistence is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldPersistenceComponent (
- final PersistenceFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- boolean isPersistent = (PersistenceFieldElement.PERSISTENT ==
- field.getPersistenceType());
+ protected ValidationComponent createFieldPersistenceComponent(final PersistenceFieldElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ boolean isPersistent = (PersistenceFieldElement.PERSISTENT == field.getPersistenceType());
String fieldName = field.getName();
- if (isPersistent &&
- !isPersistentAllowed(getClassName(), fieldName))
- {
- throw constructFieldException(fieldName,
- "util.validation.field_persistent_not_allowed");//NOI18N
+ if (isPersistent && !isPersistentAllowed(getClassName(), fieldName)) {
+ throw constructFieldException(fieldName, "util.validation.field_persistent_not_allowed");
}
}
};
@@ -647,6 +563,7 @@ protected ValidationComponent createFieldConsistencyComponent (
{
return new ValidationComponent ()
{
+ @Override
public void validate () throws ModelValidationException
{
String fieldName = field.getName();
@@ -669,7 +586,7 @@ public void validate () throws ModelValidationException
if (jdoIsRelationship != isRelationship(mappingElement))
{
throw constructFieldException(fieldName,
- "util.validation.field_type_inconsistent"); //NOI18N
+ "util.validation.field_type_inconsistent");
}
}
}
@@ -687,6 +604,7 @@ protected ValidationComponent createFieldConsistencyComponent (
{
return new ValidationComponent ()
{
+ @Override
public void validate () throws ModelValidationException
{
if (field != null)
@@ -701,7 +619,7 @@ public void validate () throws ModelValidationException
if (persistenceElement == null)
{
throw constructFieldException(fieldName,
- "util.validation.field_model_inconsistent");//NOI18N
+ "util.validation.field_model_inconsistent");
}
}
}
@@ -713,32 +631,23 @@ public void validate () throws ModelValidationException
* @param field the field whose persistence type is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldPersistenceTypeComponent (
- final PersistenceFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createFieldPersistenceTypeComponent(final PersistenceFieldElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String fieldName = field.getName();
String className = getClassName();
- boolean isLegallyPersistent =
- isPersistentAllowed(className, fieldName);
+ boolean isLegallyPersistent = isPersistentAllowed(className, fieldName);
- if (isLegallyPersistent)
- {
+ if (isLegallyPersistent) {
boolean isRelationship = isRelationship(field);
boolean mustBeRelationship = shouldBeRelationship(field);
- if (isRelationship && !mustBeRelationship)
- {
- throw constructFieldException(fieldName,
- "util.validation.field_relationship_not_allowed");//NOI18N
- }
- else if (!isRelationship && mustBeRelationship)
- {
- throw constructFieldException(fieldName,
- "util.validation.field_type_not_allowed"); //NOI18N
+ if (isRelationship && !mustBeRelationship) {
+ throw constructFieldException(fieldName, "util.validation.field_relationship_not_allowed");
+ } else if (!isRelationship && mustBeRelationship) {
+ throw constructFieldException(fieldName, "util.validation.field_type_not_allowed");
}
}
}
@@ -750,146 +659,129 @@ else if (!isRelationship && mustBeRelationship)
* @param field the relationship whose cardinality bounds are being checked
* @return the validation component
*/
- protected ValidationComponent createFieldCardinalityComponent (
- final PersistenceFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (isLegalRelationship(field))
- {
- RelationshipElement relationship =
- (RelationshipElement)field;
+ protected ValidationComponent createFieldCardinalityComponent(final PersistenceFieldElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (isLegalRelationship(field)) {
+ RelationshipElement relationship = (RelationshipElement) field;
String fieldName = field.getName();
- boolean nonCollectionRelationship =
- !isCollection(getClassName(), fieldName);
- int upperBound = (nonCollectionRelationship ?
- 1 : relationship.getUpperBound());
+ boolean nonCollectionRelationship = !isCollection(getClassName(), fieldName);
+ int upperBound = (nonCollectionRelationship ? 1 : relationship.getUpperBound());
int lowerBound = relationship.getLowerBound();
MappingRelationshipElement mapping = null;
- if ((lowerBound < 0) || (upperBound <= 0) ||
- (lowerBound > upperBound))
- {
- throw constructFieldException(fieldName,
- "util.validation.cardinality_invalid"); //NOI18N
+ if ((lowerBound < 0) || (upperBound <= 0) || (lowerBound > upperBound)) {
+ throw constructFieldException(fieldName, "util.validation.cardinality_invalid");
}
// now check specific lower bound requirements imposed
// by the mapping
mapping = getMappingRelationship(relationship);
- if (nonCollectionRelationship && (lowerBound != 1) &&
- (mapping != null) && !isJoin(mapping))
- {
+ if (nonCollectionRelationship && (lowerBound != 1) && (mapping != null) && !isJoin(mapping)) {
// If the non-collection relationship field is exactly
// mapped to a FK, we need to check the nullability
// of the columns. If there are any non-nullable
// columns the lower bound must be 1.
ForeignKeyElement fk = getMatchingFK(mapping);
- if ((fk != null) && hasNonNullableColumn(fk))
- {
- throw constructFieldException(fieldName,
- "util.validation.lower_bound_invalid"); //NOI18N
+ if ((fk != null) && hasNonNullableColumn(fk)) {
+ throw constructFieldException(fieldName, "util.validation.lower_bound_invalid");
}
}
}
}
- /** Returns true if the specified FK has at least
+
+ /**
+ * Returns true if the specified FK has at least
* one non-nullable column. Please note that the caller is
* responsible for passing a non-null fk argument.
*/
- private boolean hasNonNullableColumn (ForeignKeyElement fk)
- {
+ private boolean hasNonNullableColumn(ForeignKeyElement fk) {
ColumnElement[] localColumns = fk.getLocalColumns();
int count = ((localColumns != null) ? localColumns.length : 0);
- for (int i = 0; i < count; i++)
- {
- if (!localColumns[i].isNullable())
+ for (int i = 0; i < count; i++) {
+ if (!localColumns[i].isNullable()) {
return true;
+ }
}
return false;
}
- /** Checks whether the specified relationship is exactly mapped
+
+ /**
+ * Checks whether the specified relationship is exactly mapped
* to a FK. If yes, the method returns the matching FK. If not,
* it returns null. Please note that the caller is
* responsible for passing a non-null mapping argument.
*/
- private ForeignKeyElement getMatchingFK (
- MappingRelationshipElement mapping)
- {
- MappingClassElement mappingClass = mapping.
- getDeclaringClass();
+ private ForeignKeyElement getMatchingFK(MappingRelationshipElement mapping) {
+ MappingClassElement mappingClass = mapping.getDeclaringClass();
String databaseRoot = getSchemaForClass(getClassName());
- List pairNames = mapping.getColumns();
- List tables = mappingClass.getTables();
+ List pairNames = mapping.getColumns();
+ List tables = mappingClass.getTables();
- if (tables != null)
- {
- for (Iterator i = tables.iterator(); i.hasNext();)
- {
- String tableName = ((MappingTableElement)i.next()).
- getName();
+ if (tables != null) {
+ for (Iterator i = tables.iterator(); i.hasNext();) {
+ String tableName = i.next().getName();
TableElement table = getTable(tableName, databaseRoot);
ForeignKeyElement fk = getMatchingFK(pairNames, table);
- if (fk != null)
+ if (fk != null) {
return fk;
+ }
}
}
return null;
}
- /** Checks whether the specified TableElement has a FK that
+
+ /**
+ * Checks whether the specified TableElement has a FK that
* exactly matches the list of column pair names.
+ *
* @return the matching FK if it exactly matches the list
- * of column pairs; null otherwise.
+ * of column pairs; null otherwise.
*/
- private ForeignKeyElement getMatchingFK (List pairNames,
- TableElement table)
- {
- ForeignKeyElement[] foreignKeys = (table != null) ?
- table.getForeignKeys() : null;
+ private ForeignKeyElement getMatchingFK(List pairNames, TableElement table) {
+ ForeignKeyElement[] foreignKeys = table == null ? null : table.getForeignKeys();
int count = ((foreignKeys != null) ? foreignKeys.length : 0);
- for (int i = 0; i < count; i++)
- {
- if (matchesFK(pairNames, foreignKeys[i]))
+ for (int i = 0; i < count; i++) {
+ if (matchesFK(pairNames, foreignKeys[i])) {
return foreignKeys[i];
+ }
}
return null;
}
- /** Returns true if the specified list of column
+
+ /**
+ * Returns true if the specified list of column
* pair names matches exactly the specified FK.
*/
- private boolean matchesFK (List pairNames,
- ForeignKeyElement foreignKey)
- {
+ private boolean matchesFK(List pairNames, ForeignKeyElement foreignKey) {
ColumnPairElement[] fkPairs = foreignKey.getColumnPairs();
- int fkCount = ((fkPairs != null) ? fkPairs.length : 0);
- int count = ((pairNames != null) ? pairNames.size() : 0);
+ int fkCount = fkPairs == null ? 0 : fkPairs.length;
+ int count = pairNames == null ? 0 : pairNames.size();
// First check whether the list of fk column pairs has the
// same size than the specified list of columns.
- if (fkCount == count)
- {
+ if (fkCount == count) {
// Now check whether each fk column is included in the
// specified list of columns.
- for (int i = 0; i < fkCount; i++)
- {
- String fkPairName = NameUtil.getRelativeMemberName(
- fkPairs[i].getName().getFullName());
+ for (int i = 0; i < fkCount; i++) {
+ String fkPairName = NameUtil.getRelativeMemberName(fkPairs[i].getName().getFullName());
- if (!pairNames.contains(fkPairName))
+ if (!pairNames.contains(fkPairName)) {
return false;
+ }
}
return true;
@@ -900,35 +792,29 @@ private boolean matchesFK (List pairNames,
};
}
- /** Create a validation component which can check whether the field is
+
+ /**
+ * Create a validation component which can check whether the field is
* unmapped.
+ *
* @param field the field whose mapping is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldMappingComponent (
- final PersistenceFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- String fieldName = field.getName();
- MappingClassElement mappingClass =
- getMappingClass(getClassName());
+ protected ValidationComponent createFieldMappingComponent(final PersistenceFieldElement field) {
+ return new ValidationComponent() {
- if ((mappingClass != null) &&
- (mappingClass.getTables().size() > 0))
- {
- MappingFieldElement mappingField =
- mappingClass.getField(fieldName);
+ @Override
+ public void validate() throws ModelValidationException {
+ String fieldName = field.getName();
+ MappingClassElement mappingClass = getMappingClass(getClassName());
- if ((mappingField == null) ||
- (mappingField.getColumns().size() == 0))
- {
- throw constructFieldException(
- ModelValidationException.WARNING, fieldName,
- "util.validation.field_not_mapped"); //NOI18N
- }
+ if (mappingClass == null || mappingClass.getTables().isEmpty()) {
+ return;
+ }
+ MappingFieldElement mappingField = mappingClass.getField(fieldName);
+ if (mappingField == null || mappingField.getColumns().isEmpty()) {
+ throw constructFieldException(ModelValidationException.WARNING, fieldName,
+ "util.validation.field_not_mapped");
}
}
};
@@ -943,102 +829,82 @@ public void validate () throws ModelValidationException
* is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldBlobMappingComponent (
- final PersistenceFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createFieldBlobMappingComponent(final PersistenceFieldElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String className = getClassName();
String fieldName = field.getName();
MappingClassElement mappingClass = getMappingClass(className);
- MappingFieldElement mappingField = ((mappingClass != null) ?
- mappingClass.getField(fieldName) : null);
+ MappingFieldElement mappingField = mappingClass == null ? null : mappingClass.getField(fieldName);
- if (mappingField != null)
- {
+ if (mappingField != null) {
boolean isKey = field.isKey();
- if (isKey || (MappingFieldElement.GROUP_DEFAULT ==
- mappingField.getFetchGroup()))
- {
- if (isMappedToBlob(mappingField,
- getSchemaForClass(className)))
- {
- throw constructFieldException(fieldName, (isKey ?
- "util.validation.field_key_field_not_allowed" : //NOI18N
- "util.validation.field_fetch_group_not_allowed")); // NOI18N
+ if (isKey || (MappingFieldElement.GROUP_DEFAULT == mappingField.getFetchGroup())) {
+ if (isMappedToBlob(mappingField, getSchemaForClass(className))) {
+ throw constructFieldException(fieldName,
+ (isKey ? "util.validation.field_key_field_not_allowed"
+ : "util.validation.field_fetch_group_not_allowed"));
}
}
}
}
- private boolean isMappedToBlob (MappingFieldElement mappingField,
- String schema)
- {
- if (mappingField instanceof MappingRelationshipElement)
- {
- return isMappedToBlob(
- (MappingRelationshipElement)mappingField, schema);
+
+
+ private boolean isMappedToBlob(MappingFieldElement mappingField, String schema) {
+ if (mappingField instanceof MappingRelationshipElement) {
+ return isMappedToBlob((MappingRelationshipElement) mappingField, schema);
}
- else
- {
- Iterator iterator = mappingField.getColumns().iterator();
+ Iterator iterator = mappingField.getColumns().iterator();
+ while (iterator.hasNext()) {
+ String absoluteName = NameUtil.getAbsoluteMemberName(schema, iterator.next());
+ TableElement table = TableElement.forName(NameUtil.getTableName(absoluteName));
+ ColumnElement columnElement = ((table != null)
+ ? (ColumnElement) table.getMember(DBIdentifier.create(absoluteName))
+ : null);
- while (iterator.hasNext())
- {
- String absoluteName = NameUtil.getAbsoluteMemberName(
- schema, (String)iterator.next());
- TableElement table = TableElement.forName(
- NameUtil.getTableName(absoluteName));
- ColumnElement columnElement = ((table != null) ?
- (ColumnElement)table.getMember(
- DBIdentifier.create(absoluteName)) : null);
-
- if (isMappedToBlob(columnElement))
- return true;
+ if (isMappedToBlob(columnElement)) {
+ return true;
}
}
return false;
}
- private boolean isMappedToBlob (MappingRelationshipElement rel,
- String schema)
- {
- Iterator iterator = rel.getColumns().iterator();
- while (iterator.hasNext())
- {
- ColumnPairElement pair =
- getPair((String)iterator.next(), schema);
- if (isMappedToBlob(pair))
+ private boolean isMappedToBlob(MappingRelationshipElement rel, String schema) {
+ Iterator iterator = rel.getColumns().iterator();
+ while (iterator.hasNext()) {
+ ColumnPairElement pair = getPair(iterator.next(), schema);
+ if (isMappedToBlob(pair)) {
return true;
+ }
}
// now check join columns
iterator = rel.getAssociatedColumns().iterator();
- while (iterator.hasNext())
- {
- ColumnPairElement pair =
- getPair((String)iterator.next(), schema);
+ while (iterator.hasNext()) {
+ ColumnPairElement pair = getPair(iterator.next(), schema);
- if (isMappedToBlob(pair))
+ if (isMappedToBlob(pair)) {
return true;
+ }
}
return false;
}
- private boolean isMappedToBlob (ColumnPairElement pair)
- {
- return ((pair == null) ? false :
- isMappedToBlob(pair.getLocalColumn()) &&
- isMappedToBlob(pair.getReferencedColumn()));
+
+
+ private boolean isMappedToBlob(ColumnPairElement pair) {
+ return ((pair == null) ? false
+ : isMappedToBlob(pair.getLocalColumn()) && isMappedToBlob(pair.getReferencedColumn()));
}
- private boolean isMappedToBlob (ColumnElement column)
- {
- return ((column != null) &&
- SQLTypeUtil.isBlob(column.getType()));
+
+
+ private boolean isMappedToBlob(ColumnElement column) {
+ return ((column != null) && SQLTypeUtil.isBlob(column.getType()));
}
};
}
@@ -1048,30 +914,23 @@ private boolean isMappedToBlob (ColumnElement column)
* @param field the relationship whose collection class is being checked
* @return the validation component
*/
- protected ValidationComponent createCollectionClassComponent (
- final RelationshipElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createCollectionClassComponent(final RelationshipElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String className = getClassName();
String fieldName = field.getName();
- if (isCollection(className, fieldName))
- {
+ if (isCollection(className, fieldName)) {
Model model = getModel();
String collectionClass = field.getCollectionClass();
String fieldType = model.getFieldType(className, fieldName);
- boolean missingCollectionClass =
- StringHelper.isEmpty(collectionClass);
+ boolean missingCollectionClass = StringHelper.isEmpty(collectionClass);
- if (!missingCollectionClass &&
- !model.getSupportedCollectionClasses(fieldType).
- contains(collectionClass))
- {
- throw constructFieldException(fieldName,
- "util.validation.collection_class_invalid");//NOI18N
+ if (!missingCollectionClass
+ && !model.getSupportedCollectionClasses(fieldType).contains(collectionClass)) {
+ throw constructFieldException(fieldName, "util.validation.collection_class_invalid");
}
}
}
@@ -1083,33 +942,24 @@ public void validate () throws ModelValidationException
* @param field the relationship whose element class is being checked
* @return the validation component
*/
- protected ValidationComponent createElementClassComponent (
- final RelationshipElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createElementClassComponent(final RelationshipElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String className = getClassName();
String fieldName = field.getName();
- if (isCollection(className, fieldName))
- {
+ if (isCollection(className, fieldName)) {
String elementClass = field.getElementClass();
- if (StringHelper.isEmpty(elementClass))
- {
- MappingClassElement mappingClass =
- getMappingClass(className);
- MappingFieldElement mappingElement =
- ((mappingClass != null) ?
- mappingClass.getField(fieldName) : null);
-
- if ((mappingElement != null) &&
- (mappingElement.getColumns().size() > 0))
- {
- throw constructFieldException(fieldName,
- "util.validation.element_class_not_found");//NOI18N
+ if (StringHelper.isEmpty(elementClass)) {
+ MappingClassElement mappingClass = getMappingClass(className);
+ MappingFieldElement mappingElement = mappingClass == null ? null
+ : mappingClass.getField(fieldName);
+
+ if (mappingElement != null && !mappingElement.getColumns().isEmpty()) {
+ throw constructFieldException(fieldName, "util.validation.element_class_not_found");
}
}
}
@@ -1136,34 +986,25 @@ public void validate () throws ModelValidationException
* checked
* @return the validation component
*/
- protected ValidationComponent createVersionConsistencyComponent (
- final MappingClassElement mappingClass)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createVersionConsistencyComponent(final MappingClassElement mappingClass) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
// only bother to check for classes with version consistency
- if (MappingClassElement.VERSION_CONSISTENCY ==
- mappingClass.getConsistencyLevel())
- {
- MappingFieldElement versionField =
- validateVersionFieldExistence();
+ if (MappingClassElement.VERSION_CONSISTENCY == mappingClass.getConsistencyLevel()) {
+ MappingFieldElement versionField = validateVersionFieldExistence();
String className = mappingClass.getName();
String fieldName = versionField.getName();
String columnName = null;
ColumnElement column = null;
- if (versionField instanceof MappingRelationshipElement)
- {
+ if (versionField instanceof MappingRelationshipElement) {
throw constructFieldException(fieldName,
- "util.validation.version_field_relationship_not_allowed");//NOI18N
- }
- else if (MappingFieldElement.GROUP_DEFAULT !=
- versionField.getFetchGroup()) // must be in DFG
- {
- throw constructFieldException(fieldName,
- "util.validation.version_field_fetch_group_invalid");//NOI18N
+ "util.validation.version_field_relationship_not_allowed");
+ } else if (MappingFieldElement.GROUP_DEFAULT != versionField.getFetchGroup()) {
+ // must be in DFG
+ throw constructFieldException(fieldName, "util.validation.version_field_fetch_group_invalid");
}
validatePersistenceFieldAttributes(className, fieldName);
@@ -1172,140 +1013,128 @@ else if (MappingFieldElement.GROUP_DEFAULT !=
validateColumnAttributes(className, fieldName, column);
}
}
- /** Helper method validating the existence of the exactly one
- * version field.
+
+
+ /**
+ * Helper method validating the existence of the exactly one
+ * version field.
*/
- private MappingFieldElement validateVersionFieldExistence ()
- throws ModelValidationException
- {
- List versionFields = mappingClass.getVersionFields();
+ private MappingFieldElement validateVersionFieldExistence() throws ModelValidationException {
+ List versionFields = mappingClass.getVersionFields();
// must have exactly 1 version field (for this release)
- if (versionFields.size() != 1)
- {
- throw constructClassException(mappingClass.getName(),
- null, "util.validation.version_field_cardinality"); //NOI18N
+ if (versionFields.size() != 1) {
+ throw constructClassException(mappingClass.getName(), null,
+ "util.validation.version_field_cardinality");
}
- return (MappingFieldElement)versionFields.get(0);
+ return versionFields.get(0);
}
- /** Helper method validating the attributes of the field in the
+
+
+ /**
+ * Helper method validating the attributes of the field in the
* jdo model which corresponds to the version field.
*/
- private void validatePersistenceFieldAttributes (String className,
- String fieldName) throws ModelValidationException
- {
- Class fieldType = JavaTypeHelper.getPrimitiveClass(
- getModel().getFieldType(className, fieldName));
+ private void validatePersistenceFieldAttributes(String className, String fieldName)
+ throws ModelValidationException {
+ Class> fieldType = JavaTypeHelper.getPrimitiveClass(getModel().getFieldType(className, fieldName));
String keyName = null;
// must not be a key field
- if (getPersistenceClass(className).getField(fieldName).isKey())
- keyName = "util.validation.version_field_key_field_not_allowed";//NOI18N
- else if (Long.TYPE != fieldType) // must be type long
- keyName = "util.validation.version_field_type_not_allowed";//NOI18N
+ if (getPersistenceClass(className).getField(fieldName).isKey()) {
+ keyName = "util.validation.version_field_key_field_not_allowed";
+ } else if (Long.TYPE != fieldType) { // must be type long
+ keyName = "util.validation.version_field_type_not_allowed";
+ }
- if (keyName != null)
+ if (keyName != null) {
throw constructFieldException(fieldName, keyName);
+ }
}
- /** Helper method validating the column name of the
+
+
+ /**
+ * Helper method validating the column name of the
* version field mapping.
*/
- private String validateVersionFieldMapping (
- MappingFieldElement versionField)
- throws ModelValidationException
- {
- List columns = versionField.getColumns();
+ private String validateVersionFieldMapping(MappingFieldElement versionField)
+ throws ModelValidationException {
+ List columns = versionField.getColumns();
// must be mapped to exactly 1 column (for this release)
- if (columns.size() != 1)
- {
- throw constructFieldException(versionField.getName(),
- "util.validation.version_field_not_mapped"); //NOI18N
+ if (columns.size() != 1) {
+ throw constructFieldException(versionField.getName(), "util.validation.version_field_not_mapped");
}
- return (String)columns.get(0);
+ return columns.get(0);
}
- /** Helper method validating the column mapping of the version
+
+
+ /**
+ * Helper method validating the column mapping of the version
* field is from the primary table.
*/
- private ColumnElement validateTableMatch (String className,
- String fieldName, String columnName)
- throws ModelValidationException
- {
+ private ColumnElement validateTableMatch(String className, String fieldName, String columnName)
+ throws ModelValidationException {
String schema = getSchemaForClass(className);
- String absoluteName =
- NameUtil.getAbsoluteMemberName(schema, columnName);
- TableElement table =
- TableElement.forName(NameUtil.getTableName(absoluteName));
- String primaryName = ((MappingTableElement)mappingClass.
- getTables().get(0)).getName();
+ String absoluteName = NameUtil.getAbsoluteMemberName(schema, columnName);
+ TableElement table = TableElement.forName(NameUtil.getTableName(absoluteName));
+ String primaryName = mappingClass.getTables().get(0).getName();
TableElement pTable = getTable(primaryName, schema);
// column must be from the PT
- if (table != pTable)
- {
- throw new ModelValidationException(
- getModel().getField(className, fieldName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.version_field_table_mismatch", //NOI18N
- new Object[]{columnName, fieldName, className}));
+ if (table != pTable) {
+ throw new ModelValidationException(getModel().getField(className, fieldName),
+ I18NHelper.getMessage(getMessages(), "util.validation.version_field_table_mismatch",
+ new Object[] {columnName, fieldName, className}));
}
- return ((table != null) ? (ColumnElement)table.getMember(
- DBIdentifier.create(absoluteName)) : null);
+ return ((table != null) ? (ColumnElement) table.getMember(DBIdentifier.create(absoluteName)) : null);
}
- /** Helper method validating the attributes of the column of the
+
+
+ /**
+ * Helper method validating the attributes of the column of the
* version field mapping.
*/
- private void validateColumnAttributes (String className,
- String fieldName, ColumnElement column)
- throws ModelValidationException
- {
+ private void validateColumnAttributes(String className, String fieldName, ColumnElement column)
+ throws ModelValidationException {
String keyName = null;
// column must be numeric type and non-nullable
- if (column.isNullable() || !column.isNumericType())
- keyName = "util.validation.version_field_column_type_invalid"; // NOI18N
- else // column must be non-PK and non-FK column
- {
+ if (column.isNullable() || !column.isNumericType()) {
+ keyName = "util.validation.version_field_column_type_invalid";
+ } else {
+ // column must be non-PK and non-FK column
TableElement table = column.getDeclaringTable();
UniqueKeyElement[] uks = table.getUniqueKeys();
ForeignKeyElement[] fks = table.getForeignKeys();
int i, count = ((uks != null) ? uks.length : 0);
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
UniqueKeyElement uk = uks[i];
- if (uk.isPrimaryKey() && Arrays.asList(
- uk.getColumns()).contains(column))
- {
- keyName = "util.validation.version_field_column_pk_invalid"; // NOI18N
+ if (uk.isPrimaryKey() && Arrays.asList(uk.getColumns()).contains(column)) {
+ keyName = "util.validation.version_field_column_pk_invalid";
break;
}
}
count = ((fks != null) ? fks.length : 0);
- for (i = 0; i < count; i++)
- {
+ for (i = 0; i < count; i++) {
ForeignKeyElement fk = fks[i];
- if (Arrays.asList(fk.getLocalColumns()).
- contains(column))
- {
- keyName = "util.validation.version_field_column_fk_invalid"; // NOI18N
+ if (Arrays.asList(fk.getLocalColumns()).contains(column)) {
+ keyName = "util.validation.version_field_column_fk_invalid";
break;
}
}
}
- if (keyName != null)
- {
- throw new ModelValidationException(
- getModel().getField(className, fieldName),
- I18NHelper.getMessage(getMessages(), keyName,
- new Object[]{column.getName(), fieldName, className}));
+ if (keyName != null) {
+ throw new ModelValidationException(getModel().getField(className, fieldName), I18NHelper
+ .getMessage(getMessages(), keyName, new Object[] {column.getName(), fieldName, className}));
}
}
};
@@ -1316,29 +1145,21 @@ private void validateColumnAttributes (String className,
* @param field the relationship whose inverse relationship is being checked
* @return the validation component
*/
- protected ValidationComponent createInverseFieldComponent (
- final RelationshipElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createInverseFieldComponent(final RelationshipElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
Model model = getModel();
- RelationshipElement inverse =
- field.getInverseRelationship(model);
- RelationshipElement inverseInverse = ((inverse != null) ?
- inverse.getInverseRelationship(model) : null);
+ RelationshipElement inverse = field.getInverseRelationship(model);
+ RelationshipElement inverseInverse = ((inverse != null) ? inverse.getInverseRelationship(model) : null);
- if ((inverse != null) &&
- (!field.equals(inverseInverse) || (inverseInverse == null)))
- {
+ if (inverse != null && (!field.equals(inverseInverse) || (inverseInverse == null))) {
String fieldName = field.getName();
- throw new ModelValidationException(
- model.getField(getClassName(), fieldName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.inverse_field_invalid", //NOI18N
- new Object[]{fieldName, inverse.getName()}));
+ throw new ModelValidationException(model.getField(getClassName(), fieldName),
+ I18NHelper.getMessage(getMessages(), "util.validation.inverse_field_invalid",
+ new Object[] {fieldName, inverse.getName()}));
}
}
};
@@ -1350,35 +1171,29 @@ public void validate () throws ModelValidationException
* @param field the relationship whose inverse relationship is being checked
* @return the validation component
*/
- protected ValidationComponent createRelatedClassMatchesComponent (
- final RelationshipElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- String inverseName =
- field.getInverseRelationshipName();
+ protected ValidationComponent createRelatedClassMatchesComponent(final RelationshipElement field) {
+ return new ValidationComponent() {
- if (!StringHelper.isEmpty(inverseName))
- {
+ @Override
+ public void validate() throws ModelValidationException {
+ String inverseName = field.getInverseRelationshipName();
+
+ if (!StringHelper.isEmpty(inverseName)) {
Model model = getModel();
- RelationshipElement inverse =
- field.getInverseRelationship(model);
+ RelationshipElement inverse = field.getInverseRelationship(model);
- if (inverse == null) // no such field in that related class
- {
+ if (inverse == null) {
+ // no such field in that related class
String relatedClass = getRelatedClass(field);
String fieldName = field.getName();
- String key = ((relatedClass != null) ?
- "util.validation.related_class_mismatch" : //NOI18N
- "util.validation.related_class_not_found");//NOI18N
- Object[] args = ((relatedClass != null) ?
- new Object[]{fieldName, inverseName, relatedClass}
- : new Object[]{fieldName, inverseName});
-
- throw new ModelValidationException(
- model.getField(getClassName(), fieldName),
+ String key = ((relatedClass != null)
+ ? "util.validation.related_class_mismatch"
+ : "util.validation.related_class_not_found");
+ Object[] args = ((relatedClass != null)
+ ? new Object[] {fieldName, inverseName, relatedClass}
+ : new Object[] {fieldName, inverseName});
+
+ throw new ModelValidationException(model.getField(getClassName(), fieldName),
I18NHelper.getMessage(getMessages(), key, args));
}
}
@@ -1392,90 +1207,77 @@ public void validate () throws ModelValidationException
* @param field the relationship whose inverse relationship is being checked
* @return the validation component
*/
- protected ValidationComponent createInverseMappingComponent (
- final RelationshipElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createInverseMappingComponent(final RelationshipElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
Model model = getModel();
- RelationshipElement inverse =
- field.getInverseRelationship(model);
+ RelationshipElement inverse = field.getInverseRelationship(model);
- if ((inverse != null) && !isInverseMapping(field, inverse))
- {
+ if ((inverse != null) && !isInverseMapping(field, inverse)) {
String fieldName = field.getName();
- throw new ModelValidationException(
- model.getField(getClassName(), fieldName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.inverse_mapping_mismatch", //NOI18N
- new Object[]{fieldName, inverse.getName()}));
+ throw new ModelValidationException(model.getField(getClassName(), fieldName),
+ I18NHelper.getMessage(getMessages(), "util.validation.inverse_mapping_mismatch",
+ new Object[] {fieldName, inverse.getName()}));
}
}
- private boolean hasMappingRows (MappingRelationshipElement field2)
- {
- if (field2 != null)
- {
- ArrayList columns = field2.getColumns();
- return ((columns != null) && !columns.isEmpty());
+
+ private boolean hasMappingRows(MappingRelationshipElement field2) {
+ if (field2 != null) {
+ List columns = field2.getColumns();
+
+ return columns != null && !columns.isEmpty();
}
return false;
}
- private boolean isInverseMapping (RelationshipElement jdoField1,
- RelationshipElement jdoField2)
- {
- MappingRelationshipElement field1 =
- getMappingRelationship(jdoField1);
- MappingRelationshipElement field2 =
- getMappingRelationship(jdoField2);
+
+
+ private boolean isInverseMapping(RelationshipElement jdoField1, RelationshipElement jdoField2) {
+ MappingRelationshipElement field1 = getMappingRelationship(jdoField1);
+ MappingRelationshipElement field2 = getMappingRelationship(jdoField2);
boolean field1HasMapping = hasMappingRows(field1);
boolean field2HasMapping = hasMappingRows(field2);
// if both have rows, they must be exact inverses
- if (field1HasMapping && field2HasMapping)
- {
+ if (field1HasMapping && field2HasMapping) {
boolean field1IsJoin = isJoin(field1);
- if (field1IsJoin == isJoin(field2))
- {
- ArrayList pairs1 = field1.getColumns();
- ArrayList pairs2 = field2.getColumns();
+ if (field1IsJoin == isJoin(field2)) {
+ List pairs1 = field1.getColumns();
+ List pairs2 = field2.getColumns();
- return ((!field1IsJoin) ? isInverse(pairs1, pairs2) :
- (isInverse(pairs1,
- field2.getAssociatedColumns()) &&
- isInverse(field1.getAssociatedColumns(), pairs2)));
+ if (field1IsJoin) {
+ return isInverse(pairs1, field2.getAssociatedColumns())
+ && isInverse(field1.getAssociatedColumns(), pairs2);
+ }
+ return isInverse(pairs1, pairs2);
}
return false;
}
// if neither have rows that's fine
- return (field1HasMapping == field2HasMapping);
+ return field1HasMapping == field2HasMapping;
}
- private boolean isInverse (ArrayList pairs1, ArrayList pairs2)
- {
+
+ private boolean isInverse(List pairs1, List pairs2) {
int i, size1 = pairs1.size(), size2 = pairs2.size();
- if (size1 == size2)
- {
- for (i = 0; i < size1; i++)
- {
- String nextPair = (String)pairs1.get(i);
- String inversePair = (String)pairs2.get(i);
+ if (size1 == size2) {
+ for (i = 0; i < size1; i++) {
+ String nextPair = pairs1.get(i);
+ String inversePair = pairs2.get(i);
int semicolonIndex1 = nextPair.indexOf(';');
int semicolonIndex2 = inversePair.indexOf(';');
- if (((semicolonIndex1 == -1) || (semicolonIndex2 == -1))
- || (!nextPair.substring(0, semicolonIndex1).equals(
- inversePair.substring(semicolonIndex2 + 1)) ||
- !nextPair.substring(semicolonIndex1 + 1).equals(
- inversePair.substring(0, semicolonIndex2))))
- {
+ if (((semicolonIndex1 == -1) || (semicolonIndex2 == -1)) || (!nextPair
+ .substring(0, semicolonIndex1).equals(inversePair.substring(semicolonIndex2 + 1))
+ || !nextPair.substring(semicolonIndex1 + 1)
+ .equals(inversePair.substring(0, semicolonIndex2)))) {
return false;
}
}
@@ -1495,87 +1297,65 @@ private boolean isInverse (ArrayList pairs1, ArrayList pairs2)
* @param field the field whose fetch group is being checked
* @return the validation component
*/
- protected ValidationComponent createFieldDefaultFetchGroupComponent (
- final MappingFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (field != null)
- {
- String fieldName = field.getName();
- PersistenceClassElement persistenceClass =
- getPersistenceClass(getClassName());
- PersistenceFieldElement pElement =
- ((persistenceClass != null) ?
- persistenceClass.getField(fieldName) : null);
+ protected ValidationComponent createFieldDefaultFetchGroupComponent(final MappingFieldElement field) {
+ return new ValidationComponent() {
- if ((pElement != null) && !pElement.isKey() &&
- (MappingFieldElement.GROUP_DEFAULT ==
- field.getFetchGroup()))
- {
- MappingClassElement mappingClass =
- field.getDeclaringClass();
- boolean isVersionField =
- ((MappingClassElement.VERSION_CONSISTENCY ==
- mappingClass.getConsistencyLevel()) &&
- field.isVersion());
- Iterator iterator = mappingClass.getFields().iterator();
- String exceptionKey = (!isVersionField ?
- "util.validation.field_fetch_group_invalid"://NOI18N
- "util.validation.version_field_column_invalid");//NOI18N
-
- /* rules:
- * primitive, primitive -> error if exact match of
- * columns
- * primitive, relationship OR
- * relationship, primitive -> error if non-collection
- * relationship and none of the relationship's
- * columns are PK columns and any are present in
- * the primitive's list
- * relationship, relationship -> error if exact
- * match of mapping (local, join, associated),
- * but order is not important
+ @Override
+ public void validate() throws ModelValidationException {
+ if (field != null) {
+ String fieldName = field.getName();
+ PersistenceClassElement persistenceClass = getPersistenceClass(getClassName());
+ PersistenceFieldElement pElement = ((persistenceClass != null)
+ ? persistenceClass.getField(fieldName)
+ : null);
+
+ if ((pElement != null) && !pElement.isKey()
+ && (MappingFieldElement.GROUP_DEFAULT == field.getFetchGroup())) {
+ MappingClassElement mappingClass = field.getDeclaringClass();
+ boolean isVersionField = ((MappingClassElement.VERSION_CONSISTENCY == mappingClass
+ .getConsistencyLevel()) && field.isVersion());
+ Iterator iterator = mappingClass.getFields().iterator();
+ String exceptionKey = (!isVersionField ? "util.validation.field_fetch_group_invalid"
+ : "util.validation.version_field_column_invalid");
+
+ /*
+ * rules:
+ * primitive, primitive -> error if exact match of
+ * columns
+ * primitive, relationship OR
+ * relationship, primitive -> error if non-collection
+ * relationship and none of the relationship's
+ * columns are PK columns and any are present in
+ * the primitive's list
+ * relationship, relationship -> error if exact
+ * match of mapping (local, join, associated),
+ * but order is not important
*/
- while (iterator.hasNext())
- {
- MappingFieldElement testField =
- (MappingFieldElement)iterator.next();
-
- if (isManaged(field, testField) ||
- isManaged(testField, field))
- {
- throw constructFieldException(
- fieldName, exceptionKey);
- }
- else if (!testField.equals(field) && isExactMatch(
- field, testField))
- {
- throw constructFieldException(
- fieldName, exceptionKey);
+ while (iterator.hasNext()) {
+ MappingFieldElement testField = iterator.next();
+
+ if (isManaged(field, testField) || isManaged(testField, field)) {
+ throw constructFieldException(fieldName, exceptionKey);
+ } else if (!testField.equals(field) && isExactMatch(field, testField)) {
+ throw constructFieldException(fieldName, exceptionKey);
}
}
}
}
}
- private boolean isManaged (MappingFieldElement primField,
- MappingFieldElement relField)
- {
+
+
+ private boolean isManaged(MappingFieldElement primField, MappingFieldElement relField) {
String className = getClassName();
- if (!isRelationship(primField) && isRelationship(relField) &&
- !isCollection(className, relField.getName()))
- {
- ArrayList columns = primField.getColumns();
- Iterator iterator = relField.getColumns().iterator();
+ if (!isRelationship(primField) && isRelationship(relField)
+ && !isCollection(className, relField.getName())) {
+ List columns = primField.getColumns();
+ Iterator iterator = relField.getColumns().iterator();
String databaseRoot = getSchemaForClass(className);
- while (iterator.hasNext())
- {
- if (!testColumn(getLocalColumn((String)iterator.next(),
- databaseRoot), columns))
- {
+ while (iterator.hasNext()) {
+ if (!testColumn(getLocalColumn(iterator.next(), databaseRoot), columns)) {
return true;
}
}
@@ -1583,78 +1363,62 @@ private boolean isManaged (MappingFieldElement primField,
return false;
}
- private boolean testColumn (ColumnElement column,
- ArrayList masterList)
- {
- if ((column != null) && !isPrimaryKeyColumn(column))
- {
- return !masterList.contains(NameUtil.
- getRelativeMemberName(column.getName().getFullName()));
+
+ private boolean testColumn(ColumnElement column, List masterList) {
+ if ((column != null) && !isPrimaryKeyColumn(column)) {
+ return !masterList.contains(NameUtil.getRelativeMemberName(column.getName().getFullName()));
}
return true;
}
- private ColumnElement getLocalColumn (String pairName,
- String databaseRoot)
- {
+
+ private ColumnElement getLocalColumn(String pairName, String databaseRoot) {
ColumnPairElement pair = getPair(pairName, databaseRoot);
return ((pair != null) ? pair.getLocalColumn() : null);
}
- private boolean isPrimaryKeyColumn (ColumnElement column)
- {
- if (column != null)
- {
+
+ private boolean isPrimaryKeyColumn(ColumnElement column) {
+ if (column != null) {
KeyElement key = column.getDeclaringTable().getPrimaryKey();
- return ((key != null) &&
- (key.getColumn(column.getName()) != null));
+ return ((key != null) && (key.getColumn(column.getName()) != null));
}
return false;
}
- private boolean isExactMatch (ArrayList columns1,
- ArrayList columns2)
- {
- int count = columns1.size();
- if ((count > 0) && (count == columns2.size()))
- return getDifference(columns1, columns2).isEmpty();
+ private boolean isExactMatch(List list, List list2) {
+ int count = list.size();
+
+ if ((count > 0) && (count == list2.size())) {
+ return getDifference(list, list2).isEmpty();
+ }
return false;
}
- private boolean isExactMatch (MappingFieldElement field1,
- MappingFieldElement field2)
- {
+
+ private boolean isExactMatch(MappingFieldElement field1, MappingFieldElement field2) {
boolean field1IsRel = isRelationship(field1);
boolean match = false;
// both primitives, or both relationships
- if (field1IsRel == isRelationship(field2))
- {
- match = isExactMatch(field1.getColumns(),
- field2.getColumns());
+ if (field1IsRel == isRelationship(field2)) {
+ match = isExactMatch(field1.getColumns(), field2.getColumns());
- if (match && field1IsRel)
- {
- MappingRelationshipElement rel1 =
- (MappingRelationshipElement)field1;
- MappingRelationshipElement rel2 =
- (MappingRelationshipElement)field2;
+ if (match && field1IsRel) {
+ MappingRelationshipElement rel1 = (MappingRelationshipElement) field1;
+ MappingRelationshipElement rel2 = (MappingRelationshipElement) field2;
boolean field1IsJoin = isJoin(rel1);
// both join relationships or both direct
- if (field1IsJoin == isJoin(rel2))
- {
- if (field1IsJoin)
- {
- match = isExactMatch(
- rel1.getAssociatedColumns(),
- rel2.getAssociatedColumns());
+ if (field1IsJoin == isJoin(rel2)) {
+ if (field1IsJoin) {
+ match = isExactMatch(rel1.getAssociatedColumns(), rel2.getAssociatedColumns());
}
- }
- else
+ } else {
match = false;
+ }
}
}
@@ -1670,29 +1434,23 @@ private boolean isExactMatch (MappingFieldElement field1,
* compared
* @return the validation component
*/
- protected ValidationComponent createRelatedSchemaMatchesComponent (
- final String relatedClass, final PersistenceFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (relatedClass != null)
- {
+ protected ValidationComponent createRelatedSchemaMatchesComponent(final String relatedClass,
+ final PersistenceFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (relatedClass != null) {
String className = getClassName();
String mySchema = getSchemaForClass(className);
String relatedSchema = getSchemaForClass(relatedClass);
- if ((mySchema != null) && (relatedSchema != null) &&
- !(relatedSchema.equals(mySchema)))
- {
+ if ((mySchema != null) && (relatedSchema != null) && !(relatedSchema.equals(mySchema))) {
String fieldName = relatedField.getName();
- throw new ModelValidationException(
- getModel().getField(className, fieldName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.schema_mismatch", //NOI18N
- new Object[]{className, relatedClass, fieldName}));
+ throw new ModelValidationException(getModel().getField(className, fieldName),
+ I18NHelper.getMessage(getMessages(), "util.validation.schema_mismatch",
+ new Object[] {className, relatedClass, fieldName}));
}
}
}
@@ -1711,33 +1469,23 @@ public void validate () throws ModelValidationException
* be checked
* @return the validation component
*/
- protected ValidationComponent createRelatedTableMatchesComponent (
- final String relatedClass, final PersistenceFieldElement relatedField,
- final List tableNames, final String pairName)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- ColumnPairElement pair = getPair(pairName,
- getSchemaForClass(relatedClass));
+ protected ValidationComponent createRelatedTableMatchesComponent(final String relatedClass,
+ final PersistenceFieldElement relatedField, final List tableNames, final String pairName) {
+ return new ValidationComponent() {
- if (pair != null)
- {
+ @Override
+ public void validate() throws ModelValidationException {
+ ColumnPairElement pair = getPair(pairName, getSchemaForClass(relatedClass));
+
+ if (pair != null) {
ColumnElement column = pair.getReferencedColumn();
- if (!matchesTable(tableNames, column))
- {
+ if (!matchesTable(tableNames, column)) {
String fieldName = relatedField.getName();
- throw new ModelValidationException(
- getModel().getField(getClassName(), fieldName),
- I18NHelper.getMessage(getMessages(),
- getKey(
- "util.validation.table_mismatch", //NOI18N
- relatedField),
- new Object[]{column.getName().getFullName(),
- fieldName, relatedClass}));
+ throw new ModelValidationException(getModel().getField(getClassName(), fieldName),
+ I18NHelper.getMessage(getMessages(), getKey("util.validation.table_mismatch", relatedField),
+ new Object[] {column.getName().getFullName(), fieldName, relatedClass}));
}
}
}
@@ -1750,12 +1498,11 @@ public void validate () throws ModelValidationException
* being checked
* @return the validation component
*/
- protected ValidationComponent createSchemaExistenceComponent (
- final String className)
- {
+ protected ValidationComponent createSchemaExistenceComponent(final String className) {
return createSchemaExistenceComponent(className, null);
}
+
/** Create a validation component which can check whether the schema of
* the given class exists.
* @param className the class whose mapped schema's existence is
@@ -1766,28 +1513,21 @@ protected ValidationComponent createSchemaExistenceComponent (
* checking overall
* @return the validation component
*/
- protected ValidationComponent createSchemaExistenceComponent (
- final String className, final PersistenceFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createSchemaExistenceComponent(final String className,
+ final PersistenceFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String schemaName = getSchemaForClass(className);
- if ((schemaName != null) &&
- (SchemaElement.forName(schemaName) == null))
- {
- Object[] args = (relatedField == null) ?
- new Object[]{schemaName, className} :
- new Object[]{schemaName, className, relatedField};
+ if ((schemaName != null) && (SchemaElement.forName(schemaName) == null)) {
+ Object[] args = (relatedField == null) ? new Object[] {schemaName, className}
+ : new Object[] {schemaName, className, relatedField};
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- getOffendingObject(relatedField),
- I18NHelper.getMessage(getMessages(), getKey(
- "util.validation.schema_not_found", //NOI18N
- relatedField), args));
+ throw new ModelValidationException(ModelValidationException.WARNING,
+ getOffendingObject(relatedField), I18NHelper.getMessage(getMessages(),
+ getKey("util.validation.schema_not_found", relatedField), args));
}
}
};
@@ -1799,50 +1539,40 @@ public void validate () throws ModelValidationException
* @param primaryTable the primary table for the class
* @return the validation component
*/
- protected ValidationComponent createPrimaryTableComponent (
- final MappingTableElement primaryTable)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (primaryTable != null)
- {
+ protected ValidationComponent createPrimaryTableComponent(final MappingTableElement primaryTable) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (primaryTable != null) {
String className = getClassName();
String schemaName = getSchemaForClass(className);
- if (schemaName == null)
- {
- throw constructClassException(className, null,
- "util.validation.schema_not_set"); //NOI18N
+ if (schemaName == null) {
+ throw constructClassException(className, null, "util.validation.schema_not_set");
}
- else
- {
- String tableName = primaryTable.getName();
- TableElement table = getTable(tableName, schemaName);
+ String tableName = primaryTable.getName();
+ TableElement table = getTable(tableName, schemaName);
- if ((table != null) && (table.getPrimaryKey() == null))
- {
- throw new ModelValidationException(
- getOffendingObject(null),
- I18NHelper.getMessage(getMessages(),
- "util.validation.table_no_primarykey", //NOI18N
- new Object[]{tableName, className}));
- }
+ if (table != null && table.getPrimaryKey() == null) {
+ throw new ModelValidationException(getOffendingObject(null),
+ I18NHelper.getMessage(getMessages(), "util.validation.table_no_primarykey",
+ new Object[] {tableName, className}));
}
}
}
};
}
- /** Create a validation component which can check whether the given table
+
+ /**
+ * Create a validation component which can check whether the given table
* exists.
+ *
* @param tableName the table whose existence is being checked
* @return the validation component
*/
- protected ValidationComponent createTableExistenceComponent (
- final String tableName)
- {
+ protected ValidationComponent createTableExistenceComponent(final String tableName) {
return createTableExistenceComponent(tableName, null);
}
@@ -1855,33 +1585,25 @@ protected ValidationComponent createTableExistenceComponent (
* checking overall
* @return the validation component
*/
- protected ValidationComponent createTableExistenceComponent (
- final String tableName, final PersistenceFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (tableName != null)
- {
+ protected ValidationComponent createTableExistenceComponent(final String tableName,
+ final PersistenceFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (tableName != null) {
String className = getClassName();
boolean noRelated = (relatedField == null);
TableElement table = getTable(tableName,
- getSchemaForClass((noRelated ? className :
- getRelatedClass(relatedField))));
+ getSchemaForClass((noRelated ? className : getRelatedClass(relatedField))));
- if (table == null)
- {
- Object[] args = noRelated ?
- new Object[]{tableName, className} :
- new Object[]{tableName, relatedField};
-
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- getOffendingObject(relatedField),
- I18NHelper.getMessage(getMessages(), getKey(
- "util.validation.table_not_found", //NOI18N
- relatedField), args));
+ if (table == null) {
+ Object[] args = noRelated ? new Object[] {tableName, className}
+ : new Object[] {tableName, relatedField};
+
+ throw new ModelValidationException(ModelValidationException.WARNING,
+ getOffendingObject(relatedField), I18NHelper.getMessage(getMessages(),
+ getKey("util.validation.table_not_found", relatedField), args));
}
}
}
@@ -1893,9 +1615,7 @@ public void validate () throws ModelValidationException
* @param columnName the column whose existence is being checked
* @return the validation component
*/
- protected ValidationComponent createColumnExistenceComponent (
- final String columnName)
- {
+ protected ValidationComponent createColumnExistenceComponent(final String columnName) {
return createColumnExistenceComponent(columnName, null);
}
@@ -1907,66 +1627,48 @@ protected ValidationComponent createColumnExistenceComponent (
* same secondary table setup
* @return the validation component
*/
- protected ValidationComponent createColumnExistenceComponent (
- final String columnName, final MappingFieldElement relatedField)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
- if (columnName != null)
- {
+ protected ValidationComponent createColumnExistenceComponent(final String columnName,
+ final MappingFieldElement relatedField) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
+ if (columnName != null) {
String className = getClassName();
- String absoluteName = NameUtil.getAbsoluteMemberName(
- getSchemaForClass(className), columnName);
- TableElement table = TableElement.forName(
- NameUtil.getTableName(absoluteName));
+ String absoluteName = NameUtil.getAbsoluteMemberName(getSchemaForClass(className), columnName);
+ TableElement table = TableElement.forName(NameUtil.getTableName(absoluteName));
boolean foundTable = (table != null);
- DBMemberElement columnElement = ((foundTable) ?
- table.getMember(DBIdentifier.create(absoluteName)) :
- null);
+ DBMemberElement columnElement = foundTable
+ ? table.getMember(DBIdentifier.create(absoluteName))
+ : null;
boolean noRelated = (relatedField == null);
- if (foundTable)
- {
- boolean isRelationship =
- (!noRelated && isRelationship(relatedField));
+ if (foundTable) {
+ boolean isRelationship = (!noRelated && isRelationship(relatedField));
boolean noColumn = (columnElement == null);
- if (!isRelationship && noColumn)
- {
- Object[] args = (noRelated) ?
- new Object[]{columnName, className} :
- new Object[]{columnName, relatedField,
- className};
+ if (!isRelationship && noColumn) {
+ Object[] args = (noRelated) ? new Object[] {columnName, className}
+ : new Object[] {columnName, relatedField, className};
- throw new ModelValidationException(
- ModelValidationException.WARNING,
+ throw new ModelValidationException(ModelValidationException.WARNING,
+ getOffendingObject(relatedField), I18NHelper.getMessage(getMessages(),
+ getKey("util.validation.column_not_found", relatedField), args));
+ } else if (isRelationship && (noColumn || !isPairComplete(columnElement))) {
+ throw new ModelValidationException(ModelValidationException.WARNING,
getOffendingObject(relatedField),
- I18NHelper.getMessage(getMessages(), getKey(
- "util.validation.column_not_found", //NOI18N
- relatedField), args));
- }
- else if (isRelationship &&
- (noColumn || !isPairComplete(columnElement)))
- {
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- getOffendingObject(relatedField),
- I18NHelper.getMessage(getMessages(),
- "util.validation.column_invalid", //NOI18N
- new Object[]{columnName, relatedField,
- className}));
+ I18NHelper.getMessage(getMessages(), "util.validation.column_invalid",
+ new Object[] {columnName, relatedField, className}));
}
}
}
}
- private boolean isPairComplete (DBMemberElement member)
- {
- return ((member instanceof ColumnPairElement) &&
- (((ColumnPairElement)member).getLocalColumn() != null) &&
- (((ColumnPairElement)member).getReferencedColumn()
- != null));
+
+
+ private boolean isPairComplete(DBMemberElement member) {
+ return ((member instanceof ColumnPairElement)
+ && (((ColumnPairElement) member).getLocalColumn() != null)
+ && (((ColumnPairElement) member).getReferencedColumn() != null));
}
};
}
@@ -1976,46 +1678,35 @@ private boolean isPairComplete (DBMemberElement member)
* @param field the field whose column mapping is being checked
* @return the validation component
*/
- protected ValidationComponent createColumnOverlapComponent (
- final MappingFieldElement field)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createColumnOverlapComponent(final MappingFieldElement field) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
MappingClassElement mappingClass = field.getDeclaringClass();
- Iterator iterator = mappingClass.getFields().iterator();
- ArrayList myColumns = field.getColumns();
+ Iterator iterator = mappingClass.getFields().iterator();
+ List myColumns = field.getColumns();
- while (iterator.hasNext())
- {
- MappingFieldElement testField =
- (MappingFieldElement)iterator.next();
+ while (iterator.hasNext()) {
+ MappingFieldElement testField = iterator.next();
if (!testField.equals(field) && !isRelationship(testField)
- && isPartialMatch(myColumns, testField.getColumns()))
- {
+ && isPartialMatch(myColumns, testField.getColumns())) {
String fieldName = field.getName();
- throw new ModelValidationException(getModel().getField(
- getClassName(), fieldName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.field_mapping_invalid", //NOI18N
- new Object[]{fieldName, testField.getName()}));
+ throw new ModelValidationException(getModel().getField(getClassName(), fieldName),
+ I18NHelper.getMessage(getMessages(), "util.validation.field_mapping_invalid",
+ new Object[] {fieldName, testField.getName()}));
}
}
}
- private boolean isPartialMatch (ArrayList columns1,
- ArrayList columns2)
- {
- int count = columns1.size();
- if (count > 0)
- {
- ArrayList difference = getDifference(columns1, columns2);
- return (!difference.isEmpty() &&
- (columns2.size() != difference.size()));
+ private boolean isPartialMatch(List columns1, List columns2) {
+ int count = columns1.size();
+ if (count > 0) {
+ List difference = getDifference(columns1, columns2);
+ return !difference.isEmpty() && columns2.size() != difference.size();
}
return false;
@@ -2023,36 +1714,36 @@ private boolean isPartialMatch (ArrayList columns1,
};
}
- /** Create a validation component which can check whether the key class
+
+ /**
+ * Create a validation component which can check whether the key class
* of the persistence capable class is valid. This includes:
*
- * The key class must be public.
- * The key class must implement Serializable.
- * If the key class is an inner class, it must be static.
- * The key class must have a public constructor, which might be
+ * The key class must be public.
+ * The key class must implement Serializable.
+ * If the key class is an inner class, it must be static.
+ * The key class must have a public constructor, which might be
* the default constructor or a no-arg constructor.
- * The field types of all non-static fields in the key class must be
+ * The field types of all non-static fields in the key class must be
* of valid types.
- * All serializable non-static fields in the key class must be public.
- * The names of the non-static fields in the key class must include the
+ * All serializable non-static fields in the key class must be public.
+ * The names of the non-static fields in the key class must include the
* names of the primary key fields in the JDO class, and the types of the
* common fields must be identical
- * The key class must redefine equals and hashCode.
+ * The key class must redefine equals and hashCode.
*
*/
- protected ValidationComponent createKeyClassComponent (
- final String className)
- {
- return new ValidationComponent ()
- {
+ protected ValidationComponent createKeyClassComponent(final String className) {
+ return new ValidationComponent() {
+
/** The class element of the key class */
private Object keyClass;
/** The fully qualified name of the key class */
private String keyClassName;
- public void validate () throws ModelValidationException
- {
+ @Override
+ public void validate() throws ModelValidationException {
// checks the key class name
keyClassName = validateKeyClassName(className);
// initilialize keyClass field
@@ -2063,113 +1754,93 @@ public void validate () throws ModelValidationException
validateMethods();
}
- /** Helper method validating the key class itself:
+
+ /**
+ * Helper method validating the key class itself:
* public, serializable, static.
*/
- private void validateClass () throws ModelValidationException
- {
+ private void validateClass() throws ModelValidationException {
Model model = getModel();
int modifiers = model.getModifiersForClass(keyClassName);
boolean hasKeyClassName = !StringHelper.isEmpty(keyClassName);
- boolean isInnerClass =
- (hasKeyClassName && (keyClassName.indexOf('$') != -1));
+ boolean isInnerClass = (hasKeyClassName && (keyClassName.indexOf('$') != -1));
String pcClassName = getClassName();
// check for key class existence
- if (keyClass == null)
- {
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- model.getClass(pcClassName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_missing", //NOI18N
- keyClassName, pcClassName));
+ if (keyClass == null) {
+ throw new ModelValidationException(ModelValidationException.WARNING, model.getClass(pcClassName),
+ I18NHelper.getMessage(getMessages(), "util.validation.key_class_missing", keyClassName,
+ pcClassName));
}
// check for public class modifier
- if (!Modifier.isPublic(modifiers))
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_public", //NOI18N
- keyClassName, pcClassName));
+ if (!Modifier.isPublic(modifiers)) {
+ throw new ModelValidationException(keyClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_public", keyClassName, pcClassName));
}
// check for Serializable
- /* This check is disabled because of Boston backward
- compatibility. In Boston there was no requirement for a
- key class being serializable, thus key classes from pc
- classes mapped with boston are not serializable.
-
- if (!model.implementsInterface(keyClass,
- "java.io.Serializable")) //NOI18N
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_serializable", //NOI18N
- keyClassName, pcClassName));
- }
- */
+ /*
+ * This check is disabled because of Boston backward
+ * compatibility. In Boston there was no requirement for a
+ * key class being serializable, thus key classes from pc
+ * classes mapped with boston are not serializable.
+ * if (!model.implementsInterface(keyClass,
+ * "java.io.Serializable"))
+ * {
+ * throw new ModelValidationException(keyClass,
+ * I18NHelper.getMessage(getMessages(),
+ * "util.validation.key_class_serializable",
+ * keyClassName, pcClassName));
+ * }
+ */
// if inner class it must be static
- if (isInnerClass && !Modifier.isStatic(modifiers))
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_static", //NOI18N
- keyClassName, pcClassName));
+ if (isInnerClass && !Modifier.isStatic(modifiers)) {
+ throw new ModelValidationException(keyClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_static", keyClassName, pcClassName));
}
}
- /** Helper method validating the fields of the key class.
+
+ /**
+ * Helper method validating the fields of the key class.
*/
- private void validateFields () throws ModelValidationException
- {
+ private void validateFields() throws ModelValidationException {
String pcClassName = getClassName();
Model model = getModel();
// check for valid typed public non-static fields
- List keyClassFieldNames = model.getAllFields(keyClassName);
- Map keyFields = getKeyFields();
+ List keyClassFieldNames = model.getAllFields(keyClassName);
+ Map keyFields = getKeyFields();
- for (Iterator i = keyClassFieldNames.iterator(); i.hasNext();)
- {
- String keyClassFieldName = (String)i.next();
- Object keyClassField =
- getKeyClassField(keyClassName, keyClassFieldName);
- int keyClassFieldModifiers =
- model.getModifiers(keyClassField);
+ for (String keyClassFieldName : keyClassFieldNames) {
+ Object keyClassField = getKeyClassField(keyClassName, keyClassFieldName);
+ int keyClassFieldModifiers = model.getModifiers(keyClassField);
String keyClassFieldType = model.getType(keyClassField);
Object keyField = keyFields.get(keyClassFieldName);
- if (Modifier.isStatic(keyClassFieldModifiers))
+ if (Modifier.isStatic(keyClassFieldModifiers)) {
// we are not interested in static fields
continue;
+ }
- if (!model.isValidKeyType(keyClassName, keyClassFieldName))
- {
- throw new ModelValidationException(keyClassField,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_field_type_invalid", //NOI18N
- keyClassFieldName, keyClassName));
+ if (!model.isValidKeyType(keyClassName, keyClassFieldName)) {
+ throw new ModelValidationException(keyClassField, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_field_type_invalid", keyClassFieldName, keyClassName));
}
- if (!Modifier.isPublic(keyClassFieldModifiers))
- {
- throw new ModelValidationException(keyClassField,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_field_public", //NOI18N
- keyClassFieldName, keyClassName));
+ if (!Modifier.isPublic(keyClassFieldModifiers)) {
+ throw new ModelValidationException(keyClassField, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_field_public", keyClassFieldName, keyClassName));
}
- if (keyField == null)
+ if (keyField == null) {
continue;
+ }
- if (!keyClassFieldType.equals(model.getType(keyField)))
- {
- throw new ModelValidationException(keyClassField,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_field_type_mismatch", //NOI18N
- keyClassFieldName, keyClassName, pcClassName));
+ if (!keyClassFieldType.equals(model.getType(keyField))) {
+ throw new ModelValidationException(keyClassField, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_field_type_mismatch", keyClassFieldName, keyClassName, pcClassName));
}
// remove handled keyField from the list of keyFields
@@ -2177,75 +1848,58 @@ private void validateFields () throws ModelValidationException
}
// check whether there are any unhandled key fields
- if (!keyFields.isEmpty())
- {
+ if (!keyFields.isEmpty()) {
Object pcClass = model.getClass(pcClassName);
- String fieldNames = StringHelper.arrayToSeparatedList(
- new ArrayList(keyFields.keySet()));
+ String fieldNames = StringHelper.arrayToSeparatedList(new ArrayList<>(keyFields.keySet()));
- throw new ModelValidationException(pcClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_field_missing", //NOI18N
- pcClassName, keyClassName, fieldNames));
+ throw new ModelValidationException(pcClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_field_missing", pcClassName, keyClassName, fieldNames));
}
}
- /** Helper method validating the key class constructors.
+
+ /**
+ * Helper method validating the key class constructors.
*/
- private void validateConstructor () throws ModelValidationException
- {
+ private void validateConstructor() throws ModelValidationException {
// no constructor or no arg constructor
Model model = getModel();
boolean hasConstr = model.hasConstructor(keyClassName);
- Object noArgConstr =
- model.getConstructor(keyClassName, Model.NO_ARGS);
+ Object noArgConstr = model.getConstructor(keyClassName, Model.NO_ARGS);
int modifiers = model.getModifiers(noArgConstr);
- if (hasConstr &&
- ((noArgConstr == null) || !Modifier.isPublic(modifiers)))
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_constructor", //NOI18N
- keyClassName, getClassName()));
+ if (hasConstr && ((noArgConstr == null) || !Modifier.isPublic(modifiers))) {
+ throw new ModelValidationException(keyClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_constructor", keyClassName, getClassName()));
}
}
- /** Helper method validating the key class methods.
+
+ /**
+ * Helper method validating the key class methods.
*/
- private void validateMethods () throws ModelValidationException
- {
- Object equalsMethod = getNonObjectMethod(keyClassName,
- "equals", Model.getEqualsArgs()); //NOI18N
- Object hashCodeMethod = getNonObjectMethod(keyClassName,
- "hashCode", Model.NO_ARGS); //NOI18N
+ private void validateMethods() throws ModelValidationException {
+ Object equalsMethod = getNonObjectMethod(keyClassName, "equals", Model.getEqualsArgs());
+ Object hashCodeMethod = getNonObjectMethod(keyClassName, "hashCode", Model.NO_ARGS);
// check equals method
- if (!matchesMethod(equalsMethod, Modifier.PUBLIC,
- 0, "boolean")) //NOI18N
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_equals", //NOI18N
- keyClassName, getClassName()));
+ if (!matchesMethod(equalsMethod, Modifier.PUBLIC, 0, "boolean")) {
+ throw new ModelValidationException(keyClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_equals", keyClassName, getClassName()));
}
// check hashCode method
- if (!matchesMethod(hashCodeMethod, Modifier.PUBLIC,
- 0, "int")) //NOI18N
- {
- throw new ModelValidationException(keyClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_hashcode", //NOI18N
- keyClassName, getClassName()));
+ if (!matchesMethod(hashCodeMethod, Modifier.PUBLIC, 0, "int")) {
+ throw new ModelValidationException(keyClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_hashcode", keyClassName, getClassName()));
}
}
- /** Helper method validating the name of the key class.
+
+ /**
+ * Helper method validating the name of the key class.
*/
- private String validateKeyClassName (String keyClassName)
- throws ModelValidationException
- {
+ private String validateKeyClassName(String keyClassName) throws ModelValidationException {
String pcClassName = getClassName();
Model model = getModel();
boolean hasKeyClassName = !StringHelper.isEmpty(keyClassName);
@@ -2254,36 +1908,22 @@ private String validateKeyClassName (String keyClassName)
boolean isOIDNameSuffix;
// check for existence of key class name
- if (!hasKeyClassName)
- {
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- model.getClass(pcClassName),
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_unset", //NOI18N
- pcClassName));
+ if (!hasKeyClassName) {
+ throw new ModelValidationException(ModelValidationException.WARNING, model.getClass(pcClassName),
+ I18NHelper.getMessage(getMessages(), "util.validation.key_class_unset", pcClassName));
}
keyClassName = keyClassName.trim();
hasPrefix = keyClassName.startsWith(pcClassName);
- nameSuffix = (hasPrefix ?
- keyClassName.substring(pcClassName.length()) : keyClassName);
- isOIDNameSuffix =
- (nameSuffix.equalsIgnoreCase(".OID") || // NOI18N
- nameSuffix.equalsIgnoreCase("$OID")); // NOI18N
-
- if (!hasPrefix ||
- (!nameSuffix.equalsIgnoreCase("Key") && // NOI18N
- !isOIDNameSuffix))
- {
+ nameSuffix = (hasPrefix ? keyClassName.substring(pcClassName.length()) : keyClassName);
+ isOIDNameSuffix = (nameSuffix.equalsIgnoreCase(".OID") || nameSuffix.equalsIgnoreCase("$OID"));
+
+ if (!hasPrefix || (!nameSuffix.equalsIgnoreCase("Key") && !isOIDNameSuffix)) {
Object pcClass = getModel().getClass(pcClassName);
- throw new ModelValidationException(pcClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.key_class_invalid", //NOI18N
- keyClassName, pcClassName));
+ throw new ModelValidationException(pcClass, I18NHelper.getMessage(getMessages(),
+ "util.validation.key_class_invalid", keyClassName, pcClassName));
}
- if (isOIDNameSuffix)
- {
+ if (isOIDNameSuffix) {
StringBuffer buf = new StringBuffer(keyClassName);
buf.setCharAt(keyClassName.length() - 4, '$');
return buf.toString();
@@ -2291,69 +1931,58 @@ private String validateKeyClassName (String keyClassName)
return keyClassName;
}
+
// helper method which returns a field object from the
// given class or one of its superclasses
- private Object getKeyClassField (String keyClassName,
- String keyClassFieldName)
- {
+ private Object getKeyClassField(String keyClassName, String keyClassFieldName) {
Model model = getModel();
- Object keyClassField =
- model.getField(keyClassName, keyClassFieldName);
+ Object keyClassField = model.getField(keyClassName, keyClassFieldName);
- if (keyClassField == null) // this is an inherited field
- {
- keyClassField = model.getInheritedField(
- keyClassName, keyClassFieldName);
+ if (keyClassField == null) {
+ // this is an inherited field
+ keyClassField = model.getInheritedField(keyClassName, keyClassFieldName);
}
return keyClassField;
}
- /** Helper method returning the key fields of the pc class as a map.
+
+ /**
+ * Helper method returning the key fields of the pc class as a map.
*/
- private Map getKeyFields ()
- {
+ private Map getKeyFields() {
Model model = getModel();
String pcClassName = getClassName();
- PersistenceClassElement pce =
- model.getPersistenceClass(pcClassName);
+ PersistenceClassElement pce = model.getPersistenceClass(pcClassName);
PersistenceFieldElement[] fields = pce.getFields();
- Map keyFields = new HashMap();
+ Map keyFields = new HashMap<>();
- if (fields != null)
- {
- for (int i = 0; i < fields.length; i++)
- {
+ if (fields != null) {
+ for (int i = 0; i < fields.length; i++) {
PersistenceFieldElement pfe = fields[i];
- if (pfe.isKey())
- {
+ if (pfe.isKey()) {
String name = pfe.getName();
- keyFields.put(name,
- model.getField(pcClassName, name));
+ keyFields.put(name, model.getField(pcClassName, name));
}
}
}
return keyFields;
}
+
+
// helper method which returns a method object from the
// given class or one of its superclasses provided it
// is not java.lang.Object
- private Object getNonObjectMethod (String className,
- String methodName, String[] argTypeNames)
- {
+ private Object getNonObjectMethod(String className, String methodName, String[] argTypeNames) {
Model model = getModel();
- Object method =
- model.getMethod(className, methodName, argTypeNames);
+ Object method = model.getMethod(className, methodName, argTypeNames);
- if (method == null) // look for an inherited method
+ if (method == null) // look for an inherited method
{
- method = model.getInheritedMethod(
- className, methodName, argTypeNames);
+ method = model.getInheritedMethod(className, methodName, argTypeNames);
- if ((method != null) && model.getDeclaringClass(method).
- equals("java.lang.Object")) // NOI18N
- {
+ if ((method != null) && model.getDeclaringClass(method).equals("java.lang.Object")) {
method = null;
}
}
@@ -2363,188 +1992,162 @@ private Object getNonObjectMethod (String className,
};
}
- /** Create a validation component which can check that the persistence
+
+ /**
+ * Create a validation component which can check that the persistence
* capable class implement methods readObject and writeObject, if the class
* implements the intreface java.io.Serializable
+ *
* @param className the class whose methods are checked
* @return the validation component
*/
- protected ValidationComponent createSerializableClassComponent (
- final String className)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createSerializableClassComponent(final String className) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
Model model = getModel();
Object pcClass = null;
- if (className == null)
+ if (className == null) {
return;
+ }
pcClass = model.getClass(className);
- if (pcClass == null)
+ if (pcClass == null) {
return;
+ }
- if (model.implementsInterface(pcClass, "java.io.Serializable")) //NOI18N
- {
+ if (model.implementsInterface(pcClass, "java.io.Serializable")) {
// check readObject method
- Object readMethod = model.getMethod(className,
- "readObject", Model.getReadObjectArgs()); //NOI18N
+ Object readMethod = model.getMethod(className, "readObject", Model.getReadObjectArgs());
- if (!matchesMethod(readMethod, Modifier.PRIVATE,
- Modifier.SYNCHRONIZED, "void")) // NOI18N
- {
+ if (!matchesMethod(readMethod, Modifier.PRIVATE, Modifier.SYNCHRONIZED, "void")) {
throw new ModelValidationException(pcClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.class_readobject", //NOI18N
- className));
+ I18NHelper.getMessage(getMessages(), "util.validation.class_readobject", className));
}
// check writeObject method
- Object writeMethod = model.getMethod(className,
- "writeObject", Model.getWriteObjectArgs()); //NOI18N
+ Object writeMethod = model.getMethod(className, "writeObject", Model.getWriteObjectArgs());
- if (!matchesMethod(writeMethod, Modifier.PRIVATE,
- Modifier.SYNCHRONIZED, "void")) // NOI18N
- {
+ if (!matchesMethod(writeMethod, Modifier.PRIVATE, Modifier.SYNCHRONIZED, "void")) {
throw new ModelValidationException(pcClass,
- I18NHelper.getMessage(getMessages(),
- "util.validation.class_writeobject", //NOI18N
- className));
+ I18NHelper.getMessage(getMessages(), "util.validation.class_writeobject", className));
}
}
}
};
}
- /** Create a validation component which can check whether the class is
+
+ /**
+ * Create a validation component which can check whether the class is
* unmapped.
+ *
* @param persistenceClass the class whose mapping is being checked
* @return the validation component
*/
- protected ValidationComponent createClassMappingComponent (
- final PersistenceClassElement persistenceClass)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createClassMappingComponent(final PersistenceClassElement persistenceClass) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
PersistenceFieldElement[] fields = persistenceClass.getFields();
String className = getClassName();
- if ((fields == null) || fields.length == 0)
- {
- throw constructClassException(
- ModelValidationException.WARNING, className, null,
- "util.validation.class_no_fields"); //NOI18N
+ if (fields == null || fields.length == 0) {
+ throw constructClassException(ModelValidationException.WARNING, className, null,
+ "util.validation.class_no_fields");
}
- else // has fields, check for primary table
- {
- MappingClassElement mappingClass =
- getMappingClass(className);
+ // has fields, check for primary table
+ MappingClassElement mappingClass = getMappingClass(className);
- if ((mappingClass == null) ||
- (mappingClass.getTables().size() == 0))
- {
- throw constructClassException(
- ModelValidationException.WARNING, className, null,
- "util.validation.class_not_mapped"); //NOI18N
- }
+ if ((mappingClass == null) || (mappingClass.getTables().size() == 0)) {
+ throw constructClassException(ModelValidationException.WARNING, className, null,
+ "util.validation.class_not_mapped");
}
}
};
}
- /** Create a validation component which can check whether the class
+
+ /**
+ * Create a validation component which can check whether the class
* contains field mappings for all primary key columns.
+ *
* @param persistenceClass the class whose mapping is being checked
* @return the validation component
*/
- protected ValidationComponent createKeyColumnMappingComponent (
- final PersistenceClassElement persistenceClass)
- {
- return new ValidationComponent ()
- {
- public void validate () throws ModelValidationException
- {
+ protected ValidationComponent createKeyColumnMappingComponent(final PersistenceClassElement persistenceClass) {
+ return new ValidationComponent() {
+
+ @Override
+ public void validate() throws ModelValidationException {
String className = getClassName();
MappingClassElement mappingClass = getMappingClass(className);
- if (mappingClass != null)
- {
- List tables = mappingClass.getTables();
+ if (mappingClass == null) {
+ return;
+ }
+ List tables = mappingClass.getTables();
+ if (tables.isEmpty()) {
+ return;
+ }
+ String tableName = tables.get(0).getName();
+ TableElement table = getTable(tableName, getSchemaForClass(className));
+ List columns = getUnmappedColumnNames(table == null ? null : table.getPrimaryKey(),
+ mappingClass);
- if (tables.size() > 0)
- {
- String tableName =
- ((MappingTableElement)tables.get(0)).getName();
- TableElement table = getTable(tableName,
- getSchemaForClass(className));
- List columns = getUnmappedColumnNames(
- ((table != null) ? table.getPrimaryKey() : null),
- mappingClass);
-
- if ((columns != null) && (columns.size() > 0))
- {
- throw new ModelValidationException(
- ModelValidationException.WARNING,
- getOffendingObject(null),
- I18NHelper.getMessage(getMessages(),
- "util.validation.class_key_column_missing", //NOI18N
- className, tableName,
- StringHelper.arrayToSeparatedList(columns)));
- }
- }
+ if (columns != null && !columns.isEmpty()) {
+ throw new ModelValidationException(ModelValidationException.WARNING, getOffendingObject(null),
+ I18NHelper.getMessage(getMessages(), "util.validation.class_key_column_missing", className,
+ tableName, StringHelper.arrayToSeparatedList(columns)));
}
}
- private List getUnmappedColumnNames (KeyElement primaryKey,
- MappingClassElement mappingClass)
- {
- List unmappedColumns = null;
- if (primaryKey != null) // check if primary table has a pk
- {
- ColumnElement[] columns = primaryKey.getColumns();
- int count = ((columns != null) ? columns.length : 0);
- // all columns in the pk should be mapped to key fields
- if (count > 0)
- {
- List mappingFields = mappingClass.getFields();
- Iterator iterator = mappingFields.iterator();
+ private List getUnmappedColumnNames(KeyElement primaryKey, MappingClassElement mappingClass) {
+ if (primaryKey == null) {
+ return null;
+ }
+ // check if primary table has a pk
+ ColumnElement[] columns = primaryKey.getColumns();
+ int count = columns == null ? 0 : columns.length;
+
+ // all columns in the pk should be mapped to key fields
+ if (count <= 0) {
+ return null;
+ }
+ List mappingFields = mappingClass.getFields();
+ Iterator iterator = mappingFields.iterator();
- unmappedColumns = getRelativeColumnNames(columns);
+ List unmappedColumns = getRelativeColumnNames(columns);
- while (iterator.hasNext())
- {
- MappingFieldElement field =
- (MappingFieldElement)iterator.next();
+ while (iterator.hasNext()) {
+ MappingFieldElement field = iterator.next();
- if (isKeyField(field))
- unmappedColumns.removeAll(field.getColumns());
- }
+ if (isKeyField(field)) {
+ unmappedColumns.removeAll(field.getColumns());
}
}
return unmappedColumns;
}
- private List getRelativeColumnNames (ColumnElement[] columns)
- {
+
+
+ private List getRelativeColumnNames(ColumnElement[] columns) {
int i, count = ((columns != null) ? columns.length : 0);
- List columnNames = new ArrayList(count);
+ List columnNames = new ArrayList<>(count);
- for (i = 0; i < count; i++)
- {
- columnNames.add(NameUtil.getRelativeMemberName(
- columns[i].getName().getFullName()));
+ for (i = 0; i < count; i++) {
+ columnNames.add(NameUtil.getRelativeMemberName(columns[i].getName().getFullName()));
}
return columnNames;
}
- private boolean isKeyField (MappingFieldElement field)
- {
- PersistenceFieldElement persistenceField =
- persistenceClass.getField(field.getName());
+
+
+ private boolean isKeyField(MappingFieldElement field) {
+ PersistenceFieldElement persistenceField = persistenceClass.getField(field.getName());
return ((persistenceField != null) && persistenceField.isKey());
}
@@ -2577,9 +2180,8 @@ private Object getOffendingObject (Object field)
* null
* @return the key
*/
- private String getKey (String keyBase, Object field)
- {
- return ((field == null) ? keyBase : (keyBase + "_related")); //NOI18N
+ private String getKey(String keyBase, Object field) {
+ return field == null ? keyBase : keyBase + "_related";
}
/** Computes the arguments for the i18n string to be used in the
@@ -2592,17 +2194,18 @@ private String getKey (String keyBase, Object field)
* null
* @return the argument array
*/
- private Object[] getArguments (String className, Object field)
- {
- return ((field == null) ? new Object[]{className} :
- new Object[]{className, field});
+ private Object[] getArguments(String className, Object field) {
+ return field == null ? new Object[] {className} : new Object[] {className, field};
}
- /** Constructs a ModelValidationException for class validation tests
+
+ /**
+ * Constructs a ModelValidationException for class validation tests
* using the supplied class name, related field, and key base.
+ *
* @param className the name of the class which caused the problem
* @param field the field object which caused the problem - may be
- * null
+ * null
* @param keyBase the base key to be used for the i18n string
* @return the ModelValidationException
* @see #getOffendingObject
@@ -2610,11 +2213,8 @@ private Object[] getArguments (String className, Object field)
* @see #getArguments
* @see #constructFieldException
*/
- private ModelValidationException constructClassException (String className,
- Object relatedField, String keyBase)
- {
- return constructClassException(ModelValidationException.ERROR,
- className, relatedField, keyBase);
+ private ModelValidationException constructClassException(String className, Object relatedField, String keyBase) {
+ return constructClassException(ModelValidationException.ERROR, className, relatedField, keyBase);
}
/** Constructs a ModelValidationException for class validation tests
@@ -2632,9 +2232,8 @@ private ModelValidationException constructClassException (String className,
* @see #getArguments
* @see #constructFieldException
*/
- private ModelValidationException constructClassException (int errorType,
- String className, Object relatedField, String keyBase)
- {
+ private ModelValidationException constructClassException(int errorType, String className, Object relatedField,
+ String keyBase) {
return new ModelValidationException(errorType,
getOffendingObject(relatedField), I18NHelper.getMessage(
getMessages(), getKey(keyBase, relatedField),
@@ -2648,13 +2247,11 @@ private ModelValidationException constructClassException (int errorType,
* @return the ModelValidationException
* @see #constructClassException
*/
- private ModelValidationException constructFieldException (String fieldName,
- String key)
- {
- return constructFieldException(ModelValidationException.ERROR,
- fieldName, key);
+ private ModelValidationException constructFieldException(String fieldName, String key) {
+ return constructFieldException(ModelValidationException.ERROR, fieldName, key);
}
+
/** Constructs a ModelValidationException for field validation tests
* using the supplied field name and key.
* @param errorType the type of error -- one of
@@ -2665,11 +2262,8 @@ private ModelValidationException constructFieldException (String fieldName,
* @return the ModelValidationException
* @see #constructClassException
*/
- private ModelValidationException constructFieldException (int errorType,
- String fieldName, String key)
- {
- return new ModelValidationException(errorType,
- getModel().getField(getClassName(), fieldName),
+ private ModelValidationException constructFieldException(int errorType, String fieldName, String key) {
+ return new ModelValidationException(errorType, getModel().getField(getClassName(), fieldName),
I18NHelper.getMessage(getMessages(), key, fieldName));
}
@@ -2684,20 +2278,16 @@ private ModelValidationException constructFieldException (int errorType,
* @return true if the method matches,
* false otherwise.
*/
- private boolean matchesMethod (final Object method,
- final int expectedModifiers, final int optionalModifiers,
- final String expectedReturnType)
- {
+ private boolean matchesMethod(final Object method, final int expectedModifiers, final int optionalModifiers,
+ final String expectedReturnType) {
boolean matches = false;
- if (method != null)
- {
+ if (method != null) {
Model model = getModel();
int modifiers = model.getModifiers(method);
- matches = (((modifiers == expectedModifiers) ||
- (modifiers == (expectedModifiers | optionalModifiers))) &&
- expectedReturnType.equals(model.getType(method)));
+ matches = (((modifiers == expectedModifiers) || (modifiers == (expectedModifiers | optionalModifiers)))
+ && expectedReturnType.equals(model.getType(method)));
}
return matches;
@@ -2709,185 +2299,161 @@ private boolean matchesMethod (final Object method,
* @return true if the column belongs to a table found
* in the supplied list of table names, false otherwise
*/
- private boolean matchesTable (List tableNames, ColumnElement column)
- {
- return ((column == null) ? true : tableNames.contains(
- column.getDeclaringTable().getName().getName()));
+ private boolean matchesTable(List tableNames, ColumnElement column) {
+ return column == null ? true : tableNames.contains(column.getDeclaringTable().getName().getName());
}
- private boolean isRelationship (Object field)
- {
- return ((field instanceof RelationshipElement) ||
- (field instanceof MappingRelationshipElement));
+
+ private boolean isRelationship(Object field) {
+ return field instanceof RelationshipElement || field instanceof MappingRelationshipElement;
}
- private boolean shouldBeRelationship (PersistenceFieldElement field)
- {
+
+ private boolean shouldBeRelationship(PersistenceFieldElement field) {
Model model = getModel();
String fieldType = model.getFieldType(getClassName(), field.getName());
- return (isPersistent(fieldType) || model.isCollection(fieldType));
+ return isPersistent(fieldType) || model.isCollection(fieldType);
}
- private boolean isLegalRelationship (PersistenceFieldElement field)
- {
- return (isRelationship(field) ? shouldBeRelationship(field) : false);
+
+ private boolean isLegalRelationship(PersistenceFieldElement field) {
+ return isRelationship(field) ? shouldBeRelationship(field) : false;
}
- private boolean isCollection (String className, String fieldName)
- {
+
+ private boolean isCollection(String className, String fieldName) {
Model model = getModel();
return model.isCollection(model.getFieldType(className, fieldName));
}
- private String getRelatedClass (PersistenceFieldElement field)
- {
- if (isLegalRelationship(field))
- return getModel().getRelatedClass((RelationshipElement)field);
+
+ private String getRelatedClass(PersistenceFieldElement field) {
+ if (isLegalRelationship(field)) {
+ return getModel().getRelatedClass((RelationshipElement) field);
+ }
return null;
}
- private String getSchemaForClass (String className)
- {
+
+ private String getSchemaForClass(String className) {
MappingClassElement mappingClass = getMappingClass(className);
- String schema = ((mappingClass != null) ?
- mappingClass.getDatabaseRoot() : null);
+ String schema = ((mappingClass != null) ? mappingClass.getDatabaseRoot() : null);
return (StringHelper.isEmpty(schema) ? null : schema.trim());
}
- private MappingRelationshipElement getMappingRelationship (
- RelationshipElement jdoElement)
- {
+
+ private MappingRelationshipElement getMappingRelationship(RelationshipElement jdoElement) {
MappingRelationshipElement mappingElement = null;
- if (jdoElement != null)
- {
- MappingClassElement mappingClass = getMappingClass(
- jdoElement.getDeclaringClass().getName());
+ if (jdoElement != null) {
+ MappingClassElement mappingClass = getMappingClass(jdoElement.getDeclaringClass().getName());
- if (mappingClass != null)
- {
- MappingFieldElement fieldElement =
- mappingClass.getField(jdoElement.getName());
+ if (mappingClass != null) {
+ MappingFieldElement fieldElement = mappingClass.getField(jdoElement.getName());
- if (isRelationship(fieldElement))
- mappingElement = (MappingRelationshipElement)fieldElement;
+ if (isRelationship(fieldElement)) {
+ mappingElement = (MappingRelationshipElement) fieldElement;
+ }
}
}
return mappingElement;
}
- private boolean isJoin (MappingRelationshipElement field)
- {
- if (field != null)
- {
- ArrayList columns = field.getAssociatedColumns();
+ private boolean isJoin(MappingRelationshipElement field) {
+ if (field != null) {
+ List columns = field.getAssociatedColumns();
return ((columns != null) && !columns.isEmpty());
}
-
return false;
}
- private MappingReferenceKeyElement findReferenceKey (
- MappingTableElement primaryTable, MappingTableElement secondaryTable)
- {
- if ((primaryTable != null) && (secondaryTable != null))
- {
- Iterator iterator = primaryTable.getReferencingKeys().iterator();
- while (iterator.hasNext())
- {
- MappingReferenceKeyElement testKey =
- (MappingReferenceKeyElement)iterator.next();
+ private MappingReferenceKeyElement findReferenceKey(MappingTableElement primaryTable,
+ MappingTableElement secondaryTable) {
+ if ((primaryTable != null) && (secondaryTable != null)) {
+ Iterator iterator = primaryTable.getReferencingKeys().iterator();
+
+ while (iterator.hasNext()) {
+ MappingReferenceKeyElement testKey = iterator.next();
- if (testKey.getTable().equals(secondaryTable))
+ if (testKey.getTable().equals(secondaryTable)) {
return testKey;
+ }
}
}
return null;
}
- private TableElement getTable (String tableName, String databaseRoot)
- {
- String absoluteName = NameUtil.getAbsoluteTableName(databaseRoot,
- tableName);
+ private TableElement getTable(String tableName, String databaseRoot) {
+ String absoluteName = NameUtil.getAbsoluteTableName(databaseRoot, tableName);
return TableElement.forName(absoluteName);
}
- private ColumnPairElement getPair (String pairName, String databaseRoot)
- {
- String absoluteName = NameUtil.getAbsoluteMemberName(
- databaseRoot, pairName);
- TableElement tableElement = TableElement.forName(
- NameUtil.getTableName(absoluteName));
- DBMemberElement pair = ((tableElement == null) ? null :
- tableElement.getMember(DBIdentifier.create(absoluteName)));
+ private ColumnPairElement getPair(String pairName, String databaseRoot) {
+ String absoluteName = NameUtil.getAbsoluteMemberName(databaseRoot, pairName);
+ TableElement tableElement = TableElement.forName(NameUtil.getTableName(absoluteName));
+ DBMemberElement pair = tableElement == null ? null : tableElement.getMember(DBIdentifier.create(absoluteName));
- return ((pair instanceof ColumnPairElement) ?
- ((ColumnPairElement)pair) : null);
+ return pair instanceof ColumnPairElement ? (ColumnPairElement) pair : null;
}
- private ArrayList getDifference (ArrayList columns1, ArrayList columns2)
- {
- ArrayList differenceColumns = new ArrayList(columns2);
-
- differenceColumns.removeAll(columns1);
-
+ private List getDifference(List list, List list2) {
+ List differenceColumns = new ArrayList<>(list2);
+ differenceColumns.removeAll(list);
return differenceColumns;
}
/**
* Convenience method to call Model.getMappingClass.
*/
- private MappingClassElement getMappingClass (String className)
- {
+ private MappingClassElement getMappingClass(String className) {
return getModel().getMappingClass(className, getClassLoader());
}
/**
* Convenience method to call Model.getPersistenceClass.
*/
- private PersistenceClassElement getPersistenceClass (String className)
- {
+ private PersistenceClassElement getPersistenceClass(String className) {
return getModel().getPersistenceClass(className, getClassLoader());
}
/**
* Convenience method to call Model.isPersistent
*/
- private boolean isPersistent (String className)
- {
+ private boolean isPersistent(String className) {
return getModel().isPersistent(className, getClassLoader());
}
/**
* Convenience method to call Model.isPersistentAllowed
*/
- private boolean isPersistentAllowed (String className, String fieldName)
- {
- return getModel().isPersistentAllowed(className, getClassLoader(),
- fieldName);
+ private boolean isPersistentAllowed(String className, String fieldName) {
+ return getModel().isPersistentAllowed(className, getClassLoader(), fieldName);
}
- // ================== Validation component support =================
- /** Abstraction of component tests for validation.
+ /**
+ * Abstraction of component tests for validation.
*/
- static abstract class ValidationComponent
- {
- /** Constructs a new ValidationComponent
+ static abstract class ValidationComponent {
+
+ /**
+ * Constructs a new ValidationComponent
*/
- public ValidationComponent ()
- {
+ public ValidationComponent() {
}
- /** Method which validates this component
+
+ /**
+ * Method which validates this component
+ *
* @exception ModelValidationException when the validation fails.
*/
- public abstract void validate () throws ModelValidationException;
+ public abstract void validate() throws ModelValidationException;
}
}
diff --git a/appserver/persistence/cmp/support-ejb/pom.xml b/appserver/persistence/cmp/support-ejb/pom.xml
index be88c9b1430..d926db7f782 100644
--- a/appserver/persistence/cmp/support-ejb/pom.xml
+++ b/appserver/persistence/cmp/support-ejb/pom.xml
@@ -97,7 +97,7 @@
org.glassfish.external
- schema2beans
+ schema2beans-osgi
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/CMPBeanHelper.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/CMPBeanHelper.java
index 21c1e1093d4..9646dc3f44a 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/CMPBeanHelper.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/CMPBeanHelper.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,11 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * CMPBeanHelper.java
- *
- * Created on May 28, 2003
- */
package com.sun.jdo.spi.persistence.support.ejb.cmp;
import com.sun.jdo.api.persistence.support.JDOException;
@@ -26,17 +22,22 @@
import com.sun.jdo.api.persistence.support.PersistenceCapable;
import com.sun.jdo.api.persistence.support.PersistenceManager;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.EJBHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import jakarta.ejb.DuplicateKeyException;
import jakarta.ejb.EJBException;
import jakarta.ejb.ObjectNotFoundException;
+import java.lang.System.Logger;
+import java.lang.System.Logger.Level;
import java.util.Collection;
import java.util.ResourceBundle;
import org.glassfish.persistence.common.I18NHelper;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.ERROR;
+import static java.lang.System.Logger.Level.WARNING;
+
/** Provides static helper methods for CMP bean implementation to simplify
* the generated code.
*/
@@ -44,26 +45,10 @@ public class CMPBeanHelper {
/** I18N message handlers */
private final static ResourceBundle cmpMessages = I18NHelper.loadBundle(
- "com.sun.jdo.spi.persistence.support.ejb.ejbc.Bundle", // NOI18N
+ "com.sun.jdo.spi.persistence.support.ejb.ejbc.Bundle",
CMPBeanHelper.class.getClassLoader());
- /**
- * The lifecycle logger used to log messages from ejbCreate(), ejbRemove()
- * and other lifecycle methods.
- */
- private static Logger cmpLifecycleLogger = LogHelperEntityLifecycle.getLogger();
-
- /**
- * The finder logger used to log messages from ejbFindXXX and/or ejbSelectXXX
- * methods.
- */
- private static Logger cmpFinderLogger = LogHelperEntityFinder.getLogger();
-
- /**
- * The internal logger used to log messages from setters and getter and other
- * generated methods.
- */
- private static Logger cmpInternalLogger = LogHelperEntityInternal.getLogger();
+ private static final Logger LOG = System.getLogger(CMPBeanHelper.class.getName());
/**
* Called from a CMP bean to log JDOException message
@@ -73,12 +58,8 @@ public class CMPBeanHelper {
* @param beanName the name of the calling bean.
* @param ex the JDOException.
*/
- public static void logJDOExceptionWithLifecycleLogger(
- String key, String beanName, JDOException ex) {
-
- cmpLifecycleLogger.log(Logger.WARNING,
- I18NHelper.getMessage(cmpMessages, key,
- beanName, findCallingMethodName()), ex);
+ public static void logJDOExceptionWithLifecycleLogger(String key, String beanName, JDOException ex) {
+ LOG.log(WARNING, () -> I18NHelper.getMessage(cmpMessages, key, beanName, findCallingMethodName()), ex);
}
/**
@@ -90,16 +71,13 @@ public static void logJDOExceptionWithLifecycleLogger(
* @param paramList the list of the concatenated parameters.
* @param ex the JDOException.
*/
- public static void logJDOExceptionWithLifecycleLogger(
- String key, String beanName, String paramList,
- JDOException ex) {
-
- cmpLifecycleLogger.log(Logger.WARNING,
- I18NHelper.getMessage(cmpMessages, key,
- beanName, findCallingMethodName(), paramList),
- ex);
+ public static void logJDOExceptionWithLifecycleLogger(String key, String beanName, String paramList,
+ JDOException ex) {
+ LOG.log(WARNING, () -> I18NHelper.getMessage(cmpMessages, key, beanName, findCallingMethodName(), paramList),
+ ex);
}
+
/**
* Called from a CMP bean to log JDOException message thrown
* from a any getter or setter method, with the InternalLogger.
@@ -107,15 +85,13 @@ beanName, findCallingMethodName(), paramList),
* @param beanName the name of the calling bean.
* @param ex the JDOException.
*/
- public static void logJDOExceptionWithInternalLogger(
- String beanName, JDOException ex) {
-
- cmpInternalLogger.log(Logger.WARNING,
- I18NHelper.getMessage(cmpMessages,
- "GEN.generic_method_exception", // NOI18N
- beanName, findCallingMethodName()), ex);
+ public static void logJDOExceptionWithInternalLogger(String beanName, JDOException ex) {
+ LOG.log(WARNING,
+ () -> I18NHelper.getMessage(cmpMessages, "GEN.generic_method_exception", beanName, findCallingMethodName()),
+ ex);
}
+
/**
* Called from a CMP bean to log JDOException message thrown
* from a any finder or selector method, with the FinderLogger.
@@ -128,18 +104,15 @@ public static void logJDOExceptionWithInternalLogger(
public static void logJDOExceptionWithFinderLogger(
String beanName, Object[] params, JDOException ex) {
- String msg = null;
+ String msg;
if (params != null) {
- msg = I18NHelper.getMessage(cmpMessages,
- "GEN.ejbSSReturnBody_exception", beanName, // NOI18N
- findCallingMethodName(),
- java.util.Arrays.asList(params).toString());
+ msg = I18NHelper.getMessage(cmpMessages, "GEN.ejbSSReturnBody_exception", beanName, findCallingMethodName(),
+ java.util.Arrays.asList(params).toString());
} else {
- msg = I18NHelper.getMessage(cmpMessages,
- "GEN.ejbSSReturnBody_exception_woparams", beanName, // NOI18N
- findCallingMethodName());
+ msg = I18NHelper.getMessage(cmpMessages, "GEN.ejbSSReturnBody_exception_woparams", beanName,
+ findCallingMethodName());
}
- cmpFinderLogger.log(Logger.WARNING, msg, ex);
+ LOG.log(WARNING, msg, ex);
}
/**
@@ -150,17 +123,13 @@ public static void logJDOExceptionWithFinderLogger(
* @param beanName the name of the calling bean.
* @param ex the Exception.
*/
- public static void logFinderException(int level, String beanName,
- Exception ex) {
-
- if (cmpFinderLogger.isLoggable(level)) {
- cmpFinderLogger.log(level,
- I18NHelper.getMessage(cmpMessages,
- "GEN.generic_method_exception", // NOI18N
- beanName, findCallingMethodName()), ex);
- }
+ public static void logFinderException(Level level, String beanName, Exception ex) {
+ LOG.log(level,
+ () -> I18NHelper.getMessage(cmpMessages, "GEN.generic_method_exception", beanName, findCallingMethodName()),
+ ex);
}
+
/**
* Called from a CMP bean to log JDOException message thrown
* from a PK setter method, with the InternalLogger.
@@ -171,18 +140,13 @@ public static void logFinderException(int level, String beanName,
* @param ex the JDOException.
* @return logged message as String.
*/
- public static String logJDOExceptionFromPKSetter(
- String beanName, JDOException ex) {
-
- String msg = I18NHelper.getMessage(cmpMessages, "EXC_PKUpdate", // NOI18N
- beanName, findCallingMethodName());
- if (cmpInternalLogger.isLoggable(Logger.FINE)) {
- cmpInternalLogger.log(Logger.FINE, msg, ex);
- }
-
+ public static String logJDOExceptionFromPKSetter(String beanName, JDOException ex) {
+ String msg = I18NHelper.getMessage(cmpMessages, "EXC_PKUpdate", beanName, findCallingMethodName());
+ LOG.log(DEBUG, msg, ex);
return msg;
}
+
/**
* Called from a CMP bean to verify that the PersistenceCapable
* instance is already persistent. Throws IllegalStateException
@@ -194,14 +158,15 @@ public static String logJDOExceptionFromPKSetter(
*/
public static void assertPersistent(PersistenceCapable pc, String beanName) {
if (!JDOHelper.isPersistent(pc)) {
- String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.cmrgettersetter_exception", beanName, findCallingMethodName()); // NOI18N
+ String msg = I18NHelper.getMessage(cmpMessages, "GEN.cmrgettersetter_exception", beanName,
+ findCallingMethodName());
- cmpInternalLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw new IllegalStateException(msg);
}
}
+
/**
* Called from a CMP bean to verify that the argument for
* a Collection set method is not null. Throws IllegalArgumentException
@@ -211,12 +176,12 @@ public static void assertPersistent(PersistenceCapable pc, String beanName) {
* @param beanName the name of the caller bean.
* @throws IllegalArgumentException if the argument is null.
*/
- public static void assertCollectionNotNull(Collection c, String beanName) {
+ public static void assertCollectionNotNull(Collection> c, String beanName) {
if (c == null) {
- String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.cmrsettercol_nullexception", beanName, findCallingMethodName()); // NOI18N
+ String msg = I18NHelper.getMessage(cmpMessages, "GEN.cmrsettercol_nullexception", beanName,
+ findCallingMethodName());
- cmpInternalLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw new IllegalArgumentException(msg);
}
}
@@ -233,9 +198,9 @@ public static void assertPersistenceManagerNotNull(PersistenceManager pm,
Object bean) {
if (pm == null) {
String msg = I18NHelper.getMessage(cmpMessages,
- "JDO.beannotloaded_exception", bean); // NOI18N
+ "JDO.beannotloaded_exception", bean);
- cmpInternalLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw new IllegalStateException(msg);
}
}
@@ -252,16 +217,16 @@ public static void assertPersistenceManagerIsNull(PersistenceManager pm,
Object bean, StringBuffer buf) {
if (pm != null) {
String msg = I18NHelper.getMessage(cmpMessages,
- "JDO.beaninuse_exception", bean); // NOI18N
+ "JDO.beaninuse_exception", bean);
// Excption to use only short message
IllegalStateException e = new IllegalStateException(msg);
if (buf != null && buf.length() > 0) {
- msg = (new StringBuffer(msg)).append(" ...Last Instance Usage: "). // NOI18N
+ msg = (new StringBuffer(msg)).append(" ...Last Instance Usage: ").
append(buf).toString();
}
- cmpInternalLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw e;
}
}
@@ -276,9 +241,9 @@ public static void assertPersistenceManagerIsNull(PersistenceManager pm,
public static void assertNotContainerTransaction(Object bean) {
if (EJBHelper.getTransaction() != null) {
String msg = I18NHelper.getMessage(cmpMessages,
- "JDO.containertransaction_exception", bean); // NOI18N
+ "JDO.containertransaction_exception", bean);
- cmpInternalLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw new IllegalStateException(msg);
}
}
@@ -297,10 +262,10 @@ public static void handleJDODuplicateObjectIdAsDuplicateKeyException(
throws DuplicateKeyException {
String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.ejbcreate_exception_dup", beanName, // NOI18N
+ "GEN.ejbcreate_exception_dup", beanName,
findCallingMethodName(), paramList);
- cmpLifecycleLogger.log(Logger.FINER, msg, ex);
+ LOG.log(DEBUG, msg, ex);
throw new DuplicateKeyException(msg);
}
@@ -317,10 +282,10 @@ public static void handleJDODuplicateObjectIdAsEJBException(
String beanName, String paramList, JDOException ex) {
String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.ejbcreate_exception_dup", beanName, // NOI18N
+ "GEN.ejbcreate_exception_dup", beanName,
findCallingMethodName(), paramList);
- cmpLifecycleLogger.log(Logger.FINER, msg, ex);
+ LOG.log(DEBUG, msg, ex);
throw new EJBException(msg);
}
@@ -338,10 +303,10 @@ public static void handleJDOObjectNotFoundException(
throws ObjectNotFoundException {
String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.findbypk_exception_notfound", beanName, // NOI18N
+ "GEN.findbypk_exception_notfound", beanName,
primaryKey.toString());
- cmpLifecycleLogger.log(Logger.FINER, msg, ex);
+ LOG.log(DEBUG, msg, ex);
throw new ObjectNotFoundException(msg);
}
@@ -354,10 +319,10 @@ public static void handleJDOObjectNotFoundException(
public static void handleUpdateNotAllowedException(
String beanName) {
String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.update_not_allowed", beanName, // NOI18N
+ "GEN.update_not_allowed", beanName,
findCallingMethodName());
- cmpLifecycleLogger.log(Logger.SEVERE, msg);
+ LOG.log(ERROR, msg);
throw new EJBException(msg);
}
@@ -374,10 +339,10 @@ public static void handleCloneException(
Object primaryKey, String beanName, Exception ex) {
String msg = I18NHelper.getMessage(cmpMessages,
- "GEN.clone_exception", beanName, // NOI18N
+ "GEN.clone_exception", beanName,
primaryKey.toString());
- cmpLifecycleLogger.log(Logger.SEVERE, msg, ex);
+ LOG.log(ERROR, msg, ex);
throw new EJBException(msg);
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/EJBHashSet.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/EJBHashSet.java
index e4480bf5c03..8bbe52cfef1 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/EJBHashSet.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/EJBHashSet.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,40 +15,35 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * EJBHashSet.java
- *
- * Created on December 10, 2001
- */
-
package com.sun.jdo.spi.persistence.support.ejb.cmp;
import com.sun.jdo.api.persistence.support.PersistenceManager;
import com.sun.jdo.api.persistence.support.Transaction;
-import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.JDOEJB20Helper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import jakarta.ejb.EJBLocalObject;
+import java.lang.System.Logger;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
+
+import static java.lang.System.Logger.Level.TRACE;
/*
* This is the implementation of the java.util.Set interface for the CMP
* fields of the Collection type. Represents many side of the relationships.
*
- * @author Marina Vatkina
+ * @author Marina Vatkina 2001
*/
-public class EJBHashSet extends HashSet {
+public class EJBHashSet extends HashSet {
// Reference to the PersistenceManager and Transaction that were active
// at the time of this Set creation.
private PersistenceManager pm = null;
private Transaction tx = null;
// HashSet of the persistence-capable instances associated with this Set.
- private HashSet pcSet = null;
+ private HashSet pcSet = null;
// Helper instance for conversion of the persistence-capable instances
// to the EJBLocalObject type and back.
@@ -56,8 +52,7 @@ public class EJBHashSet extends HashSet {
// Flag that indicates invalid state of this Set.
private boolean valid = false;
- //The logger
- private static Logger logger = LogHelperSQLStore.getLogger();
+ private static final Logger LOG = System.getLogger(EJBHashSet.class.getName());
/**
* Creates new instance of EJBHashSet for this parameters.
@@ -65,7 +60,7 @@ public class EJBHashSet extends HashSet {
* @param helper the JDOEJB20Helper instance.
* @param pcs a Collection of persistence-capable instances.
*/
- public EJBHashSet(PersistenceManager pm, JDOEJB20Helper helper, Collection pcs) {
+ public EJBHashSet(PersistenceManager pm, JDOEJB20Helper helper, Collection> pcs) {
this.pm = pm;
tx = pm.currentTransaction();
this.helper = helper;
@@ -87,8 +82,9 @@ public EJBHashSet(PersistenceManager pm, JDOEJB20Helper helper, Collection pcs)
* element.
* @see java.util.HashSet
*/
+ @Override
public boolean add(Object o) {
- logger.finest("---EJBHashSet.add---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.add---"); // NOI18N
assertIsValid();
assertInTransaction();
helper.assertInstanceOfLocalInterfaceImpl(o);
@@ -109,8 +105,9 @@ public boolean add(Object o) {
* @see java.util.AbstractCollection
* @see java.util.HashSet
*/
- public boolean addAll(Collection c) {
- logger.finest("---EJBHashSet.addAll---"); // NOI18N
+ @Override
+ public boolean addAll(Collection> c) {
+ LOG.log(TRACE, "---EJBHashSet.addAll---"); // NOI18N
assertIsValid();
assertInTransaction();
assertInstancesOfLocalInterfaceImpl(c);
@@ -124,8 +121,9 @@ public boolean addAll(Collection c) {
* @return true if the set contained the specified element.
* @see java.util.HashSet
*/
+ @Override
public boolean remove(Object o) {
- logger.finest("---EJBHashSet.remove---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.remove---"); // NOI18N
assertIsValid();
assertInTransaction();
helper.assertInstanceOfLocalInterfaceImpl(o);
@@ -149,8 +147,9 @@ public boolean remove(Object o) {
* @see java.util.HashSet
* @see java.util.AbstractCollection
*/
- public boolean removeAll(Collection c) {
- logger.finest("---EJBHashSet.removeAll---"); // NOI18N
+ @Override
+ public boolean removeAll(Collection> c) {
+ LOG.log(TRACE, "---EJBHashSet.removeAll---"); // NOI18N
assertIsValid();
assertInTransaction();
assertInstancesOfLocalInterfaceImpl(c);
@@ -170,8 +169,9 @@ public boolean removeAll(Collection c) {
* @see java.util.HashSet
* @see java.util.AbstractCollection
*/
- public boolean retainAll(Collection c) {
- logger.finest("---EJBHashSet.retainAll---"); // NOI18N
+ @Override
+ public boolean retainAll(Collection> c) {
+ LOG.log(TRACE, "---EJBHashSet.retainAll---"); // NOI18N
assertIsValid();
assertInTransaction();
assertInstancesOfLocalInterfaceImpl(c);
@@ -183,8 +183,9 @@ public boolean retainAll(Collection c) {
* Removes all of the elements from this set.
* @see java.util.HashSet
*/
+ @Override
public void clear() {
- logger.finest("---EJBHashSet.clear---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.clear---"); // NOI18N
assertIsValid();
assertInTransaction();
pcSet.clear();
@@ -195,8 +196,9 @@ public void clear() {
*
* @return the number of elements in this set (its cardinality).
*/
+ @Override
public int size() {
- logger.finest("---EJBHashSet.size---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.size---"); // NOI18N
assertIsValid();
assertInTransaction();
return pcSet.size();
@@ -207,8 +209,9 @@ public int size() {
*
* @return true if this set contains no elements.
*/
+ @Override
public boolean isEmpty() {
- logger.finest("---EJBHashSet.isEmpty---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.isEmpty---"); // NOI18N
assertIsValid();
assertInTransaction();
return pcSet.isEmpty();
@@ -220,8 +223,9 @@ public boolean isEmpty() {
* @param o element whose presence in this set is to be tested.
* @return true if this set contains the specified element.
*/
+ @Override
public boolean contains(Object o) {
- logger.finest("---EJBHashSet.contains---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.contains---"); // NOI18N
assertIsValid();
assertInTransaction();
helper.assertInstanceOfLocalInterfaceImpl(o);
@@ -244,8 +248,9 @@ public boolean contains(Object o) {
*
* @see #contains(Object)
*/
- public boolean containsAll(Collection c) {
- logger.finest("---EJBHashSet.containsAll---"); // NOI18N
+ @Override
+ public boolean containsAll(Collection> c) {
+ LOG.log(TRACE, "---EJBHashSet.containsAll---"); // NOI18N
assertIsValid();
assertInTransaction();
assertInstancesOfLocalInterfaceImpl(c);
@@ -258,10 +263,11 @@ public boolean containsAll(Collection c) {
*
* @return a shallow copy of this set.
*/
+ @Override
public Object clone() {
- logger.finest("---EJBHashSet.clone---"); // NOI18N
+ LOG.log(TRACE, "---EJBHashSet.clone---"); // NOI18N
EJBHashSet newSet = (EJBHashSet)super.clone();
- newSet.pcSet = (HashSet)pcSet.clone();
+ newSet.pcSet = (HashSet)pcSet.clone();
return newSet;
}
@@ -270,10 +276,10 @@ public Object clone() {
* with this Set.
* @return Set of the persistence-capable instances.
*/
- public HashSet getSCOHashSet() {
+ public HashSet> getSCOHashSet() {
assertIsValid();
assertInTransaction();
- return (pcSet != null) ? (HashSet)pcSet.clone() : null;
+ return (pcSet != null) ? (HashSet>)pcSet.clone() : null;
}
/**
@@ -282,11 +288,12 @@ public HashSet getSCOHashSet() {
* There is no need to check transaction as it has already been checked
* in this case.
*/
- public void setSCOHashSet(Collection coll) {
- if (coll instanceof java.util.HashSet)
+ public void setSCOHashSet(Collection> coll) {
+ if (coll instanceof java.util.HashSet) {
pcSet = (java.util.HashSet)coll;
- else
- pcSet = new java.util.HashSet(coll);
+ } else {
+ pcSet = new java.util.HashSet<>(coll);
+ }
}
/**
@@ -296,48 +303,54 @@ public void setSCOHashSet(Collection coll) {
* @return an Iterator over the elements in this set.
* @see ConcurrentModificationException
*/
- public Iterator iterator() {
+ @Override
+ public Iterator iterator() {
assertIsValid();
assertInTransaction();
return new EJBHashIterator();
}
- private class EJBHashIterator implements Iterator {
- Iterator _iterator = null;
+ private class EJBHashIterator implements Iterator {
+
+ Iterator _iterator;
Object lastReturned = null;
EJBHashIterator() {
_iterator = pcSet.iterator();
}
+
+ @Override
public boolean hasNext() {
assertIsValid();
assertInTransaction();
return _iterator.hasNext();
}
- public Object next() {
+
+ @Override
+ public EJBLocalObject next() {
assertIsValid();
assertInTransaction();
try {
lastReturned = _iterator.next();
- } catch(ConcurrentModificationException e) {
- IllegalStateException ise = new IllegalStateException(
- e.toString());
+ } catch (ConcurrentModificationException e) {
+ IllegalStateException ise = new IllegalStateException(e.toString());
ise.initCause(e);
throw ise;
}
- return helper.convertPCToEJBLocalObject(lastReturned, pm);
+ return helper.convertPCToEJBLocalObject(lastReturned, pm);
}
+
+ @Override
public void remove() {
assertIsValid();
assertInTransaction();
try {
_iterator.remove();
- } catch(ConcurrentModificationException e) {
- IllegalStateException ise = new IllegalStateException(
- e.toString());
+ } catch (ConcurrentModificationException e) {
+ IllegalStateException ise = new IllegalStateException(e.toString());
ise.initCause(e);
throw ise;
}
@@ -349,8 +362,9 @@ public void remove() {
* @throw IllegalStateException of validation fails.
*/
private void assertIsValid() {
- if (!valid)
+ if (!valid) {
throw new IllegalStateException(); // RESOLVE Exception text.
+ }
}
/**
@@ -370,9 +384,10 @@ private void assertInTransaction() {
* @param c the Collection to verify.
* @throw EJBException of validation fails.
*/
- private void assertInstancesOfLocalInterfaceImpl(Collection c) {
- for (Iterator it = c.iterator(); it.hasNext();)
+ private void assertInstancesOfLocalInterfaceImpl(Collection> c) {
+ for (Iterator> it = c.iterator(); it.hasNext();) {
helper.assertInstanceOfLocalInterfaceImpl(it.next());
+ }
}
/**
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB11HelperImpl.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB11HelperImpl.java
index 1ba9d7cbd12..074daf333be 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB11HelperImpl.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB11HelperImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * JDOEJB11HelperImpl.java
- *
- * Created on January 17, 2002
- */
-
package com.sun.jdo.spi.persistence.support.ejb.cmp;
import com.sun.jdo.api.persistence.support.JDOFatalDataStoreException;
@@ -32,7 +27,6 @@
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.JDOEJB11Helper;
import com.sun.jdo.spi.persistence.support.sqlstore.utility.NumericConverter;
import com.sun.jdo.spi.persistence.support.sqlstore.utility.NumericConverterFactory;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBObject;
@@ -46,30 +40,32 @@
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.io.StreamCorruptedException;
+import java.lang.System.Logger;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.ResourceBundle;
import java.util.Set;
import org.glassfish.persistence.common.I18NHelper;
-/*
+import static java.lang.System.Logger.Level.DEBUG;
+
+/**
* This is an abstract class which is a generic implementation of the
* JDOEJB11Helper interface for conversion of persistence-capable instances
* to and from EJB objects of type: EJBObject, PrimaryKey, and Collections of those.
* These implementations are common for CMP1.1 and CMP2.0 beans.
*
- * @author Marina Vatkina
+ * @author Marina Vatkina 2002
*/
abstract public class JDOEJB11HelperImpl implements JDOEJB11Helper {
/**
* I18N message handler
*/
- protected final static ResourceBundle messages = I18NHelper.loadBundle(
- JDOEJB11HelperImpl.class);
+ protected final static ResourceBundle messages = I18NHelper.loadBundle(JDOEJB11HelperImpl.class);
- //The logger
- protected static final Logger logger = LogHelperEntityInternal.getLogger();
+ private static final Logger LOG = System.getLogger(JDOEJB11HelperImpl.class.getName());
/**
* Converts persistence-capable instance to EJBObject.
@@ -77,16 +73,18 @@ abstract public class JDOEJB11HelperImpl implements JDOEJB11Helper {
* @param pm the associated instance of PersistenceManager.
* @return instance of EJBObject.
*/
+ @Override
public EJBObject convertPCToEJBObject (Object pc, PersistenceManager pm) {
- if (pc == null) return null;
+ if (pc == null) {
+ return null;
+ }
Object jdoObjectId = pm.getObjectId(pc);
Object key = convertObjectIdToPrimaryKey(jdoObjectId);
try {
return CMPHelper.getEJBObject(key, getContainer());
} catch (Exception ex) {
- EJBException e = new EJBException(I18NHelper.getMessage(messages,
- "EXC_ConvertPCToEJBObject", key.toString()), ex);// NOI18N
- logger.throwing("JDOEJB11HelperImpl", "convertPCToEJBObject", e); // NOI18N
+ EJBException e = new EJBException(
+ I18NHelper.getMessage(messages, "EXC_ConvertPCToEJBObject", key.toString()), ex);
throw e;
}
}
@@ -100,14 +98,14 @@ public EJBObject convertPCToEJBObject (Object pc, PersistenceManager pm) {
* @throws IllegalArgumentException if validate is true and instance does
* not exist in the database or is deleted.
*/
+ @Override
public Object convertEJBObjectToPC(EJBObject o, PersistenceManager pm, boolean validate) {
Object key = null;
try {
key = o.getPrimaryKey();
} catch (Exception ex) {
EJBException e = new EJBException(I18NHelper.getMessage(messages,
- "EXC_ConvertEJBObjectToPC", o.getClass().getName()), ex);// NOI18N
- logger.throwing("JDOEJB11HelperImpl", "convertEJBObjectToPC", e); // NOI18N
+ "EXC_ConvertEJBObjectToPC", o.getClass().getName()), ex);
throw e;
}
return convertPrimaryKeyToPC(key, pm, validate);
@@ -128,17 +126,13 @@ protected Object convertPrimaryKeyToPC(Object key, PersistenceManager pm, boolea
Object jdoObjectId = convertPrimaryKeyToObjectId(key);
pc = pm.getObjectById(jdoObjectId, validate);
} catch (JDOObjectNotFoundException ex) {
- logger.fine("---JDOEJB11HelperImpl.convertPrimaryKeyToPC: Object not found for: " + key); // NOI18N
-
throw new IllegalArgumentException(I18NHelper.getMessage(messages,
- "EXC_DeletedInstanceOtherTx", key.toString()));// NOI18N
+ "EXC_DeletedInstanceOtherTx", key.toString()));
}
if (validate && JDOHelper.isDeleted(pc)) {
- logger.fine("---JDOEJB11HelperImpl.convertPrimaryKeyToPC: Object is deleted for: " + key); // NOI18N
-
throw new IllegalArgumentException(I18NHelper.getMessage(messages,
- "EXC_DeletedInstanceThisTx", key.toString()));// NOI18N
+ "EXC_DeletedInstanceThisTx", key.toString()));
}
return pc;
@@ -151,16 +145,14 @@ protected Object convertPrimaryKeyToPC(Object key, PersistenceManager pm, boolea
* @param pm the associated instance of PersistenceManager.
* @return Collection of EJBObjects.
*/
- public Collection convertCollectionPCToEJBObject (Collection pcs, PersistenceManager pm) {
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionPCToEJBObject (Collection> pcs, PersistenceManager pm) {
+ Collection rc = new ArrayList<>();
Object o = null;
- for (java.util.Iterator it = pcs.iterator(); it.hasNext();) {
- o = convertPCToEJBObject((Object)it.next(), pm);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionPCToEJBObject() adding: " + o);// NOI18N
- }
+ for (Object pc : pcs) {
+ o = convertPCToEJBObject(pc, pm);
+ LOG.log(DEBUG, "convertCollectionPCToEJBObject() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -173,16 +165,14 @@ public Collection convertCollectionPCToEJBObject (Collection pcs, PersistenceMan
* @param pm the associated instance of PersistenceManager.
* @return Set of EJBObjects.
*/
- public Set convertCollectionPCToEJBObjectSet (Collection pcs, PersistenceManager pm) {
- java.util.Set rc = new java.util.HashSet();
+ @Override
+ public Set convertCollectionPCToEJBObjectSet (Collection> pcs, PersistenceManager pm) {
+ java.util.Set rc = new java.util.HashSet<>();
Object o = null;
- for (java.util.Iterator it = pcs.iterator(); it.hasNext();) {
- o = convertPCToEJBObject((Object)it.next(), pm);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionPCToEJBObjectSet() adding: " + o);// NOI18N
- }
+ for (Object pc : pcs) {
+ o = convertPCToEJBObject(pc, pm);
+ LOG.log(DEBUG, "convertCollectionPCToEJBObjectSet() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -198,17 +188,15 @@ public Set convertCollectionPCToEJBObjectSet (Collection pcs, PersistenceManager
* @throws IllegalArgumentException if validate is true and at least one instance does
* not exist in the database or is deleted.
*/
- public Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager pm,
- boolean validate) {
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionEJBObjectToPC(Collection> coll, PersistenceManager pm,
+ boolean validate) {
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = coll.iterator(); it.hasNext();) {
- o = convertEJBObjectToPC((EJBObject)it.next(), pm, validate);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionEJBObjectToPC() adding: " + o);// NOI18N
- }
+ for (Object element : coll) {
+ o = convertEJBObjectToPC((EJBObject)element, pm, validate);
+ LOG.log(DEBUG, "convertCollectionEJBObjectToPC() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -220,13 +208,13 @@ public Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceMa
* @param pm the associated instance of PersistenceManager.
* @return instance of the PrimaryKey Class.
*/
+ @Override
public Object convertPCToPrimaryKey (Object pc, PersistenceManager pm) {
- if (pc == null) return null;
- Object rc = convertObjectIdToPrimaryKey(pm.getObjectId(pc));
-
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest("\n---JDOEJB11HelperImpl.convertPCToPrimaryKey() PK: " + rc);// NOI18N
+ if (pc == null) {
+ return null;
}
+ Object rc = convertObjectIdToPrimaryKey(pm.getObjectId(pc));
+ LOG.log(DEBUG, "convertPCToPrimaryKey() PK: {0}", rc);
return rc;
}
@@ -238,16 +226,14 @@ public Object convertPCToPrimaryKey (Object pc, PersistenceManager pm) {
* @param pm the associated instance of PersistenceManager.
* @return Collection of the PrimaryKey Class instances.
*/
- public Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceManager pm) {
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionPCToPrimaryKey (Collection> pcs, PersistenceManager pm) {
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = pcs.iterator(); it.hasNext();) {
- o = convertPCToPrimaryKey(it.next(), pm);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionPCToPrimaryKey() adding: " + o);// NOI18N
- }
+ for (Object pc : pcs) {
+ o = convertPCToPrimaryKey(pc, pm);
+ LOG.log(DEBUG, "convertCollectionPCToPrimaryKey() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -259,6 +245,7 @@ public Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceMa
* @param objectId the Object Id to be converted.
* @return instance of the PrimaryKey Class.
*/
+ @Override
abstract public Object convertObjectIdToPrimaryKey (Object objectId);
/**
@@ -267,6 +254,7 @@ public Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceMa
* @param key the PrimaryKey instance to be converted.
* @return instance of the Object Id.
*/
+ @Override
abstract public Object convertPrimaryKeyToObjectId (Object key);
/**
@@ -275,16 +263,14 @@ public Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceMa
* @param oids Collection of the Object Id to be converted.
* @return Collection of of the PrimaryKey Class instances.
*/
- public Collection convertCollectionObjectIdToPrimaryKey (Collection oids) {
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionObjectIdToPrimaryKey (Collection> oids) {
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = oids.iterator(); it.hasNext();) {
- o = convertObjectIdToPrimaryKey(it.next());
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionObjectIdToPrimaryKey() adding: " + o);// NOI18N
- }
+ for (Object oid : oids) {
+ o = convertObjectIdToPrimaryKey(oid);
+ LOG.log(DEBUG, "convertCollectionObjectIdToPrimaryKey() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -296,16 +282,14 @@ public Collection convertCollectionObjectIdToPrimaryKey (Collection oids) {
* @param keys Collection of the PrimaryKey instances to be converted.
* @return Collection of the Object Id's.
*/
- public Collection convertCollectionPrimaryKeyToObjectId (Collection keys) {
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionPrimaryKeyToObjectId (Collection> keys) {
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = keys.iterator(); it.hasNext();) {
- o = convertPrimaryKeyToObjectId(it.next());
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB11HelperImpl.convertCollectionPrimaryKeyToObjectId() adding: " + o);// NOI18N
- }
+ for (Object key : keys) {
+ o = convertPrimaryKeyToObjectId(key);
+ LOG.log(DEBUG, "convertCollectionPrimaryKeyToObjectId() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -316,6 +300,7 @@ public Collection convertCollectionPrimaryKeyToObjectId (Collection keys) {
* @param serializableObject Instance of a Serializable Object
* @return serializableObject serialized into a byte array
*/
+ @Override
public byte[] writeSerializableObjectToByteArray(Serializable serializableObject)
{
byte[] byteArray = null;
@@ -333,7 +318,7 @@ public byte[] writeSerializableObjectToByteArray(Serializable serializableObject
{
String clsName = serializableObject.getClass().getName();
throw new JDOUserException(I18NHelper.getMessage(messages,
- "EXC_IOWriteSerializableObject", clsName), e);// NOI18N
+ "EXC_IOWriteSerializableObject", clsName), e);
}
}
return byteArray;
@@ -346,6 +331,7 @@ public byte[] writeSerializableObjectToByteArray(Serializable serializableObject
* @return A Serializable object contructed from byteArray
* @see #writeSerializableObjectToByteArray(Serializable)
*/
+ @Override
public Serializable readSerializableObjectFromByteArray(byte[] byteArray)
{
Serializable serializableObject = null;
@@ -366,12 +352,12 @@ public Serializable readSerializableObjectFromByteArray(byte[] byteArray)
catch (ClassNotFoundException e)
{
throw new JDOFatalDataStoreException(I18NHelper.getMessage(messages,
- "EXC_CNFReadSerializableObject"), e);// NOI18N
+ "EXC_CNFReadSerializableObject"), e);
}
catch(java.io.IOException e)
{
throw new JDOFatalDataStoreException(I18NHelper.getMessage(messages,
- "EXC_IOReadSerializableObject"), e);// NOI18N
+ "EXC_IOReadSerializableObject"), e);
}
}
return serializableObject;
@@ -383,6 +369,7 @@ public Serializable readSerializableObjectFromByteArray(byte[] byteArray)
* correct policy value to the NumericConverterFactory.
* @return NumericConverter for given object policy
*/
+ @Override
public NumericConverter getNumericConverter() {
int policy = CMPHelper.getNumericConverterPolicy(getContainer());
return NumericConverterFactory.getNumericConverter(policy);
@@ -393,7 +380,8 @@ public NumericConverter getNumericConverter() {
* of the concrete bean class.
* @return the pc class object
*/
- abstract public Class getPCClass ();
+ @Override
+ abstract public Class> getPCClass ();
/**
* Validates that this instance is of the correct implementation class
@@ -402,6 +390,7 @@ public NumericConverter getNumericConverter() {
* @param o the instance to validate.
* @throws IllegalArgumentException if validation fails.
*/
+ @Override
abstract public void assertInstanceOfRemoteInterfaceImpl(Object o);
/**
@@ -418,18 +407,18 @@ protected void assertInstanceOfRemoteInterfaceImpl(Object o,
// We can't check if null is the correct type or not. So
// we let it succeed.
- if (o == null)
+ if (o == null) {
return;
+ }
try {
CMPHelper.assertValidRemoteObject(o, getContainer());
} catch (EJBException ex) {
- String msg = I18NHelper.getMessage(messages, "EXC_WrongRemoteInstance", // NOI18N
+ String msg = I18NHelper.getMessage(messages, "EXC_WrongRemoteInstance",
new Object[] {o.getClass().getName(), beanName,
ex.getMessage()});
- logger.log(Logger.WARNING, msg);
- throw new IllegalArgumentException(msg);
+ throw new IllegalArgumentException(msg, ex);
}
}
@@ -442,7 +431,7 @@ protected void assertInstanceOfRemoteInterfaceImpl(Object o,
protected void assertPrimaryKeyNotNull(Object pk) {
if (pk == null) {
throw new IllegalArgumentException(I18NHelper.getMessage(
- messages, "EXC_pknull_exception")); // NOI18N
+ messages, "EXC_pknull_exception"));
}
}
@@ -459,7 +448,7 @@ public void assertPrimaryKeyFieldNotNull(Object pkfield, String pkfieldName,
if (pkfield == null) {
throw new IllegalArgumentException(I18NHelper.getMessage(
- messages, "EXC_pkfieldnull_exception", // NOI18N
+ messages, "EXC_pkfieldnull_exception",
pkfieldName, beanName));
}
}
@@ -474,7 +463,7 @@ public void assertPrimaryKeyFieldNotNull(Object pkfield, String pkfieldName,
protected void assertObjectIdNotNull(Object oid) {
if (oid == null) {
throw new JDOFatalInternalException(I18NHelper.getMessage(
- messages, "EXC_oidnull_exception")); // NOI18N
+ messages, "EXC_oidnull_exception"));
}
}
@@ -493,7 +482,8 @@ public HelperObjectInputStream(InputStream is, ClassLoader cl)
}
/** Overrides the same method of the base class */
- protected Class resolveClass(ObjectStreamClass v)
+ @Override
+ protected Class> resolveClass(ObjectStreamClass v)
throws IOException, ClassNotFoundException {
return Class.forName(v.getName(), true, classLoader);
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB20HelperImpl.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB20HelperImpl.java
index a9c71d7dc5a..111c7c64cd0 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB20HelperImpl.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/JDOEJB20HelperImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,28 +15,24 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * JDOEJB20HelperImpl.java
- *
- * Created on January 17, 2002
- */
-
package com.sun.jdo.spi.persistence.support.ejb.cmp;
import com.sun.jdo.api.persistence.support.PersistenceManager;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.CMPHelper;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.JDOEJB20Helper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import jakarta.ejb.EJBContext;
import jakarta.ejb.EJBException;
import jakarta.ejb.EJBLocalObject;
+import java.lang.System.Logger;
import java.util.Collection;
import java.util.Set;
import org.glassfish.persistence.common.I18NHelper;
+import static java.lang.System.Logger.Level.DEBUG;
+
/*
* This is an abstract class which is a generic implementation of the
@@ -43,10 +40,11 @@
* to and from EJB objects of type EJBLocalObject and Collections of those.
* It extends JDOEJB11HelperImpl for conversion of instances of other types.
*
- * @author Marina Vatkina
+ * @author Marina Vatkina 2002
*/
-abstract public class JDOEJB20HelperImpl extends JDOEJB11HelperImpl
- implements JDOEJB20Helper {
+abstract public class JDOEJB20HelperImpl extends JDOEJB11HelperImpl implements JDOEJB20Helper {
+
+ private static final Logger LOG = System.getLogger(JDOEJB20HelperImpl.class.getName());
/**
* Converts persistence-capable instance to EJBLocalObject.
@@ -54,16 +52,18 @@ abstract public class JDOEJB20HelperImpl extends JDOEJB11HelperImpl
* @param pm the associated instance of PersistenceManager.
* @return instance of EJBLocalObject.
*/
+ @Override
public EJBLocalObject convertPCToEJBLocalObject (Object pc, PersistenceManager pm) {
- if (pc == null) return null;
+ if (pc == null) {
+ return null;
+ }
Object jdoObjectId = pm.getObjectId(pc);
Object key = convertObjectIdToPrimaryKey(jdoObjectId);
try {
return CMPHelper.getEJBLocalObject(key, getContainer());
} catch (Exception ex) {
EJBException e = new EJBException(I18NHelper.getMessage(messages,
- "EXC_ConvertPCToEJBLocalObject", key.toString()), ex);// NOI18N
- logger.throwing("JDOEJB20HelperImpl", "convertPCToEJBLocalObject", e); // NOI18N
+ "EXC_ConvertPCToEJBLocalObject", key.toString()), ex);
throw e;
}
}
@@ -76,17 +76,19 @@ public EJBLocalObject convertPCToEJBLocalObject (Object pc, PersistenceManager p
* @param context the EJBContext of the calling bean.
* @return instance of EJBLocalObject.
*/
+ @Override
public EJBLocalObject convertPCToEJBLocalObject (Object pc, PersistenceManager pm,
EJBContext context) {
- if (pc == null) return null;
+ if (pc == null) {
+ return null;
+ }
Object jdoObjectId = pm.getObjectId(pc);
Object key = convertObjectIdToPrimaryKey(jdoObjectId);
try {
return CMPHelper.getEJBLocalObject(key, getContainer(), context);
} catch (Exception ex) {
EJBException e = new EJBException(I18NHelper.getMessage(messages,
- "EXC_ConvertPCToEJBLocalObjectCtx", key.toString()), ex);// NOI18N
- logger.throwing("JDOEJB20HelperImpl", "convertPCToEJBLocalObjectCtx", e); // NOI18N
+ "EXC_ConvertPCToEJBLocalObjectCtx", key.toString()), ex);
throw e;
}
}
@@ -100,14 +102,14 @@ public EJBLocalObject convertPCToEJBLocalObject (Object pc, PersistenceManager p
* @throws IllegalArgumentException if validate is true and instance does
* not exist in the database or is deleted.
*/
+ @Override
public Object convertEJBLocalObjectToPC(EJBLocalObject o, PersistenceManager pm, boolean validate) {
Object key = null;
try {
key = o.getPrimaryKey();
} catch (Exception ex) {
EJBException e = new EJBException(I18NHelper.getMessage(messages,
- "EXC_ConvertEJBObjectToPC", o.getClass().getName()), ex);// NOI18N
- logger.throwing("JDOEJB20HelperImpl", "convertEJBLocalObjectToPC", e); // NOI18N
+ "EXC_ConvertEJBObjectToPC", o.getClass().getName()), ex);
throw e;
}
return convertPrimaryKeyToPC(key, pm, validate);
@@ -120,16 +122,14 @@ public Object convertEJBLocalObjectToPC(EJBLocalObject o, PersistenceManager pm,
* @param pm the associated instance of PersistenceManager.
* @return Collection of EJBLocalObjects.
*/
- public Collection convertCollectionPCToEJBLocalObject (Collection pcs, PersistenceManager pm){
- Collection rc = new java.util.ArrayList();
+ @Override
+ public Collection convertCollectionPCToEJBLocalObject (Collection> pcs, PersistenceManager pm){
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = pcs.iterator(); it.hasNext();) {
- o = convertPCToEJBLocalObject((Object)it.next(), pm);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB20HelperImpl.convertCollectionPCToEJBLocalObject() adding: " + o);// NOI18N
- }
+ for (Object pc : pcs) {
+ o = convertPCToEJBLocalObject(pc, pm);
+ LOG.log(DEBUG, "convertCollectionPCToEJBLocalObject() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -142,16 +142,14 @@ public Collection convertCollectionPCToEJBLocalObject (Collection pcs, Persisten
* @param pm the associated instance of PersistenceManager.
* @return Set of EJBLocalObjects.
*/
- public Set convertCollectionPCToEJBLocalObjectSet (Collection pcs, PersistenceManager pm) {
- java.util.Set rc = new java.util.HashSet();
+ @Override
+ public Set convertCollectionPCToEJBLocalObjectSet (Collection> pcs, PersistenceManager pm) {
+ java.util.Set rc = new java.util.HashSet<>();
Object o = null;
- for (java.util.Iterator it = pcs.iterator(); it.hasNext();) {
- o = convertPCToEJBLocalObject((Object)it.next(), pm);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB20HelperImpl.convertCollectionPCToEJBLocalObjectSet() adding: " + o);// NOI18N
- }
+ for (Object pc : pcs) {
+ o = convertPCToEJBLocalObject(pc, pm);
+ LOG.log(DEBUG, "convertCollectionPCToEJBLocalObjectSet() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -167,17 +165,15 @@ public Set convertCollectionPCToEJBLocalObjectSet (Collection pcs, PersistenceMa
* @throws IllegalArgumentException if validate is true and at least one instance does
* not exist in the database or is deleted.
*/
- public Collection convertCollectionEJBLocalObjectToPC (Collection coll, PersistenceManager pm,
+ @Override
+ public Collection convertCollectionEJBLocalObjectToPC (Collection> coll, PersistenceManager pm,
boolean validate) {
- Collection rc = new java.util.ArrayList();
+ Collection rc = new java.util.ArrayList<>();
Object o = null;
- for (java.util.Iterator it = coll.iterator(); it.hasNext();) {
- o = convertEJBLocalObjectToPC((EJBLocalObject)it.next(), pm, validate);
- if(logger.isLoggable(Logger.FINEST) ) {
- logger.finest(
- "\n---JDOEJB20HelperImpl.convertCollectionEJBLocalObjectToPC() adding: " + o);// NOI18N
- }
+ for (Object element : coll) {
+ o = convertEJBLocalObjectToPC((EJBLocalObject)element, pm, validate);
+ LOG.log(DEBUG, "convertCollectionEJBLocalObjectToPC() adding: {0}", o);
rc.add(o);
}
return rc;
@@ -190,6 +186,7 @@ public Collection convertCollectionEJBLocalObjectToPC (Collection coll, Persiste
* @param o the instance to validate.
* @throws IllegalArgumentException if validation fails.
*/
+ @Override
abstract public void assertInstanceOfLocalInterfaceImpl(Object o);
/**
@@ -207,18 +204,18 @@ protected void assertInstanceOfLocalInterfaceImpl(Object o,
// We can't check if null is the correct type or not. So
// we let it succeed.
- if (o == null)
+ if (o == null) {
return;
+ }
try {
CMPHelper.assertValidLocalObject(o, getContainer());
} catch (EJBException ex) {
- String msg = I18NHelper.getMessage(messages, "EXC_WrongLocalInstance", // NOI18N
+ String msg = I18NHelper.getMessage(messages, "EXC_WrongLocalInstance",
new Object[] {o.getClass().getName(), beanName,
ex.getMessage()});
- logger.log(Logger.WARNING, msg);
- throw new IllegalArgumentException(msg);
+ throw new IllegalArgumentException(msg, ex);
}
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityFinder.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityFinder.java
index ab9e78bff8b..e8429d0a697 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityFinder.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityFinder.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -16,9 +17,6 @@
package com.sun.jdo.spi.persistence.support.ejb.cmp;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
/**
*
* @author Craig Russell
@@ -38,10 +36,4 @@ public class LogHelperEntityFinder {
*/
protected static final String bundleName = "com.sun.jdo.spi.persistence.support.ejb.cmp.Bundle"; //NOI18N
- /** Return the logger for the entity finder component
- */
- public static Logger getLogger() {
- return LogHelper.getLogger (componentName, bundleName, loader);
- }
-
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityInternal.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityInternal.java
index 7b64b3c46f2..7d854aa18b8 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityInternal.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityInternal.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -16,9 +17,6 @@
package com.sun.jdo.spi.persistence.support.ejb.cmp;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
/**
*
* @author Craig Russell
@@ -38,10 +36,4 @@ public class LogHelperEntityInternal {
*/
protected static final String bundleName = "com.sun.jdo.spi.persistence.support.ejb.cmp.Bundle"; //NOI18N
- /** Return the logger for the entity internal component
- */
- public static Logger getLogger() {
- return LogHelper.getLogger (componentName, bundleName, loader);
- }
-
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityLifecycle.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityLifecycle.java
index c563089aec0..04d2fa95944 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityLifecycle.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/cmp/LogHelperEntityLifecycle.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -16,9 +17,6 @@
package com.sun.jdo.spi.persistence.support.ejb.cmp;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
/**
*
* @author Craig Russell
@@ -38,10 +36,4 @@ public class LogHelperEntityLifecycle {
*/
protected static final String bundleName = "com.sun.jdo.spi.persistence.support.ejb.cmp.Bundle"; //NOI18N
- /** Return the logger for the entity lifecycle component
- */
- public static Logger getLogger() {
- return LogHelper.getLogger (componentName, bundleName, loader);
- }
-
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/Bundle.properties b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/Bundle.properties
index cbb75075f15..9b42eba7cd9 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/Bundle.properties
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/Bundle.properties
@@ -63,9 +63,5 @@ cmpc.cmp_module_error=JDO83002: Caught {0} while processing CMP beans for applic
cmpc.compile=JDO83003: Compiling {0} ....
cmpc.cmp_complilation_failed=JDO83004: CMP Compilation failed. See log for details.
-cmpc.processing_cmp=JDO83005: Start of CMP section for [{0}]
-cmpc.done_processing_cmp=JDO83006: End of CMP section for [{0}]
cmpc.cmp_complilation_exception=JDO83007: Caught Exception while compiling generated classes: {0}
cmpc.cmp_complilation_problems=JDO83008: CMP Compilation failed: {0}
-
-cmpc.cmp_cleanup_problems=JDO83009: CMP cleanup failed.
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPDeployerImpl.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPDeployerImpl.java
index a450b2fea05..7460816f32e 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPDeployerImpl.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPDeployerImpl.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -21,12 +22,12 @@
import com.sun.jdo.spi.persistence.support.ejb.ejbc.CMPProcessor;
import com.sun.jdo.spi.persistence.support.ejb.ejbc.JDOCodeGenerator;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.EJBHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.File;
+import java.lang.System.Logger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@@ -50,6 +51,9 @@
import org.jvnet.hk2.annotations.Optional;
import org.jvnet.hk2.annotations.Service;
+import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.WARNING;
+
/**
* Generates concrete impls for CMP beans in an archive.
*
@@ -59,7 +63,12 @@
@Service
public class CMPDeployerImpl implements CMPDeployer {
- @Inject @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME) @Optional
+ private static final Logger LOG = System.getLogger(CMPDeployerImpl.class.getName());
+ private static final ResourceBundle messages = I18NHelper.loadBundle(CMPDeployerImpl.class);
+
+ @Inject
+ @Named(ServerEnvironment.DEFAULT_INSTANCE_NAME)
+ @Optional
private JavaConfig javaConfig;
/**
@@ -67,6 +76,7 @@ public class CMPDeployerImpl implements CMPDeployer {
*
* @throws DeploymentException if this exception was thrown while generating concrete impls
*/
+ @Override
public void deploy(DeploymentContext ctx) throws DeploymentException {
// deployment descriptor object representation for the archive
@@ -78,21 +88,16 @@ public void deploy(DeploymentContext ctx) throws DeploymentException {
// ejb name
String beanName = null;
- // GeneratorException message if any
- StringBuffer generatorExceptionMsg = null;
-
+ final CmpGeneratorException cause = new CmpGeneratorException();
try {
CMPGenerator gen = new JDOCodeGenerator();
// stubs dir for the current deployment (generated/ejb)
- File stubsDir = ctx.getScratchDir("ejb"); //NOI18N
+ File stubsDir = ctx.getScratchDir("ejb");
application = ctx.getModuleMetaData(Application.class);
- if (_logger.isLoggable(Logger.FINE)) {
- _logger.fine( "cmpc.processing_cmp", //NOI18N
- application.getRegistrationName());
- }
+ LOG.log(DEBUG, "Start of CMP section for [{0}]", application.getRegistrationName());
List cmpFiles = new ArrayList();
final ClassLoader jcl = application.getClassLoader();
@@ -102,44 +107,38 @@ public void deploy(DeploymentContext ctx) throws DeploymentException {
// This gives the dir where application is exploded
String archiveUri = ctx.getSource().getURI().getSchemeSpecificPart();
- if (_logger.isLoggable(Logger.FINE)) {
- _logger.fine("[CMPC] Module Dir name is " //NOI18N
- + archiveUri);
+ {
+ LOG.log(DEBUG, () -> "[CMPC] Module Dir name is " + archiveUri);
}
// xml dir for the current deployment (generated/xml)
String generatedXmlsPath = ctx.getScratchDir("xml").getCanonicalPath();
- if (_logger.isLoggable(Logger.FINE)) {
- _logger.fine("[CMPC] Generated XML Dir name is " //NOI18N
- + generatedXmlsPath);
+ {
+ LOG.log(DEBUG, () -> "[CMPC] Generated XML Dir name is " + generatedXmlsPath);
}
try {
long start = System.currentTimeMillis();
gen.init(bundle, ctx, archiveUri, generatedXmlsPath);
- Iterator ejbs=bundle.getEjbs().iterator();
+ Iterator ejbs=bundle.getEjbs().iterator();
while ( ejbs.hasNext() ) {
- EjbDescriptor desc = (EjbDescriptor) ejbs.next();
+ EjbDescriptor desc = ejbs.next();
beanName = desc.getName();
- if (_logger.isLoggable(Logger.FINE)) {
- _logger.fine("[CMPC] Ejb Class Name: " //NOI18N
- + desc.getEjbClassName());
+ {
+ LOG.log(DEBUG, () -> "[CMPC] Ejb Class Name: " + desc.getEjbClassName());
}
- if ( desc instanceof IASEjbCMPEntityDescriptor) {
+ if (desc instanceof IASEjbCMPEntityDescriptor) {
// generate concrete CMP class implementation
- IASEjbCMPEntityDescriptor entd =
- (IASEjbCMPEntityDescriptor)desc;
+ IASEjbCMPEntityDescriptor entd = (IASEjbCMPEntityDescriptor) desc;
- if (_logger.isLoggable(Logger.FINE)) {
- _logger.fine(
- "[CMPC] Home Object Impl name is " //NOI18N
- + entd.getLocalHomeImplClassName());
+ {
+ LOG.log(DEBUG, () -> "[CMPC] Home Object Impl name is " + entd.getLocalHomeImplClassName());
}
// The classloader needs to be set else we fail down the road.
@@ -149,105 +148,77 @@ public void deploy(DeploymentContext ctx) throws DeploymentException {
try {
gen.generate(entd, stubsDir, stubsDir);
} catch (GeneratorException e) {
- String msg = e.getMessage();
- _logger.warning(msg);
- generatorExceptionMsg = addGeneratorExceptionMessage(
- msg, generatorExceptionMsg);
+ cause.addSuppressed(e);
} finally {
entd.setClassLoader(ocl);
}
-
- /* WARNING: IASRI 4683195
- * JDO Code failed when there was a relationship involved
- * because it depends upon the orginal ejbclasname and hence
- * this code is shifted to just before the Remote Impl is
- * generated.Remote/Home Impl generation depends upon this
- * value
- */
-
}
} // end while ejbs.hasNext()
beanName = null;
-
cmpFiles.addAll(gen.cleanup());
-
long end = System.currentTimeMillis();
- _logger.fine("CMP Generation: " + (end - start) + " msec");
+ LOG.log(DEBUG, () -> "CMP Generation: " + (end - start) + " ms");
} catch (GeneratorException e) {
- String msg = e.getMessage();
- _logger.warning(msg);
- generatorExceptionMsg = addGeneratorExceptionMessage(msg,
- generatorExceptionMsg);
+ cause.addSuppressed(e);
}
bundle = null; // Used in exception processing
// Compile the generated classes
- if (generatorExceptionMsg == null) {
+ if (!cause.hasErrors()) {
long start = System.currentTimeMillis();
compileClasses(ctx, cmpFiles, stubsDir);
- long end = System.currentTimeMillis();
- _logger.fine("Java Compilation: " + (end - start) + " msec");
+ LOG.log(DEBUG, () -> "Java Compilation: " + (System.currentTimeMillis() - start) + " ms");
// Do Java2DB if needed
- start = System.currentTimeMillis();
+ long start2 = System.currentTimeMillis();
CMPProcessor processor = new CMPProcessor(ctx);
processor.process();
- end = System.currentTimeMillis();
- _logger.fine("Java2DB processing: " + (end - start) + " msec");
- _logger.fine( "cmpc.done_processing_cmp",
- application.getRegistrationName());
+ long end = System.currentTimeMillis();
+ LOG.log(DEBUG, () -> "Java2DB processing: " + (end - start2) + " ms");
+ LOG.log(DEBUG, "JDO83006: End of CMP section for [{0}]", application.getRegistrationName());
}
} catch (GeneratorException e) {
- _logger.warning(e.getMessage());
throw new DeploymentException(e);
-
} catch (Throwable e) {
+ cause.addSuppressed(e);
String eType = e.getClass().getName();
String appName = application.getRegistrationName();
String exMsg = e.getMessage();
- String msg = null;
+ final String msg;
if (bundle == null) {
// Application or compilation error
- msg = I18NHelper.getMessage(messages,
- "cmpc.cmp_app_error", eType, appName, exMsg);
+ msg = I18NHelper.getMessage(messages, "cmpc.cmp_app_error", eType, appName, exMsg);
} else {
String bundleName = bundle.getModuleDescriptor().getArchiveUri();
if (beanName == null) {
// Module processing error
- msg = I18NHelper.getMessage(messages,
- "cmpc.cmp_module_error",
- new Object[] {eType, appName, bundleName, exMsg});
+ msg = I18NHelper.getMessage(messages, "cmpc.cmp_module_error", eType, appName, bundleName, exMsg);
} else {
// CMP bean generation error
- msg = I18NHelper.getMessage(messages,
- "cmpc.cmp_bean_error",
- new Object[] {eType, beanName, appName, bundleName, exMsg});
+ msg = I18NHelper.getMessage(messages, "cmpc.cmp_bean_error", eType, beanName, appName, bundleName, exMsg);
}
}
-
- _logger.log(Logger.SEVERE, msg, e);
-
- throw new DeploymentException(msg);
+ throw new DeploymentException(msg, cause.fillInStackTrace());
}
- if (generatorExceptionMsg != null) {
- // We already logged each separate part.
- throw new DeploymentException(generatorExceptionMsg.toString());
+ if (cause.hasErrors()) {
+ throw new DeploymentException("Deployment failed.\n" + cause.getMessage(), cause.fillInStackTrace());
}
}
/**
* Integration point for cleanup on undeploy or failed deploy.
*/
+ @Override
public void clean(DeploymentContext ctx) {
CMPProcessor processor = new CMPProcessor(ctx);
processor.clean();
@@ -256,11 +227,12 @@ public void clean(DeploymentContext ctx) {
/**
* Integration point for application unload
*/
+ @Override
public void unload(ClassLoader cl) {
try {
EJBHelper.notifyApplicationUnloaded(cl);
} catch (Exception e) {
- _logger.log(Logger.WARNING, "cmpc.cmp_cleanup_problems", e);
+ LOG.log(WARNING, "CMP cleanup failed.", e);
}
}
@@ -287,27 +259,26 @@ private void compileClasses(DeploymentContext ctx, List files,
options.addAll(javaConfig.getJavacOptionsAsList());
}
- StringBuffer msgBuffer = new StringBuffer();
+ StringBuilder msgBuffer = new StringBuilder();
boolean compilationResult = false;
try {
// add the rest of the javac options
options.add("-d");
options.add(destDir.toString());
options.add("-classpath");
- options.add(System.getProperty("java.class.path") //TODO do we need to add java.class.path for compilation?
- + File.pathSeparator + classPath);
+ // TODO do we need to add java.class.path for compilation?
+ options.add(System.getProperty("java.class.path") + File.pathSeparator + classPath);
- if (_logger.isLoggable(Logger.FINE)) {
+ {
for(File file : files) {
- _logger.fine(I18NHelper.getMessage(messages,
- "cmpc.compile", file.getPath()));
+ LOG.log(DEBUG, () -> I18NHelper.getMessage(messages, "cmpc.compile", file));
}
- StringBuffer sbuf = new StringBuffer();
- for ( String s : options) {
+ StringBuilder sbuf = new StringBuilder();
+ for (String s : options) {
sbuf.append("\n\t").append(s);
}
- _logger.fine("[CMPC] JAVAC OPTIONS: " + sbuf.toString());
+ LOG.log(DEBUG, () -> "[CMPC] JAVAC OPTIONS: " + sbuf.toString());
}
// Using Java 6 compiler API to compile the generated .java files
@@ -316,23 +287,21 @@ private void compileClasses(DeploymentContext ctx, List files,
new DiagnosticCollector();
StandardJavaFileManager manager =
compiler.getStandardFileManager(diagnostics, null, null);
- Iterable compilationUnits = manager.getJavaFileObjectsFromFiles(files);
+ Iterable extends JavaFileObject> compilationUnits = manager.getJavaFileObjectsFromFiles(files);
long start = System.currentTimeMillis();
- long end = start;
compilationResult = compiler.getTask(
null, manager, diagnostics, options, null, compilationUnits).call();
- end = System.currentTimeMillis();
- _logger.fine("JAVA compile time (" + files.size()
- + " files) = " + (end - start));
+ long end = System.currentTimeMillis();
+ LOG.log(DEBUG, () -> "JAVA compile time (" + files.size() + " files) = " + (end - start));
// Save compilation erros in msgBuffer to be used in case of failure
for (Diagnostic extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
//Ignore NOTE about generated non safe code
if (diagnostic.getKind().equals(Diagnostic.Kind.NOTE)) {
- if (_logger.isLoggable(Logger.FINE)) {
+ {
msgBuffer.append("\n").append(diagnostic.getMessage(null));
}
continue;
@@ -343,10 +312,9 @@ private void compileClasses(DeploymentContext ctx, List files,
manager.close();
} catch(Exception jce) {
- _logger.fine("cmpc.cmp_complilation_exception", jce);
- String msg = I18NHelper.getMessage(messages,
- "cmpc.cmp_complilation_exception",
- new Object[] {jce.getMessage()} );
+ LOG.log(DEBUG, () -> "cmpc.cmp_complilation_exception", jce);
+ String msg = I18NHelper.getMessage(messages, "cmpc.cmp_complilation_exception",
+ new Object[] {jce.getMessage()});
GeneratorException ge = new GeneratorException(msg);
ge.initCause(jce);
throw ge;
@@ -354,32 +322,23 @@ private void compileClasses(DeploymentContext ctx, List files,
if (!compilationResult) {
// Log but throw an exception with a shorter message
- _logger.warning(I18NHelper.getMessage(messages,
- "cmpc.cmp_complilation_problems", msgBuffer.toString()));
- throw new GeneratorException(I18NHelper.getMessage(
- messages, "cmpc.cmp_complilation_failed"));
+ LOG.log(WARNING,
+ () -> I18NHelper.getMessage(messages, "cmpc.cmp_complilation_problems", msgBuffer.toString()));
+ throw new GeneratorException(I18NHelper.getMessage(messages, "cmpc.cmp_complilation_failed"));
}
}
- /** Adds GeneratorException message to the buffer.
- *
- * @param msg the message text to add to the buffer.
- * @param buf the buffer to use.
- * @return the new or updated buffer.
- */
- private StringBuffer addGeneratorExceptionMessage(String msg, StringBuffer buf) {
- StringBuffer rc = buf;
- if (rc == null)
- rc = new StringBuffer(msg);
- else
- rc.append('\n').append(msg);
-
- return rc;
- }
- // ---- VARIABLE(S) - PRIVATE --------------------------------------
- private static final Logger _logger = LogHelperCmpCompiler.getLogger();
- private static final ResourceBundle messages = I18NHelper.loadBundle(CMPDeployerImpl.class);
+ public static class CmpGeneratorException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+ /**
+ * @return true if there was at least one exception added using {@link #addSuppressed(Throwable)}
+ */
+ public boolean hasErrors() {
+ return getSuppressed().length != 0;
+ }
+ }
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPGenerator.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPGenerator.java
index d7eb4219cd0..dcec13a117a 100755
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPGenerator.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/CMPGenerator.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -44,6 +45,7 @@ public interface CMPGenerator {
* @throws GeneratorException if there is a problem initializing bean
* processing.
*/
+ @Deprecated
void init(EjbBundleDescriptorImpl ejbBundleDescriptor, ClassLoader cl,
String bundlePathName) throws GeneratorException;
@@ -90,6 +92,6 @@ void generate(IASEjbCMPEntityDescriptor descr, File srcout, File classout)
* @return a Collection of Exceptions if there are any problems processing the bean.
* Returns an empty Collection if validation succeeds.
*/
- Collection validate(IASEjbCMPEntityDescriptor descr);
+ Collection validate(IASEjbCMPEntityDescriptor descr);
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/LogHelperCmpCompiler.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/LogHelperCmpCompiler.java
index fe10bd6f137..c21274e4db5 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/LogHelperCmpCompiler.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/codegen/LogHelperCmpCompiler.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -16,9 +17,6 @@
package com.sun.jdo.spi.persistence.support.ejb.codegen;
-import com.sun.jdo.spi.persistence.utility.logging.LogHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
-
/**
*
* @author Piali Nag
@@ -39,10 +37,4 @@ public class LogHelperCmpCompiler {
protected static final String bundleName =
"com.sun.jdo.spi.persistence.support.ejb.codegen.Bundle"; // NOI18N
- /** Return the logger for the codegen component
- */
- public static Logger getLogger() {
- return LogHelper.getLogger (componentName, bundleName, loader);
- }
-
}
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/Bundle.properties b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/Bundle.properties
index 86cb9c2798e..3da13cc18e9 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/Bundle.properties
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/Bundle.properties
@@ -240,7 +240,5 @@ JDO.pm_closed_exception=JDO74047: Persistence manager is closed.
#
#
#
-ejb.CMPProcessor.createanddroptables=Processing event to create tables: {0}, drop tables: {1}.
ejb.PersistenceProcessor.createanddroptables=Processing event to create tables: {0}, drop tables: {1}.
ejb.PersistenceProcessor.createanddropfilenames=Processing event to create files - create file: {0}, and drop file: {1}.
-ejb.CMPProcessor.createanddropfilenames=Names of the files to be used for create is: {0}, and for drop is: {1}.
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMP20Templates.properties b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMP20Templates.properties
index 386e24a70d5..13974344b49 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMP20Templates.properties
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMP20Templates.properties
@@ -495,7 +495,7 @@ ejbSingleSelectorBody = \
\t\t'}'\n\
\t\tFinderException ex = new FinderException(msg);\n\
\t\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.FINE, _jdoBeanName, ex);\n\
+ \t\t\tjava.lang.System.Logger.Level.DEBUG, _jdoBeanName, ex);\n\
\t\tthrow ex;\n\
\t'}' \n\
\tif (result.size() < 1) '{' \n\
@@ -507,7 +507,7 @@ ejbSingleSelectorBody = \
\t\t'}'\n\
\t\tFinderException ex = new ObjectNotFoundException(msg);\n\
\t\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.FINER, _jdoBeanName, ex);\n\
+ \t\t\tjava.lang.System.Logger.Level.DEBUG, _jdoBeanName, ex);\n\
\t\tthrow ex;\n\
\t'}'\n
@@ -546,7 +546,7 @@ ejbAggregateSelectorPrimitiveReturnBody = \
\t\t'}'\n\
\t\tObjectNotFoundException ex = new ObjectNotFoundException(msg);\n\
\t\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.FINER, _jdoBeanName, ex);\n\
+ \t\t\tjava.lang.System.Logger.Level.DEBUG, _jdoBeanName, ex);\n\
\t\tthrow ex;\n\
\t'}' \n\
\trs = (({1})result){2};\n\
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPProcessor.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPProcessor.java
index 8257da5f65b..5a0d639056f 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPProcessor.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPProcessor.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022 Contributors to the Eclipse Foundation
+ * Copyright (c) 2022, 2026 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -19,7 +19,8 @@
import com.sun.enterprise.deployment.ResourceReferenceDescriptor;
import com.sun.jdo.spi.persistence.support.sqlstore.ejb.DeploymentHelper;
-import com.sun.jdo.spi.persistence.utility.logging.Logger;
+
+import java.lang.System.Logger;
import org.glassfish.api.deployment.DeploymentContext;
import org.glassfish.api.naming.SimpleJndiName;
@@ -27,6 +28,8 @@
import org.glassfish.persistence.common.DatabaseConstants;
import org.glassfish.persistence.common.Java2DBProcessorHelper;
+import static java.lang.System.Logger.Level.DEBUG;
+
/**
* If the application contains cmp 2.x beans process them. Check if
* tables have to created or dropped depending on where we are called
@@ -35,7 +38,7 @@
*/
public class CMPProcessor {
- private static Logger logger = LogHelperEJBCompiler.getLogger();
+ private static final Logger LOG = System.getLogger(CMPProcessor.class.getName());
private Java2DBProcessorHelper helper;
@@ -76,7 +79,7 @@ public void process() {
boolean userDropTables = cmpResource.isDropTablesAtUndeploy();
- logger.fine("ejb.CMPProcessor.createanddroptables", new Object[] {createTables, userDropTables});
+ LOG.log(DEBUG, "Processing event to create tables: {0}, drop tables: {1}.", createTables, userDropTables);
if (!createTables && !userDropTables) {
// Nothing to do.
@@ -87,11 +90,9 @@ public void process() {
helper.setDropTablesValue(userDropTables, bundle.getName());
constructJdbcFileNames(bundle);
- if (logger.isLoggable(Logger.FINE)) {
- logger.fine("ejb.CMPProcessor.createanddropfilenames",
- helper.getCreateJdbcFileName(bundle.getName()),
- helper.getDropJdbcFileName(bundle.getName()));
- }
+ LOG.log(DEBUG,
+ () -> "Names of the files to be used for create is: " + helper.getCreateJdbcFileName(bundle.getName())
+ + ", and for drop is: " + helper.getDropJdbcFileName(bundle.getName()) + ".");
if (createTables) {
helper.createOrDropTablesInDB(true, "CMP"); // NOI18N
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPTemplates.properties b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPTemplates.properties
index 2e5d4b9f45d..d2c7b3f16e2 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPTemplates.properties
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/CMPTemplates.properties
@@ -118,7 +118,7 @@ ejbFindByPrimaryKey=\
\t\tkey, _jdoBeanName, ex);\n\
} catch (com.sun.jdo.api.persistence.support.JDOException ex) {\n\
\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.WARNING, _jdoBeanName, ex);\n\
+ \t\tjava.lang.System.Logger.Level.WARNING, _jdoBeanName, ex);\n\
\tthrow ex;\n\
} finally {\n\
\tjdoReleasePersistenceManager0(_jdoPersistenceManager);\n\
@@ -547,7 +547,7 @@ ejbSingleFinderBody = \
\t\t'}'\n\
\t\tFinderException ex = new FinderException(msg);\n\
\t\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.FINE, _jdoBeanName, ex);\n\
+ \t\t\tjava.lang.System.Logger.Level.DEBUG, _jdoBeanName, ex);\n\
\t\tthrow ex;\n\
\t'}' \n\
\tif (result.size() < 1) '{' \n\
@@ -559,7 +559,7 @@ ejbSingleFinderBody = \
\t\t'}'\n\
\t\tObjectNotFoundException ex = new ObjectNotFoundException(msg);\n\
\t\tcom.sun.jdo.spi.persistence.support.ejb.cmp.CMPBeanHelper.logFinderException(\n\
- \t\t\tcom.sun.jdo.spi.persistence.utility.logging.Logger.FINER, _jdoBeanName, ex);\n\
+ \t\t\tjava.lang.System.Logger.Level.DEBUG, _jdoBeanName, ex);\n\
\t\tthrow ex;\n\
\t'}'\n\
\trs = ({1}){2}_JDOHelper.getHelperInstance().convertPCToPrimaryKey(result.iterator().next(), _jdoPersistenceManager);\n\
diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EJBBundleInfoHelper.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EJBBundleInfoHelper.java
index 9079a5be5eb..14c1e715592 100644
--- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EJBBundleInfoHelper.java
+++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EJBBundleInfoHelper.java
@@ -1,4 +1,5 @@
/*
+ * Copyright (c) 2026 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
@@ -14,12 +15,6 @@
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
-/*
- * EJBBundleInfoHelper.java
- *
- * Created on October 15, 2004, 1:51 PM
- */
-
package com.sun.jdo.spi.persistence.support.ejb.ejbc;
import com.sun.jdo.api.persistence.mapping.ejb.AbstractNameMapper;
@@ -43,14 +38,14 @@
/** This is a class which implements the EJBInfoHelper interface
* based on EjbBundleDescriptor and other DOL classes.
*
- * @author Rochelle Raccah
+ * @author Rochelle Raccah 2004
*/
public class EJBBundleInfoHelper implements EJBInfoHelper {
- private static final char UNDERLINE = '_'; // NOI18N
- private static final char DOT = '.'; // NOI18N
+ private static final char UNDERLINE = '_';
+ private static final char DOT = '.';
private final EjbBundleDescriptorImpl bundleDescriptor;
- private Collection availableSchemaNames;
+ private Collection availableSchemaNames;
private NameMapper nameMapper; // standard one
private Model model;
@@ -60,8 +55,7 @@ public class EJBBundleInfoHelper implements EJBInfoHelper {
* @param availableSchemaNames a Collection of available schemas
* in the application - used only during development
*/
- public EJBBundleInfoHelper(EjbBundleDescriptorImpl bundleDescriptor,
- Collection availableSchemaNames) {
+ public EJBBundleInfoHelper(EjbBundleDescriptorImpl bundleDescriptor, Collection availableSchemaNames) {
this(bundleDescriptor, null, null, availableSchemaNames);
}
@@ -79,7 +73,7 @@ public EJBBundleInfoHelper(EjbBundleDescriptorImpl bundleDescriptor,
*/
EJBBundleInfoHelper(EjbBundleDescriptorImpl bundleDescriptor,
NameMapper nameMapper, Model model,
- Collection availableSchemaNames) {
+ Collection availableSchemaNames) {
this.bundleDescriptor = bundleDescriptor;
this.nameMapper = nameMapper;
this.model = model;
@@ -98,6 +92,7 @@ private EjbBundleDescriptorImpl getBundleDescriptor() {
/**
* @see EJBInfoHelper#getEjbJarDisplayName
*/
+ @Override
public String getEjbJarDisplayName() {
return bundleDescriptor.getName();
}
@@ -107,7 +102,8 @@ public String getEjbJarDisplayName() {
* the constructor or null if there was none supplied.
* @return a collection schema names
*/
- public Collection getAvailableSchemaNames () {
+ @Override
+ public Collection getAvailableSchemaNames () {
return availableSchemaNames;
}
@@ -115,6 +111,7 @@ public Collection getAvailableSchemaNames () {
* uses a combo of app name, module name, etc.
* @return the name to use for schema generation
*/
+ @Override
public String getSchemaNameToGenerate() {
// make sure there is no '.' in schema name
return DeploymentHelper.getDDLNamePrefix(
@@ -127,6 +124,7 @@ public String getSchemaNameToGenerate() {
* @param schemaName the name of the schema to be loaded
* @return the schema object
*/
+ @Override
public SchemaElement getSchema(String schemaName) {
return SchemaElement.forName(schemaName, getClassLoader());
}
@@ -134,15 +132,17 @@ public SchemaElement getSchema(String schemaName) {
/**
* @see EJBInfoHelper#getEjbNames
*/
- public Collection getEjbNames() {
- Iterator iterator = getBundleDescriptor().getEjbs().iterator();
- ArrayList returnList = new ArrayList();
+ @Override
+ public Collection getEjbNames() {
+ Iterator iterator = getBundleDescriptor().getEjbs().iterator();
+ ArrayList returnList = new ArrayList<>();
while (iterator.hasNext()) {
- EjbDescriptor ejb = (EjbDescriptor)iterator.next();
+ EjbDescriptor ejb = iterator.next();
- if (ejb instanceof EjbCMPEntityDescriptor)
+ if (ejb instanceof EjbCMPEntityDescriptor) {
returnList.add(ejb.getName());
+ }
}
return returnList;
@@ -151,12 +151,14 @@ public Collection getEjbNames() {
/**
* @see EJBInfoHelper#getFieldsForEjb
*/
- public Collection getFieldsForEjb(String ejbName) {
- Iterator iterator = getModel().getFields(ejbName).iterator();
- ArrayList returnList = new ArrayList();
+ @Override
+ public Collection