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[] 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 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 dynamicClass = (Class) 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 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 _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 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 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 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 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 getFieldsForEjb(String ejbName) { + Iterator iterator = getModel().getFields(ejbName).iterator(); + ArrayList returnList = new ArrayList<>(); - while (iterator.hasNext()) + while (iterator.hasNext()) { returnList.add(iterator.next()); + } return returnList; } @@ -164,9 +166,10 @@ public Collection getFieldsForEjb(String ejbName) { /** * @see EJBInfoHelper#getRelationshipsForEjb */ - public Collection getRelationshipsForEjb(String ejbName) { - Iterator iterator = getBundleDescriptor().getRelationships().iterator(); - ArrayList returnList = new ArrayList(); + @Override + public Collection getRelationshipsForEjb(String ejbName) { + Iterator iterator = getBundleDescriptor().getRelationships().iterator(); + ArrayList returnList = new ArrayList<>(); // TODO: issue of usage of this - several iterations of this if // iterating all the bean - but, I think it can change, so can't @@ -174,21 +177,23 @@ public Collection getRelationshipsForEjb(String ejbName) { // getFieldsForEjb) while (iterator.hasNext()) { RelationshipDescriptor relD = - (RelationshipDescriptor)iterator.next(); + iterator.next(); RelationRoleDescriptor testRole = relD.getSource(); String cmrField = null; if (ejbName.equals(testRole.getOwner().getName())) { cmrField = testRole.getCMRField(); - if (cmrField != null) + if (cmrField != null) { returnList.add(cmrField); + } } testRole = relD.getSink(); if (ejbName.equals(testRole.getOwner().getName())) { cmrField = testRole.getCMRField(); - if (cmrField != null) + if (cmrField != null) { returnList.add(cmrField); + } } } @@ -198,6 +203,7 @@ public Collection getRelationshipsForEjb(String ejbName) { /** Gets the class loader which corresponds to this ejb bundle. * @return the class loader which corresponds to this ejb bundle */ + @Override public ClassLoader getClassLoader() { return bundleDescriptor.getClassLoader(); } @@ -205,6 +211,7 @@ public ClassLoader getClassLoader() { /** * @see EJBInfoHelper#getNameMapper */ + @Override public AbstractNameMapper getNameMapper() { return getNameMapperInternal(); } @@ -212,13 +219,15 @@ public AbstractNameMapper getNameMapper() { /** * @see EJBInfoHelper#createUniqueNameMapper */ + @Override public AbstractNameMapper createUniqueNameMapper() { return new NameMapper(bundleDescriptor); } private NameMapper getNameMapperInternal() { - if (nameMapper == null) + if (nameMapper == null) { nameMapper = new NameMapper(bundleDescriptor, false); + } return nameMapper; } @@ -226,6 +235,7 @@ private NameMapper getNameMapperInternal() { /** * @see EJBInfoHelper#createConversionHelper */ + @Override public ConversionHelper createConversionHelper() { return new EjbConversionHelper(getNameMapperInternal()); } @@ -233,6 +243,7 @@ public ConversionHelper createConversionHelper() { /** * @see EJBInfoHelper#getModel */ + @Override public Model getModel() { if (model == null) { model = new DeploymentDescriptorModel(getNameMapperInternal(), diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EjbConversionHelper.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EjbConversionHelper.java index cf3092010fa..704e0fc6752 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EjbConversionHelper.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/EjbConversionHelper.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,14 +15,9 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * EjbConversionHelper.java - * - * Created on March 19, 2002 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; +import com.sun.jdo.api.persistence.mapping.ejb.AbstractNameMapper; import com.sun.jdo.api.persistence.mapping.ejb.ConversionHelper; import com.sun.jdo.spi.persistence.support.ejb.model.util.NameMapper; @@ -33,6 +29,7 @@ import java.util.Set; import org.glassfish.ejb.deployment.descriptor.EjbBundleDescriptorImpl; +import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; import org.glassfish.ejb.deployment.descriptor.IASEjbCMPEntityDescriptor; import org.glassfish.ejb.deployment.descriptor.PersistenceDescriptor; import org.glassfish.ejb.deployment.descriptor.PersistentFieldInfo; @@ -43,17 +40,17 @@ * This class implements ConversionHelper interface by using data from * IASEjbBundleDescriptor. * - * @author Shing Wai Chan + * @author Shing Wai Chan 2002 */ public class EjbConversionHelper implements ConversionHelper { private NameMapper nameMapper = null; private EjbBundleDescriptorImpl bundle = null; - private HashMap ejbDescMap = new HashMap(); - private HashMap ejbFieldMap = new HashMap(); - private HashMap ejbKeyMap = new HashMap(); - private HashMap ejbPerDescMap = new HashMap(); - private HashMap ejbRelMap = new HashMap(); + private HashMap ejbDescMap = new HashMap<>(); + private HashMap> ejbFieldMap = new HashMap<>(); + private HashMap> ejbKeyMap = new HashMap<>(); + private HashMap ejbPerDescMap = new HashMap<>(); + private HashMap> ejbRelMap = new HashMap<>(); boolean generateFields = true; boolean ensureValidation = true; @@ -61,7 +58,7 @@ public EjbConversionHelper(NameMapper nameMapper) { this.nameMapper = nameMapper; this.bundle = nameMapper.getBundleDescriptor(); - Iterator iter = bundle.getEjbs().iterator(); + Iterator iter = bundle.getEjbs().iterator(); while (iter.hasNext()) { Object desc = iter.next(); if (desc instanceof IASEjbCMPEntityDescriptor) { @@ -77,28 +74,28 @@ public EjbConversionHelper(NameMapper nameMapper) { ejbPerDescMap.put(ejbName, pers); //collect pers fields - Collection pFields = ejbDesc.getPersistentFields(); - HashMap fieldMap = new HashMap(); - Iterator fIter = pFields.iterator(); + Collection pFields = ejbDesc.getPersistentFields(); + HashMap fieldMap = new HashMap<>(); + Iterator fIter = pFields.iterator(); while (fIter.hasNext()) { - String fieldName = ((PersistentFieldInfo)fIter.next()).name; + String fieldName = fIter.next().name; fieldMap.put(fieldName, fieldName); } ejbFieldMap.put(ejbName, fieldMap); //collect pseudo cmr fields - List pseudoFields = nameMapper.getGeneratedRelationshipsForEjbName(ejbName); - Iterator pIter = pseudoFields.iterator(); + List pseudoFields = nameMapper.getGeneratedRelationshipsForEjbName(ejbName); + Iterator pIter = pseudoFields.iterator(); while (pIter.hasNext()) { - addField(ejbName, (String)pIter.next()); + addField(ejbName, pIter.next()); } //collect all keys - Collection pKeys = ejbDesc.getPrimaryKeyFields(); - HashMap pKeyMap = new HashMap(); - Iterator kIter = pKeys.iterator(); + Collection pKeys = ejbDesc.getPrimaryKeyFields(); + HashMap pKeyMap = new HashMap<>(); + Iterator kIter = pKeys.iterator(); while (kIter.hasNext()) { - String fieldName = ((PersistentFieldInfo)kIter.next()).name; + String fieldName = kIter.next().name; pKeyMap.put(fieldName, fieldName); } ejbKeyMap.put(ejbName, pKeyMap); @@ -106,18 +103,18 @@ public EjbConversionHelper(NameMapper nameMapper) { } //collect relationship - Set rels = bundle.getRelationships(); - Iterator relIter = rels.iterator(); + Set rels = bundle.getRelationships(); + Iterator relIter = rels.iterator(); while (relIter.hasNext()) { - RelationshipDescriptor rel = (RelationshipDescriptor)relIter.next(); + RelationshipDescriptor rel = relIter.next(); RelationRoleDescriptor source = rel.getSource(); RelationRoleDescriptor sink = rel.getSink(); //collect source RelationshipDescriptor String sourceEjbName = source.getOwner().getName(); - ArrayList sourceRels = (ArrayList)ejbRelMap.get(sourceEjbName); + ArrayList sourceRels = ejbRelMap.get(sourceEjbName); if (sourceRels == null) { - sourceRels = new ArrayList(); + sourceRels = new ArrayList<>(); ejbRelMap.put(sourceEjbName, sourceRels); } sourceRels.add(rel); @@ -130,9 +127,9 @@ public EjbConversionHelper(NameMapper nameMapper) { //collect sink RelationshipDescriptor String sinkEjbName = sink.getOwner().getName(); - ArrayList sinkRels = (ArrayList)ejbRelMap.get(sinkEjbName); + ArrayList sinkRels = ejbRelMap.get(sinkEjbName); if (sinkRels == null) { - sinkRels = new ArrayList(); + sinkRels = new ArrayList<>(); ejbRelMap.put(sinkEjbName, sinkRels); } sinkRels.add(rel); @@ -147,6 +144,7 @@ public EjbConversionHelper(NameMapper nameMapper) { //---- implements interface ConversionHelper ---- + @Override public String getMappedClassName(String ejbName) { return nameMapper.getPersistenceClassForEjbName(ejbName); } @@ -160,14 +158,13 @@ public String getMappedClassName(String ejbName) { * @return true if the bean contains the field, otherwise * return false */ + @Override public boolean hasField(String ejbName, String fieldName) { - if (!generateFields && isGeneratedRelationship(ejbName, fieldName)) - return false; - else { - HashMap fieldMap = (HashMap)ejbFieldMap.get(ejbName); - return (fieldMap != null) ? - (fieldMap.get(fieldName) != null) : false; + if (generateFields || !isGeneratedRelationship(ejbName, fieldName)) { + HashMap fieldMap = ejbFieldMap.get(ejbName); + return fieldMap == null ? false : fieldMap.get(fieldName) != null; } + return false; } /** @@ -177,10 +174,11 @@ public boolean hasField(String ejbName, String fieldName) { * @param ejbName The ejb-name element for the bean * @return an array of fields in the ejb bean */ + @Override public Object[] getFields(String ejbName) { - HashMap fieldMap = (HashMap)ejbFieldMap.get(ejbName); + HashMap fieldMap = ejbFieldMap.get(ejbName); if (fieldMap != null) { - List fields = new ArrayList(fieldMap.keySet()); + ArrayList fields = new ArrayList<>(fieldMap.keySet()); if (!generateFields) { fields.removeAll(getGeneratedRelationships(ejbName)); } @@ -192,8 +190,9 @@ public Object[] getFields(String ejbName) { /** * The boolean argument candidate is ignored in this case. */ + @Override public boolean isKey(String ejbName, String fieldName, boolean candidate) { - HashMap keyMap = (HashMap)ejbKeyMap.get(ejbName); + HashMap keyMap = ejbKeyMap.get(ejbName); return (keyMap != null) ? (keyMap.get(fieldName) != null) : false; } @@ -201,12 +200,13 @@ public boolean isKey(String ejbName, String fieldName, boolean candidate) { * This API will only be called from MappingFile when multiplicity is Many * on the other role. */ + @Override public String getRelationshipFieldType(String ejbName, String fieldName) { if (isGeneratedRelationship(ejbName, fieldName)) { return java.util.Collection.class.getName(); } else { PersistenceDescriptor pers = - (PersistenceDescriptor)ejbPerDescMap.get(ejbName); + ejbPerDescMap.get(ejbName); return pers.getCMRFieldReturnType(fieldName); } } @@ -215,12 +215,14 @@ public String getRelationshipFieldType(String ejbName, String fieldName) { * getMultiplicity of the other role on the relationship * Please note that multiplicity is JDO style */ + @Override public String getMultiplicity(String ejbName, String fieldName) { RelationRoleDescriptor oppRole = getRelationRoleDescriptor(ejbName, fieldName, false); return (oppRole.getIsMany()) ? MANY : ONE; } + @Override public String getRelationshipFieldContent(String ejbName, String fieldName) { RelationRoleDescriptor oppRole = getRelationRoleDescriptor(ejbName, fieldName, false); @@ -230,15 +232,17 @@ public String getRelationshipFieldContent(String ejbName, String fieldName) { /** * This method return the fieldName of relation role on the other end. */ + @Override public String getInverseFieldName(String ejbName, String fieldName) { RelationRoleDescriptor oppRole = getRelationRoleDescriptor(ejbName, fieldName, false); String inverseName = oppRole.getCMRField(); // if we are generating relationships, check for a generated inverse - if ((generateFields) && (inverseName == null)) + if ((generateFields) && (inverseName == null)) { inverseName = nameMapper.getGeneratedFieldForEjbField( ejbName, fieldName)[1]; + } return inverseName; } @@ -251,9 +255,10 @@ public String getInverseFieldName(String ejbName, String fieldName) { * @return true to apply the default unknown PK Class Strategy, * false otherwise */ + @Override public boolean applyDefaultUnknownPKClassStrategy(String ejbName) { IASEjbCMPEntityDescriptor ejbDesc = - (IASEjbCMPEntityDescriptor)ejbDescMap.get(ejbName); + ejbDescMap.get(ejbName); String keyClassName = ejbDesc.getPrimaryKeyClassName(); return keyClassName != null && keyClassName.equals(Object.class.getName()); @@ -263,18 +268,21 @@ public boolean applyDefaultUnknownPKClassStrategy(String ejbName) { * Returns the name used for generated primary key fields. * @return a string for key field name */ + @Override public String getGeneratedPKFieldName() { - return nameMapper.GENERATED_KEY_FIELD_NAME; + return AbstractNameMapper.GENERATED_KEY_FIELD_NAME; } /** * Returns the prefix used for generated version fields. * @return a string for version field name prefix */ + @Override public String getGeneratedVersionFieldNamePrefix() { - return nameMapper.GENERATED_VERSION_FIELD_PREFIX; + return AbstractNameMapper.GENERATED_VERSION_FIELD_PREFIX; } + @Override public boolean relatedObjectsAreDeleted(String beanName, String fieldName) { RelationRoleDescriptor oppRole = getRelationRoleDescriptor(beanName, fieldName, false); return oppRole.getCascadeDelete(); @@ -288,6 +296,7 @@ public boolean relatedObjectsAreDeleted(String beanName, String fieldName) { * @return true to generate fields in the dot-mapping file * (if they are not present). */ + @Override public boolean generateFields() { return generateFields; } @@ -298,6 +307,7 @@ public boolean generateFields() { * @param generateFields a flag which indicates whether fields should be * generated */ + @Override public void setGenerateFields(boolean generateFields) { this.generateFields = generateFields; } @@ -307,6 +317,7 @@ public void setGenerateFields(boolean generateFields) { * @return true to validate all the fields in the dot-mapping * file. */ + @Override public boolean ensureValidation() { return ensureValidation; } @@ -316,6 +327,7 @@ public boolean ensureValidation() { * against schema columns. * @param isValidating a boolean of indicating validating fields or not */ + @Override public void setEnsureValidation(boolean isValidating) { ensureValidation = isValidating; } @@ -330,10 +342,12 @@ public void setEnsureValidation(boolean isValidating) { * otherwise. */ + @Override public boolean isGeneratedField(String ejbName, String fieldName) { return nameMapper.isGeneratedField(ejbName, fieldName); } + @Override public boolean isGeneratedRelationship(String ejbName, String fieldName) { return nameMapper.isGeneratedEjbRelationship(ejbName, fieldName); } @@ -343,7 +357,8 @@ public boolean isGeneratedRelationship(String ejbName, String fieldName) { * @param ejbName The ejb-name element for the bean * @return a list of generated relationship field names */ - public List getGeneratedRelationships(String ejbName) { + @Override + public List getGeneratedRelationships(String ejbName) { return nameMapper.getGeneratedRelationshipsForEjbName(ejbName); } @@ -366,9 +381,9 @@ private RelationRoleDescriptor getRelationRoleDescriptor(String ejbName, private RelationRoleDescriptor getRealRelationRoleDescriptor( String ejbName, String cmrFieldName, boolean self) { - ArrayList rels = (ArrayList)ejbRelMap.get(ejbName); + ArrayList rels = ejbRelMap.get(ejbName); for (int i = 0; i < rels.size(); i++) { - RelationshipDescriptor rel = (RelationshipDescriptor)rels.get(i); + RelationshipDescriptor rel = rels.get(i); RelationRoleDescriptor source = rel.getSource(); RelationRoleDescriptor sink = rel.getSink(); if (ejbName.equals(source.getOwner().getName()) && @@ -383,9 +398,9 @@ private RelationRoleDescriptor getRealRelationRoleDescriptor( } private void addField(String ejbName, String fieldName) { - HashMap fieldMap = (HashMap)ejbFieldMap.get(ejbName); + HashMap fieldMap = ejbFieldMap.get(ejbName); if (fieldMap == null) { - fieldMap = new HashMap(); + fieldMap = new HashMap<>(); ejbFieldMap.put(ejbName, fieldMap); } fieldMap.put(fieldName, fieldName); diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOCodeGenerator.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOCodeGenerator.java index 9ed24f09fd5..13dc733d27e 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOCodeGenerator.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOCodeGenerator.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 */ -/* - * JDOCodeGenerator.java - * - * Created on November 14, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; import com.sun.enterprise.deployment.Application; @@ -40,13 +35,13 @@ import com.sun.jdo.spi.persistence.support.sqlstore.ejb.DeploymentHelper; import com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.JDOQLParameterDeclarationParser; import com.sun.jdo.spi.persistence.utility.MergedBundle; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; @@ -65,25 +60,26 @@ import org.netbeans.modules.dbschema.SchemaElement; import org.netbeans.modules.schema2beans.Schema2BeansException; -//import com.sun.enterprise.deployment.backend.Deployer; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.WARNING; -/* +/** * This is the JDO specific generator for the concrete CMP beans and any * other dependent files. * - * @author Marina Vatkina + * @author Marina Vatkina 2001 */ public class JDOCodeGenerator implements CMPGenerator, DatabaseConstants { /** * Signature with CVS keyword substitution for identifying the generated code */ - public static final String SIGNATURE = "$RCSfile: JDOCodeGenerator.java,v $ $Revision: 1.7 $"; //NOI18N + public static final String SIGNATURE = "$RCSfile: JDOCodeGenerator.java,v $ $Revision: 1.7 $"; - private static final String MAPPING_EXTENSION = ".mapping"; // NOI18N + private static final String MAPPING_EXTENSION = ".mapping"; /** The logger */ - private static final Logger logger = LogHelperEJBCompiler.getLogger(); + private static final Logger LOG = System.getLogger(JDOCodeGenerator.class.getName()); /** The resource bundle used for validation */ private static final ResourceBundle validationBundle = new MergedBundle( @@ -119,12 +115,12 @@ public class JDOCodeGenerator implements CMPGenerator, DatabaseConstants { /** * @see CMPGenerator#init(org.glassfish.ejb.deployment.descriptor.EjbBundleDescriptorImpl, DeploymentContext, String, String) */ + @Override public void init(EjbBundleDescriptorImpl bundle, DeploymentContext ctx, String bundlePathName, String generatedXmlsPathName) throws GeneratorException { - if (logger.isLoggable(Logger.FINE)) - logger.fine("cmp gen init"); // NOI18N + LOG.log(DEBUG, () -> "cmp gen init"); this.ctx = ctx; this.generatedXmlsPath = generatedXmlsPathName; @@ -143,6 +139,8 @@ public void init(EjbBundleDescriptorImpl bundle, DeploymentContext ctx, * * @deprecated */ + @Deprecated + @Override public void init(EjbBundleDescriptorImpl bundle, ClassLoader loader, String bundlePathName) throws GeneratorException { @@ -160,8 +158,7 @@ public void init(EjbBundleDescriptorImpl bundle, ClassLoader loader, public void init(EjbBundleDescriptorImpl bundle, ClassLoader loader, String bundlePathName, boolean ignoreSunDeploymentDescriptors) throws GeneratorException { - if (logger.isLoggable(Logger.FINE)) - logger.fine("cmp gen init"); // NOI18N + LOG.log(DEBUG, "cmp gen init"); this.bundle = bundle; this.loader = loader; @@ -179,27 +176,28 @@ public void init(EjbBundleDescriptorImpl bundle, ClassLoader loader, } catch (IOException e) { // Problems storing properties file(s) throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.IOExceptionInInit", bundle, e); //NOI18N + "CMG.IOExceptionInInit", bundle, e); } } /** * @see CMPGenerator#validate(IASEjbCMPEntityDescriptor descr) */ - public Collection validate(IASEjbCMPEntityDescriptor descr) { + @Override + public Collection validate(IASEjbCMPEntityDescriptor descr) { - Collection c = new ArrayList(); + Collection c = new ArrayList<>(); c.addAll(validateModel(descr)); // only do EJBQL validation if the mapping info is present - if (getMappingMissingException(c) == null) + if (getMappingMissingException(c) == null) { c.addAll(validateEJB(descr)); + } - if (logger.isLoggable(Logger.FINE)) { - for (Iterator i = c.iterator(); i.hasNext();) { - logger.log(Logger.FINE, "validation exception: ", //NOI18N - (Exception)i.next()); + if (LOG.isLoggable(DEBUG)) { + for (Iterator i = c.iterator(); i.hasNext();) { + LOG.log(DEBUG, "validation exception: ", i.next()); } } @@ -221,17 +219,17 @@ public Collection validate(IASEjbCMPEntityDescriptor descr) { * totally missing or Collection of ModelException instances * for each found validation error. */ - private Collection validateModel(IASEjbCMPEntityDescriptor descr) { + private Collection validateModel(IASEjbCMPEntityDescriptor descr) { String beanName = descr.getName(); String className = nameMapper.getPersistenceClassForEjbName(beanName); if (model.getPersistenceClass(className) == null) { return Collections.singletonList( JDOCodeGeneratorHelper.createGeneratorException( - "CMG.MissingBeanMapping", beanName, bundle)); //NOI18N + "CMG.MissingBeanMapping", beanName, bundle)); } - return model.validate(className, loader, validationBundle); + return new ArrayList<>(model.validate(className, loader, validationBundle)); } /** @@ -246,12 +244,13 @@ private Collection validateModel(IASEjbCMPEntityDescriptor descr) { * @return if the collection contains exactly one GeneratorException * return it, otherwise return null */ - private GeneratorException getMappingMissingException(Collection c) { + private GeneratorException getMappingMissingException(Collection c) { if (c.size() == 1) { Object firstElement = c.iterator().next(); - if (firstElement instanceof GeneratorException) + if (firstElement instanceof GeneratorException) { return (GeneratorException)firstElement; + } } return null; @@ -265,13 +264,13 @@ private GeneratorException getMappingMissingException(Collection c) { * @return a Collection of Exception instances for each found * validation error. */ - private Collection validateEJB(IASEjbCMPEntityDescriptor descr) { - Collection c = null; + private Collection validateEJB(IASEjbCMPEntityDescriptor descr) { + Collection c = null; try { JDOConcreteBeanGenerator cmpGenerator = getCMPGenerator(descr); c = cmpGenerator.validate(new MethodHelper(descr), descr.getName()); } catch (GeneratorException e) { - c = new ArrayList(); + c = new ArrayList<>(); c.add(e); } @@ -285,8 +284,8 @@ private Collection validateEJB(IASEjbCMPEntityDescriptor descr) { * @return a Collection of Exception instances for each found * validation error. */ - private Collection validateSupported(IASEjbCMPEntityDescriptor descr) { - Collection rc = new ArrayList(); + private Collection validateSupported(IASEjbCMPEntityDescriptor descr) { + Collection rc = new ArrayList<>(); /* * XXX Add validation of read-only configuration? */ @@ -297,9 +296,8 @@ private Collection validateSupported(IASEjbCMPEntityDescriptor descr) { /** * @see CMPGenerator#generate(IASEjbCMPEntityDescriptor, File, File) */ - public void generate(IASEjbCMPEntityDescriptor ejbcmp, File srcout, - File classout) - throws GeneratorException { + @Override + public void generate(IASEjbCMPEntityDescriptor ejbcmp, File srcout, File classout) throws GeneratorException { String beanName = ejbcmp.getName(); @@ -307,21 +305,20 @@ public void generate(IASEjbCMPEntityDescriptor ejbcmp, File srcout, // If there are no validation exceptions, the reference will be null. StringBuffer validateex = null; - boolean debug = logger.isLoggable(Logger.FINE); - if (debug) - logger.fine("gen file in " + srcout.getAbsolutePath()); // NOI18N + LOG.log(DEBUG, () -> "gen file in " + srcout.getAbsolutePath()); // We need to create a new ArrayList because model validation // returns an unmodifiable list. This may be a place to look // for a performance improvement later for the case of empty // or singleton collection (extra copies). - Collection c = new ArrayList(validateModel(ejbcmp)); + Collection c = new ArrayList<>(validateModel(ejbcmp)); // if the mapping info is not present, throw the exception and // stop the generation process GeneratorException mappingMissingEx = getMappingMissingException(c); - if (mappingMissingEx != null) + if (mappingMissingEx != null) { throw mappingMissingEx; + } c.addAll(validateSupported(ejbcmp)); @@ -334,26 +331,27 @@ public void generate(IASEjbCMPEntityDescriptor ejbcmp, File srcout, // exceptions in a concatenated message and a GeneratorException // is thrown. validateex = new StringBuffer(); - Iterator iter = c.iterator(); + Iterator iter = c.iterator(); while (iter.hasNext()) { - Exception ex = (Exception)iter.next(); - if (debug) - logger.log(Logger.FINE,"validation exception: " , ex); //NOI18N - validateex.append(ex.getMessage()).append('\n'); //NOI18N + Exception ex = iter.next(); + LOG.log(DEBUG, "validation exception: " , ex); + validateex.append(ex.getMessage()).append('\n'); } - if (!ignoreValidationResults) + if (!ignoreValidationResults) { throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.ExceptionInValidate", //NOI18N + "CMG.ExceptionInValidate", beanName, bundle, validateex.toString()); + } } try { Collection newfiles = null; - if (!ejbcmp.isEJB20()) + if (!ejbcmp.isEJB20()) { ejbcmp.setQueryParser(jdoqlParamDeclParser); + } // IMPORTANT: // Concrete impl class generation must happen before generation of @@ -365,29 +363,30 @@ public void generate(IASEjbCMPEntityDescriptor ejbcmp, File srcout, newfiles = generatePC(ejbcmp, srcout, classout); files.addAll(newfiles); - if (validateex != null) + if (validateex != null) { throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.ExceptionInValidate", //NOI18N + "CMG.ExceptionInValidate", beanName, bundle, validateex.toString()); + } } catch (JDOUserException e) { // User error found. Append this exception's message to validation // messages if there are any. throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.ExceptionInGenerate", //NOI18N + "CMG.ExceptionInGenerate", beanName, bundle, e, validateex); } catch (EJBQLException e) { // EJBQL parsing error found. Append this exception's message to // validation messages if there are any. throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.ExceptionInGenerate", //NOI18N + "CMG.ExceptionInGenerate", beanName, bundle, e, validateex); } catch (IOException e) { // Problems generating file(s). Append this exception's message to // validation messages if there are any. throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.IOExceptionInGenerate", //NOI18N + "CMG.IOExceptionInGenerate", beanName, bundle, e, validateex); } @@ -416,9 +415,9 @@ private Collection generatePC(IASEjbCMPEntityDescriptor ejbcmp, MappingClassElement mappingClass = model.getMappingClass(className); BufferedOutputStream mapOut = null; + String mapPath = className.replace('.', File.separatorChar); + String mappingFile = mapPath + MAPPING_EXTENSION; try { - String mapPath = className.replace('.', File.separatorChar); - String mappingFile = mapPath + MAPPING_EXTENSION; mapOut = new BufferedOutputStream( new FileOutputStream(new File(classout, mappingFile))); //"touch" need to create the output stream first since the @@ -430,8 +429,7 @@ private Collection generatePC(IASEjbCMPEntityDescriptor ejbcmp, try { mapOut.close(); } catch(Exception ex) { - if (logger.isLoggable(Logger.FINE)) - logger.fine(ex.getMessage()); + LOG.log(DEBUG, "Failed to close the output mapping file " + mappingFile, ex); } } } @@ -443,7 +441,8 @@ private Collection generatePC(IASEjbCMPEntityDescriptor ejbcmp, /* * @see CMPGenerator#cleanup() */ - public Collection cleanup() throws GeneratorException { + @Override + public Collection cleanup() throws GeneratorException { // Remove the strong references to MappingClassElements // needed during deployment. The mapping class cache // can now be cleaned up by the garbage collector. @@ -478,7 +477,7 @@ private JDOConcreteBeanGenerator getCMPGenerator( } catch (IOException e) { // Problems reading file(s) throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.IOExceptionInInit", bundle, e); //NOI18N + "CMG.IOExceptionInInit", bundle, e); } return cmpGenerator; @@ -610,36 +609,27 @@ private void loadOrCreateMappingClasses(boolean ignoreSunDeploymentDescriptors) throws IOException, GeneratorException { try { - SchemaElement schema = mappingGenerator.generateMapping( - ctx, inputFilesPath, generatedXmlsPath, classout, - ignoreSunDeploymentDescriptors); + SchemaElement schema = mappingGenerator.generateMapping(ctx, inputFilesPath, generatedXmlsPath, classout, + ignoreSunDeploymentDescriptors); // If this is from verify, do not create DDL. - if (ctx != null - && mappingGenerator.isJavaToDatabase()) { + if (ctx != null && mappingGenerator.isJavaToDatabase()) { createDDLs(schema, mappingGenerator.getDatabaseVendorName(), null); } } catch (SQLException ex) { // Problems talking to the database. - throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.SQLException", bundle, ex); + throw JDOCodeGeneratorHelper.createGeneratorException("CMG.SQLException", bundle, ex); } catch (DBException ex) { // Problems reading or creating DBModel. - throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.DBException", bundle, ex); //NOI18N - + throw JDOCodeGeneratorHelper.createGeneratorException("CMG.DBException", bundle, ex); } catch (ModelException ex) { // Problems reading or creating model. - throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.ModelException", bundle, ex); //NOI18N - + throw JDOCodeGeneratorHelper.createGeneratorException("CMG.ModelException", bundle, ex); } catch (Schema2BeansException ex) { // Problems reading or creating sun-cmp-mapping.xml - throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.Schema2BeansException", bundle, ex); //NOI18N + throw JDOCodeGeneratorHelper.createGeneratorException("CMG.Schema2BeansException", bundle, ex); } catch (ConversionException ex) { // Problems converting between sun-cmp-mappings and mapping model - throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.MappingConversionException", bundle, ex); //NOI18N + throw JDOCodeGeneratorHelper.createGeneratorException("CMG.MappingConversionException", bundle, ex); } } @@ -695,8 +685,7 @@ private void createDDLs(SchemaElement schema, String dbVendorName, Connection co DDLGenerator.generateDDL(schema, dbVendorName, createDDLSql, dropDDLSql, dropDDLTxt, createDDLTxt, dbStream, dropTablesAtDeploy); } catch (SQLException ex) { - if (logger.isLoggable(Logger.WARNING)) - logger.warning(ex.toString()); + LOG.log(WARNING, "Failed to generate DDL to directory " + fileDir, ex); } } diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBean20Generator.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBean20Generator.java index 407b7652a6e..f9ef2e7931f 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBean20Generator.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBean20Generator.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 */ -/* - * JDOConcreteBean20Generator.java - * - * Created on February 24, 2004 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; import com.sun.jdo.api.persistence.model.Model; @@ -31,10 +26,12 @@ import com.sun.jdo.spi.persistence.support.ejb.ejbqlc.EJBQLException; import com.sun.jdo.spi.persistence.support.ejb.ejbqlc.JDOQLElements; import com.sun.jdo.spi.persistence.support.ejb.model.util.NameMapper; +import com.sun.jdo.spi.persistence.utility.JavaTypeHelper; +import com.sun.jdo.spi.persistence.utility.generator.JavaClassWriterHelper; import com.sun.jdo.spi.persistence.utility.generator.JavaFileWriter; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.IOException; +import java.lang.System.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.MessageFormat; @@ -46,6 +43,10 @@ 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; + /* * This is the JDO specific generator for the concrete CMP beans for EJB2.0 * @@ -53,6 +54,8 @@ */ class JDOConcreteBean20Generator extends JDOConcreteBeanGenerator { + private static final Logger LOG = System.getLogger(JDOConcreteBean20Generator.class.getName()); + // EJBQLC ejbqlc private EJBQLC ejbqlc; @@ -62,7 +65,7 @@ class JDOConcreteBean20Generator extends JDOConcreteBeanGenerator { * finder or selector and the value is JDOQLElements object * that represents EJBQL compilation results. */ - private Map jdoqlElementsMap; + private Map jdoqlElementsMap; // StringBuffer for cascade-delete operations on ejbRemove private StringBuffer cascadeDelete = null; @@ -77,7 +80,7 @@ class JDOConcreteBean20Generator extends JDOConcreteBeanGenerator { * Signature with CVS keyword substitution for identifying the generated code */ static final String SIGNATURE = - "$RCSfile: JDOConcreteBean20Generator.java,v $ $Revision: 1.2 $"; //NOI18N + "$RCSfile: JDOConcreteBean20Generator.java,v $ $Revision: 1.2 $"; JDOConcreteBean20Generator(ClassLoader loader, Model model, @@ -104,8 +107,9 @@ class JDOConcreteBean20Generator extends JDOConcreteBeanGenerator { * @return a Collection of Exception instances with a separate instance for * each failed validation. */ - Collection validate(AbstractMethodHelper methodHelper, String beanName) { - Collection rc = super.validate(methodHelper, beanName); + @Override + Collection validate(AbstractMethodHelper methodHelper, String beanName) { + Collection rc = super.validate(methodHelper, beanName); this.beanName = beanName; rc.addAll(validateEJBQL(methodHelper)); @@ -116,6 +120,7 @@ Collection validate(AbstractMethodHelper methodHelper, String beanName) { /** Add interfaces to the class declarations. */ + @Override void addInterfaces() throws IOException { super.addInterfaces(); jdoHelperWriter.addInterface(CMP20TemplateFormatter.helper20Interface_); @@ -123,12 +128,14 @@ void addInterfaces() throws IOException { /** Set super class for the helper class. */ + @Override void setHelperSuperclass() throws IOException { jdoHelperWriter.setSuperclass(CMP20TemplateFormatter.helper20Impl_); } /** Add import statements for for the generated classes. */ + @Override void addImportStatements(JavaFileWriter concreteImplFileWriter, JavaFileWriter helperFileWriter) throws IOException { @@ -139,6 +146,7 @@ void addImportStatements(JavaFileWriter concreteImplFileWriter, /** Generate CMP2.0 specific methods. */ + @Override void generateTypeSpecificMethods(PersistenceFieldElement[] allFields, AbstractMethodHelper methodHelper) throws IOException { @@ -161,7 +169,7 @@ private void generateGetSetMethods(PersistenceFieldElement[] fields) cascadeDelete = new StringBuffer(); // jdoCleanCollectionRef() body - StringBuffer cmrcleanbodyBuf = new StringBuffer(CMP20TemplateFormatter.none_); + StringBuffer cmrcleanbodyBuf = new StringBuffer(JavaClassWriterHelper.none_); for (i = 0; i < count; i++) { PersistenceFieldElement pfe = fields[i]; @@ -195,8 +203,8 @@ private void generateGetSetMethods(PersistenceFieldElement[] fields) generateCMRGetSetBodies(fieldInfo, cmrcleanbodyBuf); } else { - logger.log(Logger.WARNING, I18NHelper.getMessage(messages, - "CMG.CMRAccessNotAllowed", beanName, fieldInfo.name)); // NOI18N + LOG.log(WARNING, I18NHelper.getMessage(messages, + "CMG.CMRAccessNotAllowed", beanName, fieldInfo.name)); gbody = CMPROTemplateFormatter.accessNotAllowedTemplate; sbody = CMPROTemplateFormatter.updateNotAllowedTemplate; @@ -204,27 +212,27 @@ private void generateGetSetMethods(PersistenceFieldElement[] fields) } // Now generate getter and setter: - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( fieldInfo.getter, Modifier.PUBLIC, fieldInfo.type, - CMP20TemplateFormatter.getBodyAsStrings(gbody), + JavaClassWriterHelper.getBodyAsStrings(gbody), concreteImplWriter); oneParam[0] = fieldInfo.type; concreteImplWriter.addMethod(fieldInfo.setter, // name Modifier.PUBLIC, // modifiers - CMP20TemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames oneParam,// parameterTypes null,// exceptions - CMP20TemplateFormatter.getBodyAsStrings(sbody), // body + JavaClassWriterHelper.getBodyAsStrings(sbody), // body null);// comments } } // Now generate jdoCleanCollectionRef method - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMP20TemplateFormatter.jdoCleanCollectionRef_, - CMP20TemplateFormatter.getBodyAsStrings(cmrcleanbodyBuf.toString()), + JavaClassWriterHelper.getBodyAsStrings(cmrcleanbodyBuf.toString()), concreteImplWriter); } @@ -324,15 +332,13 @@ private void generateCMRGetSetBodies(FieldInfo fieldInfo, String otherPC = model.getRelatedClass(rel); boolean manySide = model.isCollection(fieldInfo.type); - if (logger.isLoggable(Logger.FINE)) { + if (LOG.isLoggable(DEBUG)) { RelationshipElement otherField = rel.getInverseRelationship(model); - String otherFieldName = ((otherField != null) ? - nameMapper.getEjbFieldForPersistenceField(otherPC, - otherField.getName()) : - null); + String otherFieldName = otherField != null + ? nameMapper.getEjbFieldForPersistenceField(otherPC, otherField.getName()) + : null; - logger.fine("manySide: " + manySide); // NOI18N - logger.fine("Field: " + otherFieldName); // NOI18N + LOG.log(DEBUG, "manySide: " + manySide + ", field: " + otherFieldName); } String otherEJB = nameMapper.getEjbNameForPersistenceClass(otherPC); @@ -355,7 +361,7 @@ private void generateCMRGetSetBodies(FieldInfo fieldInfo, twoParams[0] = fieldInfo.type; twoParams[1] = fieldInfo.name; - CMP20TemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMP20TemplateFormatter.cmrvformatter.format(twoParams), 0, concreteImplWriter); @@ -386,8 +392,7 @@ private void generateCMRGetSetBodies(FieldInfo fieldInfo, // Reset DeleteAction to NONE to suppress it in PM.deletePersistent(). rel.setDeleteAction(RelationshipElement.NONE_ACTION); } catch (ModelException me) { - logger.log(Logger.SEVERE, I18NHelper.getMessage(messages, - "CMG.ModelExceptionOnDeleteAction", me)); //NOI18N + LOG.log(ERROR, () -> I18NHelper.getMessage(messages, "CMG.ModelExceptionOnDeleteAction", me)); } } @@ -401,16 +406,16 @@ private void generateCMRGetSetBodies(FieldInfo fieldInfo, * all categorized methods and some other convenience methods for this bean. * @return a Collection of found exceptions. */ - private Collection validateEJBQL(AbstractMethodHelper methodHelper) { - Collection rc = new ArrayList(); - jdoqlElementsMap = new HashMap(); + private Collection validateEJBQL(AbstractMethodHelper methodHelper) { + Collection rc = new ArrayList<>(); + jdoqlElementsMap = new HashMap<>(); - List methods = new ArrayList(methodHelper.getFinders()); + List methods = new ArrayList<>(methodHelper.getFinders()); methods.addAll(methodHelper.getSelectors()); for (int i = 0; i < methods.size(); i++) { - Method m = (Method)methods.get(i); + Method m = methods.get(i); String mname = m.getName(); - if (mname.equals(CMP20TemplateFormatter.findByPrimaryKey_)) { + if (mname.equals(CMPTemplateFormatter.findByPrimaryKey_)) { // No EJBQL is defined for findByPrimaryKey. continue; } @@ -420,7 +425,7 @@ private Collection validateEJBQL(AbstractMethodHelper methodHelper) { jdoqlElementsMap.put(m, ejbqlc.compile(methodHelper.getQueryString(m), m, methodHelper.getQueryReturnType(m), - mname.startsWith(CMP20TemplateFormatter.find_), + mname.startsWith(CMPTemplateFormatter.find_), beanName)); } catch (EJBQLException e) { rc.add(e); @@ -436,15 +441,14 @@ private Collection validateEJBQL(AbstractMethodHelper methodHelper) { * all categorized methods and some other convenience methods for this bean. * @return JDOQLElements instance. */ + @Override JDOQLElements getJDOQLElements(Method m, AbstractMethodHelper methodHelper) throws IOException{ // Call the EJBQL compiler if there is no known result // from validate call. - JDOQLElements rs = (JDOQLElements)jdoqlElementsMap.get(m); + JDOQLElements rs = jdoqlElementsMap.get(m); if (rs == null) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine("JDOQLElements NOT FOUND for: " + m.getName()); - } + LOG.log(DEBUG, () -> "JDOQLElements NOT FOUND for: " + m.getName()); rs = ejbqlc.compile(methodHelper.getQueryString(m), m, methodHelper.getQueryReturnType(m), true, beanName); @@ -456,25 +460,18 @@ JDOQLElements getJDOQLElements(Method m, /** Adds ejbSelectBy methods. */ private void generateSelectors(AbstractMethodHelper methodHelper) throws IOException{ - List selectors = methodHelper.getSelectors(); - boolean debug = logger.isLoggable(Logger.FINE); - if (debug) { - logger.fine("Selectors: " + selectors.size()); // NOI18N - } + List selectors = methodHelper.getSelectors(); + LOG.log(DEBUG, () -> "Selectors: " + selectors.size()); for (int i = 0; i < selectors.size(); i++) { - Method m = (Method)selectors.get(i); + Method m = selectors.get(i); String mname = m.getName(); - if (debug) { - logger.fine("Selector: " + mname); // NOI18N - } + LOG.log(DEBUG, () -> "Selector: " + mname); - JDOQLElements rs = (JDOQLElements)jdoqlElementsMap.get(m); + JDOQLElements rs = jdoqlElementsMap.get(m); if (rs == null) { - if (debug) { - logger.fine("JDOQLElements NOT FOUND for: " + mname); - } + LOG.log(DEBUG, () -> "JDOQLElements NOT FOUND for: " + mname); // calling EJBQL compiler rs = ejbqlc.compile(methodHelper.getQueryString(m), m, @@ -482,7 +479,7 @@ private void generateSelectors(AbstractMethodHelper methodHelper) throws IOExcep } String returnType = m.getReturnType().getName(); - CMP20TemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( m, mname, returnType, generateSelectorMethodBody(methodHelper, rs, mname, m, returnType, i), concreteImplWriter); @@ -497,15 +494,16 @@ private void generateSelectors(AbstractMethodHelper methodHelper) throws IOExcep * parameters to be passed to another method as String. * @return method body as String. */ + @Override String getEJBCreateMethodBody(String createName, String[] exc, String parametersList, String parametersListWithSeparator) { // ejbCreate in the superclass will have the same suffix, so we need // to pass the actual name to the formatter - see 'createName' parameter. - if (!containsException(exc, CMP20TemplateFormatter.CreateException_)) { + if (!containsException(exc, CMPTemplateFormatter.CreateException_)) { throw new JDOUserException(I18NHelper.getMessage(messages, - "EXC_NoCreateException", createName, abstractBean)); // NOI18N + "EXC_NoCreateException", createName, abstractBean)); } // For read-only beans it will be the same. For updateable @@ -538,12 +536,13 @@ String getEJBCreateMethodBody(String createName, * parameters to be passed to another method as String. * @return method body as String. */ + @Override String getEJBPostCreateMethodBody(String postCreateName, String parametersList, String parametersListWithSeparator) { // For read-only beans it will be the same. For updateable // beans it will be generated as required. - String body = CMPTemplateFormatter.none_; + String body = JavaClassWriterHelper.none_; if (isUpdateable) { twoParams[0] = postCreateName; @@ -558,6 +557,7 @@ String getEJBPostCreateMethodBody(String postCreateName, /** Returns method body for EJBRemove method. * @return method body as String. */ + @Override String getEJBRemoveMethodBody() { // For read-only beans it will throw an exception. For updateable // beans it will be generated as required. @@ -570,7 +570,7 @@ String getEJBRemoveMethodBody() { CMP20TemplateFormatter.endCascadeDeleteTemplate). toString(); } else { - oneParam[0] = CMP20TemplateFormatter.none_; + oneParam[0] = JavaClassWriterHelper.none_; } body = CMP20TemplateFormatter.rmformatter.format(oneParam); @@ -583,13 +583,14 @@ String getEJBRemoveMethodBody() { * not need formatting but differ between CMP types. * CMP20TemplateFormatter.otherPublicMethods_ differ between CMP types. */ + @Override void generateKnownMethods(AbstractMethodHelper methodHelper) throws IOException { super.generateKnownMethods(methodHelper); String[] exc = null; - String[] st = CMP20TemplateFormatter.otherPublicMethodsArray; + String[] st = CMPTemplateFormatter.otherPublicMethodsArray; for (int i = 0; i < st.length; i++) { String mname = st[i]; exc = getExceptionList(methodHelper, mname); @@ -597,18 +598,18 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) String body = CMPROTemplateFormatter.updateNotAllowedTemplate; // Only ejbLoad from this list doesn't differ for read-only beans. if (isUpdateable || mname.equals(CMPTemplateFormatter.ejbLoad_)) { - body = CMP20TemplateFormatter.helpers.getProperty(mname); + body = CMPTemplateFormatter.helpers.getProperty(mname); } else if (mname.equals(CMPTemplateFormatter.jdoCleanAllRefs_)) { body = CMPROTemplateFormatter.jdoCleanAllRefsTemplate; } concreteImplWriter.addMethod(mname, // name Modifier.PUBLIC, // modifiers - CMP20TemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType null, // parameterNames null,// parameterTypes exc,// exceptions - CMP20TemplateFormatter.getBodyAsStrings(body), // body + JavaClassWriterHelper.getBodyAsStrings(body), // body null);// comments } @@ -617,6 +618,7 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) /** * Generates helper methods for the helper class. */ + @Override void generateHelperClassMethods() throws IOException { super.generateHelperClassMethods(); @@ -625,7 +627,7 @@ void generateHelperClassMethods() throws IOException { jdoHelperWriter.addMethod(CMP20TemplateFormatter.assertInstanceOfLocalInterfaceImpl_, // name Modifier.PUBLIC, // modifiers - CMP20TemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames objectType,// parameterTypes null,// exceptions @@ -637,19 +639,20 @@ void generateHelperClassMethods() throws IOException { * Generates conversion methods from PC to EJBObject and back * to the helper class. */ + @Override void generateConversions() throws IOException { super.generateConversions(); // For EJBLocalObject. if (hasLocalInterface == false) { - String[] pcParams = new String[] {CMP20TemplateFormatter.pc_, - CMP20TemplateFormatter.jdoPersistenceManager_}; - String[] pcParamTypes = new String[] {CMP20TemplateFormatter.Object_, - CMP20TemplateFormatter.jdoPersistenceManagerClass_}; + String[] pcParams = new String[] {CMPTemplateFormatter.pc_, + CMPTemplateFormatter.jdoPersistenceManager_}; + String[] pcParamTypes = new String[] {JavaClassWriterHelper.Object_, + CMPTemplateFormatter.jdoPersistenceManagerClass_}; - String[] body = CMP20TemplateFormatter.getBodyAsStrings( - CMP20TemplateFormatter.returnNull_); + String[] body = JavaClassWriterHelper.getBodyAsStrings( + JavaClassWriterHelper.returnNull_); jdoHelperWriter.addMethod(CMP20TemplateFormatter.convertPCToEJBLocalObject_, // name Modifier.PUBLIC, // modifiers @@ -660,12 +663,12 @@ void generateConversions() throws IOException { body, // body null);// comments - String[] pcParamsX = new String[] {CMP20TemplateFormatter.pc_, - CMP20TemplateFormatter.jdoPersistenceManager_, - CMP20TemplateFormatter.context_}; - String[] pcParamTypesX = new String[] {CMP20TemplateFormatter.Object_, - CMP20TemplateFormatter.jdoPersistenceManagerClass_, - CMP20TemplateFormatter.ejbContext_}; + String[] pcParamsX = new String[] {CMPTemplateFormatter.pc_, + CMPTemplateFormatter.jdoPersistenceManager_, + CMPTemplateFormatter.context_}; + String[] pcParamTypesX = new String[] {JavaClassWriterHelper.Object_, + CMPTemplateFormatter.jdoPersistenceManagerClass_, + CMPTemplateFormatter.ejbContext_}; jdoHelperWriter.addMethod(CMP20TemplateFormatter.convertPCToEJBLocalObject_, // name Modifier.PUBLIC, // modifiers CMP20TemplateFormatter.ejbLocalObject_, // returnType @@ -677,10 +680,10 @@ void generateConversions() throws IOException { twoParams[0] = CMP20TemplateFormatter.ejbLocalObject_; - twoParams[1] = CMP20TemplateFormatter.jdoPersistenceManagerClass_; - jdoHelperWriter.addMethod(CMP20TemplateFormatter.convertEJBLocalObjectToPC_, // name + twoParams[1] = CMPTemplateFormatter.jdoPersistenceManagerClass_; + jdoHelperWriter.addMethod(CMPTemplateFormatter.convertEJBLocalObjectToPC_, // name Modifier.PUBLIC, // modifiers - CMP20TemplateFormatter.Object_, // returnType + JavaClassWriterHelper.Object_, // returnType param0PM, // parameterNames twoParams,// parameterTypes null,// exceptions @@ -761,7 +764,9 @@ private String generateResultHandlingForMultiSelector( // depending of the kind of returntype a different convertermethodcall // is generated - if (isSelectorReturningSet(m)) convertToSet = true; + if (isSelectorReturningSet(m)) { + convertToSet = true; + } int queryReturnType = methodHelper.getQueryReturnType(m); if ((queryReturnType == AbstractMethodHelper.NO_RETURN) && @@ -780,7 +785,7 @@ private String generateResultHandlingForMultiSelector( threeParams[1] = convertToSet ? CMP20TemplateFormatter.convertCollectionPCToEJBLocalObjectSet_ : CMP20TemplateFormatter.convertCollectionPCToEJBLocalObject_; - threeParams[2] = CMP20TemplateFormatter.catchClauseTemplate; + threeParams[2] = CMPTemplateFormatter.catchClauseTemplate; body = mformat.format(threeParams); break; case (AbstractMethodHelper.REMOTE_RETURN): @@ -790,7 +795,7 @@ private String generateResultHandlingForMultiSelector( threeParams[1] = convertToSet ? CMP20TemplateFormatter.convertCollectionPCToEJBObjectSet_ : CMP20TemplateFormatter.convertCollectionPCToEJBObject_; - threeParams[2] = CMP20TemplateFormatter.catchClauseTemplate; + threeParams[2] = CMPTemplateFormatter.catchClauseTemplate; body = mformat.format(threeParams); break; case (AbstractMethodHelper.NO_RETURN): @@ -798,7 +803,7 @@ private String generateResultHandlingForMultiSelector( mformat = convertToSet ? CMP20TemplateFormatter.multiselectorsetformatter : CMP20TemplateFormatter.multiselectorformatter; - oneParam[0] = CMP20TemplateFormatter.catchClauseTemplate; + oneParam[0] = CMPTemplateFormatter.catchClauseTemplate; body = mformat.format(oneParam); break; } @@ -839,7 +844,7 @@ private String generateResultHandlingForSingleSelector( } // getting the catch-clause body from the properties - oneParam[0] = CMP20TemplateFormatter.none_; + oneParam[0] = JavaClassWriterHelper.none_; int queryReturnType = methodHelper.getQueryReturnType(m); if ((queryReturnType == AbstractMethodHelper.NO_RETURN) && @@ -858,7 +863,7 @@ private String generateResultHandlingForSingleSelector( fourParams[0] = nameMapper.getLocalInterfaceForEjbName(ejbName); fourParams[1] = nameMapper.getConcreteBeanClassForEjbName(ejbName); fourParams[2] = CMP20TemplateFormatter.convertPCToEJBLocalObject_; - fourParams[3] = CMP20TemplateFormatter.catchClauseTemplate; + fourParams[3] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(fourParams)); break; case (AbstractMethodHelper.REMOTE_RETURN): @@ -866,50 +871,50 @@ private String generateResultHandlingForSingleSelector( mformat = CMP20TemplateFormatter.singleselectorreturnconvformatter; fourParams[0] = nameMapper.getRemoteInterfaceForEjbName(ejbName); fourParams[1] = nameMapper.getConcreteBeanClassForEjbName(ejbName); - fourParams[2] = CMP20TemplateFormatter.convertPCToEJBObject_; - fourParams[3] = CMP20TemplateFormatter.catchClauseTemplate; + fourParams[2] = CMPTemplateFormatter.convertPCToEJBObject_; + fourParams[3] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(fourParams)); break; case (AbstractMethodHelper.NO_RETURN): default: - Class returnTypeClass = m.getReturnType(); + Class returnTypeClass = m.getReturnType(); // tests if it is aggregate function and proceed it first if (jdoqlElements.isAggregate()) { if (returnTypeClass.isPrimitive()) { mformat = CMP20TemplateFormatter.aggregateselectorprimitivereturnformatter; fourParams[0] = mname; fourParams[1] = jdoResultType; - fourParams[2] = CMP20TemplateFormatter.dot_ + - CMP20TemplateFormatter.getUnwrapMethodName(returnTypeClass); - fourParams[3] = CMP20TemplateFormatter.catchClauseTemplate; + fourParams[2] = JavaClassWriterHelper.dot_ + + JavaClassWriterHelper.getUnwrapMethodName(returnTypeClass); + fourParams[3] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(fourParams)); } else if (returnTypeClass.getName().equals(jdoResultType)) { mformat = CMP20TemplateFormatter.aggregateselectorreturnformatter; twoParams[0] = jdoResultType; - twoParams[1] = CMP20TemplateFormatter.catchClauseTemplate; + twoParams[1] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(twoParams)); } else if (returnTypeClass.isAssignableFrom( java.math.BigDecimal.class)) { mformat = CMP20TemplateFormatter.aggregateselectorreturnbigdecimalconvformatter; twoParams[0] = jdoResultType; - twoParams[1] = CMP20TemplateFormatter.catchClauseTemplate; + twoParams[1] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(twoParams)); } else if (returnTypeClass.isAssignableFrom( java.math.BigInteger.class)) { mformat = CMP20TemplateFormatter.aggregateselectorreturnbigintegerconvformatter; twoParams[0] = jdoResultType; - twoParams[1] = CMP20TemplateFormatter.catchClauseTemplate; + twoParams[1] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(twoParams)); } else { mformat = CMP20TemplateFormatter.aggregateselectorreturnconvformatter; fourParams[0] = returnType; fourParams[1] = jdoResultType; - fourParams[2] = CMP20TemplateFormatter.dot_ + - CMP20TemplateFormatter.getUnwrapMethodName( - CMP20TemplateFormatter.getPrimitiveClass( - CMP20TemplateFormatter.getPrimitiveName(returnTypeClass))); - fourParams[3] = CMP20TemplateFormatter.catchClauseTemplate; + fourParams[2] = JavaClassWriterHelper.dot_ + + JavaClassWriterHelper.getUnwrapMethodName( + JavaTypeHelper.getPrimitiveClass( + JavaTypeHelper.getPrimitiveName(returnTypeClass))); + fourParams[3] = CMPTemplateFormatter.catchClauseTemplate; body.append(mformat.format(fourParams)); } } else { @@ -921,14 +926,14 @@ private String generateResultHandlingForSingleSelector( // of objects only, but the selector returns a primitive type. mformat = CMP20TemplateFormatter.singleselectorreturnformatter; if (returnTypeClass.isPrimitive()) { - threeParams[0] = CMP20TemplateFormatter.getWrapperName(returnType); - threeParams[1] = CMP20TemplateFormatter.dot_ + - CMP20TemplateFormatter.getUnwrapMethodName(returnTypeClass); - threeParams[2] = CMP20TemplateFormatter.catchClauseTemplate; + threeParams[0] = JavaTypeHelper.getWrapperName(returnType); + threeParams[1] = JavaClassWriterHelper.dot_ + + JavaClassWriterHelper.getUnwrapMethodName(returnTypeClass); + threeParams[2] = CMPTemplateFormatter.catchClauseTemplate; } else { threeParams[0] = returnType; - threeParams[1] = CMP20TemplateFormatter.none_; - threeParams[2] = CMP20TemplateFormatter.catchClauseTemplate; + threeParams[1] = JavaClassWriterHelper.none_; + threeParams[2] = CMPTemplateFormatter.catchClauseTemplate; } body.append(mformat.format(threeParams)); } @@ -947,11 +952,12 @@ private String generateResultHandlingForSingleSelector( * @return the codefragment for the checking local/remote parameters * for method if EJB name is known from ejbql. */ + @Override String generateFinderSelectorParamCheck(Method m, String[] parameterEjbNames) { StringBuffer checkBody = new StringBuffer(); - Class[] paramTypes = m.getParameterTypes(); + Class[] paramTypes = m.getParameterTypes(); int paramLength = paramTypes.length; String paramClassName = null; for (int i = 0; i < paramLength; i++) { @@ -961,7 +967,7 @@ String generateFinderSelectorParamCheck(Method m, nameMapper.getConcreteBeanClassForEjbName( parameterEjbNames[i]); twoParams[0] = concreteImplName; - twoParams[1] = CMP20TemplateFormatter.param_ + i; + twoParams[1] = JavaClassWriterHelper.param_ + i; if (nameMapper.isLocalInterface(paramClassName)) { checkBody.append(CMP20TemplateFormatter.finderselectorchecklocalformatter.format(twoParams)); @@ -980,6 +986,7 @@ String generateFinderSelectorParamCheck(Method m, * @param finder Methodobject of the finder * @return true if the finder returns a Enumeration */ + @Override boolean isFinderReturningEnumeration(Method finder) { return false; } @@ -1008,6 +1015,7 @@ private boolean isSelectorReturningSet(Method selector) { * involved in the codegen. * @return The signatures as a string. */ + @Override String getSignaturesOfGeneratorClasses() { StringBuffer signatures = new StringBuffer(). diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBeanGenerator.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBeanGenerator.java index f0bde3f329c..9b9319f9999 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBeanGenerator.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/JDOConcreteBeanGenerator.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 */ -/* - * JDOConcreteBeanGenerator.java - * - * Created on November 20, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; import com.sun.jdo.api.persistence.model.Model; @@ -30,16 +25,17 @@ import com.sun.jdo.spi.persistence.support.ejb.ejbqlc.JDOQLElements; import com.sun.jdo.spi.persistence.support.ejb.model.DeploymentDescriptorModel; import com.sun.jdo.spi.persistence.support.ejb.model.util.NameMapper; +import com.sun.jdo.spi.persistence.utility.JavaTypeHelper; import com.sun.jdo.spi.persistence.utility.StringHelper; import com.sun.jdo.spi.persistence.utility.generator.JavaClassWriter; import com.sun.jdo.spi.persistence.utility.generator.JavaClassWriterHelper; 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.IOException; +import java.lang.System.Logger; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.MessageFormat; @@ -52,15 +48,17 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.DEBUG; + /* * This is the base class for JDO specific generator for the concrete CMP * beans. * - * @author Marina Vatkina + * @author Marina Vatkina 2001 */ abstract class JDOConcreteBeanGenerator { - static final Logger logger = LogHelperEJBCompiler.getLogger(); + private static final Logger LOG = System.getLogger(JDOConcreteBeanGenerator.class.getName()); // used to transform b/w various ejb names and pc class names NameMapper nameMapper = null; @@ -84,9 +82,9 @@ abstract class JDOConcreteBeanGenerator { String[] pcnameParam = new String[1]; String[] pkClassParam = new String[1]; - static String[] objectType = new String[]{CMPTemplateFormatter.Object_}; - static String[] param0 = new String[]{CMPTemplateFormatter.param0_}; - static String[] param0PM = new String[] {CMPTemplateFormatter.param0_, + static String[] objectType = new String[]{JavaClassWriterHelper.Object_}; + static String[] param0 = new String[]{JavaClassWriterHelper.param0_}; + static String[] param0PM = new String[] {JavaClassWriterHelper.param0_, CMPTemplateFormatter.jdoPersistenceManager_}; // Generic parameters @@ -118,14 +116,14 @@ abstract class JDOConcreteBeanGenerator { /** Name of the SUPPORT_TRAILING_SPACES_IN_VARCHAR_PK_COLUMNS property. */ public static final String SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS_PROPERTY = - "com.sun.jdo.spi.persistence.support.ejb.ejbc.SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS"; // NOI18N + "com.sun.jdo.spi.persistence.support.ejb.ejbc.SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS"; /** * Property to swich on/off support for trailing spaces for pk of String types. Note, the default is false, meaning * we trip trailing spaces in pk columns */ private static final boolean SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS = Boolean.valueOf( - System.getProperty(SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS_PROPERTY, "false")).booleanValue(); // NOI18N + System.getProperty(SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS_PROPERTY, "false")).booleanValue(); /** @@ -169,8 +167,8 @@ void setUpdateable(boolean updateable) { * each failed validation. This implementation returns an empty collection * because generic validation always succeeds. */ - Collection validate(AbstractMethodHelper methodHelper, String beanName) { - return new ArrayList(); + Collection validate(AbstractMethodHelper methodHelper, String beanName) { + return new ArrayList<>(); } /** @@ -194,9 +192,9 @@ Collection generate(AbstractMethodHelper methodHelper, this.appName = appName; this.abstractBean = nameMapper.getAbstractBeanClassForEjbName(beanName); - String pkgName = CMPTemplateFormatter.getPackageName(abstractBean); + String pkgName = JavaTypeHelper.getPackageName(abstractBean); concreteImplName = nameMapper.getConcreteBeanClassForEjbName(beanName); - String shortCmpName = CMPTemplateFormatter.getShortClassName(concreteImplName); + String shortCmpName = JavaTypeHelper.getShortClassName(concreteImplName); pcname = nameMapper.getPersistenceClassForEjbName(beanName); pcnameParam[0] = pcname; @@ -213,24 +211,24 @@ Collection generate(AbstractMethodHelper methodHelper, String prefix = srcout.getPath() + File.separator + concreteImplName.replace('.', File.separatorChar); - String cmp_file_name = prefix + CMPTemplateFormatter.javaExtension_; + String cmp_file_name = prefix + JavaClassWriterHelper.javaExtension_; - String hlp_file_name = prefix + CMPTemplateFormatter.Helper_ + - CMPTemplateFormatter.javaExtension_; + String hlp_file_name = prefix + JavaClassWriterHelper.Helper_ + + JavaClassWriterHelper.javaExtension_; hasLocalInterface = (nameMapper.getLocalInterfaceForEjbName(beanName) != null); hasRemoteInterface = (nameMapper.getRemoteInterfaceForEjbName(beanName) != null); - if (logger.isLoggable(Logger.FINE)) { - logger.fine("allFields: " + // NOI18N + if (LOG.isLoggable(DEBUG)) { + LOG.log(DEBUG, () -> "allFields: " + ((allFields != null) ? allFields.length : 0)); - logger.fine("cmp_file_name: " + cmp_file_name); // NOI18N - logger.fine("hlp_file_name: " + hlp_file_name); // NOI18N - logger.fine("cmp_name: " + concreteImplName); // NOI18N - logger.fine("pkClass: " + pkClass); // NOI18N - logger.fine("PCname: " + pcname); // NOI18N + LOG.log(DEBUG, () -> "cmp_file_name: " + cmp_file_name); + LOG.log(DEBUG, () -> "hlp_file_name: " + hlp_file_name); + LOG.log(DEBUG, () -> "cmp_name: " + concreteImplName); + LOG.log(DEBUG, () -> "pkClass: " + pkClass); + LOG.log(DEBUG, () -> "PCname: " + pcname); } File cmp_file = new File(cmp_file_name); @@ -263,14 +261,14 @@ Collection generate(AbstractMethodHelper methodHelper, // Add no-arg constructor. concreteImplWriter.addConstructor(shortCmpName, Modifier.PUBLIC, null, null, null, - CMPTemplateFormatter.super_, null); + JavaClassWriterHelper.super_, null); // Add helper class. - helperName = shortCmpName + CMPTemplateFormatter.Helper_; + helperName = shortCmpName + JavaClassWriterHelper.Helper_; oneParam[0] = shortCmpName; jdoHelperWriter.setClassDeclaration(Modifier.PUBLIC, - helperName, CMPTemplateFormatter.getBodyAsStrings( + helperName, JavaClassWriterHelper.getBodyAsStrings( CMPTemplateFormatter.hcomformatter.format(oneParam))); setHelperSuperclass(); @@ -405,13 +403,13 @@ void addCodeGeneratorClassSignature(String newSignature) void generateFields() throws IOException { // Add private transient fields: - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.privatetransientvformatter.format(pcnameParam), Modifier.TRANSIENT, concreteImplWriter); // Add private static fields: - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.privateStaticVariablesTemplate, Modifier.STATIC, concreteImplWriter); @@ -419,7 +417,7 @@ void generateFields() throws IOException { // Add private static final fields: twoParams[0] = pcname; twoParams[1] = beanName; - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.privatestaticfinalvformatter.format(twoParams), Modifier.STATIC + Modifier.FINAL, concreteImplWriter); @@ -427,7 +425,7 @@ void generateFields() throws IOException { // Add public static final variables for signatures twoParams[0] = generatorClassesSignature; twoParams[1] = inputFilesSignature; - CMPTemplateFormatter.addFields( + JavaClassWriterHelper.addFields( CMPTemplateFormatter.publicstaticfinalvformatter.format(twoParams), Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL, concreteImplWriter); @@ -435,14 +433,14 @@ void generateFields() throws IOException { // The static fields holding the Query variables and their monitors // are generated during finder/selector method handling. - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.otherVariablesTemplate, 0, concreteImplWriter); threeParams[0] = concreteImplName; threeParams[1] = beanName; threeParams[2] = appName; - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.hvformatter.format(threeParams), Modifier.TRANSIENT+Modifier.STATIC, jdoHelperWriter); @@ -450,13 +448,13 @@ void generateFields() throws IOException { // Add read-only fields: if (!isUpdateable) { // private transient fields: - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPROTemplateFormatter.privatetransientvformatter.format(pcnameParam), Modifier.TRANSIENT, concreteImplWriter); // private static fields: - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPROTemplateFormatter.privateStaticFinalVariablesTemplate, Modifier.STATIC + Modifier.FINAL, concreteImplWriter); @@ -469,21 +467,17 @@ void generateFields() throws IOException { void generateFinders(AbstractMethodHelper methodHelper) throws IOException { - boolean debug = logger.isLoggable(Logger.FINE); - List finders = methodHelper.getFinders(); + List finders = methodHelper.getFinders(); for (int i = 0; i < finders.size(); i++) { - Method m = (Method)finders.get(i); + Method m = finders.get(i); String mname = CMPTemplateFormatter.ejb_ + StringHelper.getCapitalizedString(m.getName()); - if (debug) { - logger.fine("Finder: " + mname); // NOI18N - } + LOG.log(DEBUG, () -> "Finder: " + mname); if (mname.equals(CMPTemplateFormatter.ejbFindByPrimaryKey_)) { // ejbFindByPrimaryKey - String[] exceptionTypes = - CMPTemplateFormatter.getExceptionNames(m); + String[] exceptionTypes = JavaClassWriterHelper.getExceptionNames(m); oneParam[0] = CMPTemplateFormatter.key_; @@ -502,7 +496,7 @@ void generateFinders(AbstractMethodHelper methodHelper) // check for single-object finder vs. multi-object finder String returnType = isSingleObjectFinder(m) ? pkClass : m.getReturnType().getName(); - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( m, mname, returnType, generateFinderMethodBody(methodHelper, rs, mname, m, returnType, i), concreteImplWriter); @@ -523,8 +517,8 @@ abstract JDOQLElements getJDOQLElements(Method m, /** Adds ejbCreate methods. */ - private void generateCreateMethods(List createMethods) throws IOException { - Class beanClass = null; + private void generateCreateMethods(List createMethods) throws IOException { + Class beanClass = null; try { beanClass = Class.forName(abstractBean, true, loader); } catch (Exception e) { @@ -532,10 +526,10 @@ private void generateCreateMethods(List createMethods) throws IOException { } // Store generated getters to avoid duplicates. - HashSet generated = new HashSet(); + HashSet generated = new HashSet<>(); for (int i = 0; i < createMethods.size(); i++) { - Method m = (Method)createMethods.get(i); + Method m = createMethods.get(i); Method m1 = m; // Method name is ejbCreate @@ -547,16 +541,16 @@ private void generateCreateMethods(List createMethods) throws IOException { postCreateName += suffix; } - boolean debug = logger.isLoggable(Logger.FINE); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("CreateMethod: " + abstractBean + "" + m.getName()); // NOI18N - logger.fine("ejbCreateMethod: " + createName); // NOI18N - logger.fine("ejbPostCreateMethod: " + postCreateName); // NOI18N + LOG.log(DEBUG, "CreateMethod: " + abstractBean + "" + m.getName()); + LOG.log(DEBUG, "ejbCreateMethod: " + createName); + LOG.log(DEBUG, "ejbPostCreateMethod: " + postCreateName); } // Get actual method in the bean and resolve exception type to generate... try { - Class[] params = m.getParameterTypes(); + Class[] params = m.getParameterTypes(); // This is a work around the case when the parameter class loader // differs from the given class loader ("loader"). @@ -569,9 +563,9 @@ private void generateCreateMethods(List createMethods) throws IOException { String pname = params[j].getName(); if (debug) { - logger.fine("Replacing parameter class for: " + pname); // NOI18N - logger.fine("Param ClassLoader: " + params[j].getClassLoader()); - logger.fine("Need ClassLoader: " + loader); + LOG.log(DEBUG, "Replacing parameter class for: " + pname); + LOG.log(DEBUG, "Param ClassLoader: " + params[j].getClassLoader()); + LOG.log(DEBUG, "Need ClassLoader: " + loader); } params[j] = Class.forName(pname, true, loader); @@ -585,7 +579,7 @@ private void generateCreateMethods(List createMethods) throws IOException { if (generated.contains(m)) { // Called from more than one interface - skip it. if (debug) { - logger.fine("...generated..."); // NOI18N + LOG.log(DEBUG, () -> "...generated..."); } continue; @@ -598,24 +592,18 @@ private void generateCreateMethods(List createMethods) throws IOException { continue; } - String[] exc = CMPTemplateFormatter.getExceptionNames(m); - String parametersList = CMPTemplateFormatter.getParametersList(m); + String[] exc = JavaClassWriterHelper.getExceptionNames(m); + String parametersList = JavaClassWriterHelper.getParametersList(m); String parametersListWithSeparator = makeLiteral( - CMPTemplateFormatter.getParametersListWithSeparator( - m, CMPTemplateFormatter.paramConcatenator_ )); + JavaClassWriterHelper.getParametersListWithSeparator(m, JavaClassWriterHelper.paramConcatenator_)); - String body = getEJBCreateMethodBody(createName, exc, - parametersList, parametersListWithSeparator); + String body = getEJBCreateMethodBody(createName, exc, parametersList, parametersListWithSeparator); - CMPTemplateFormatter.addGenericMethod( - m, createName, pkClass, body, concreteImplWriter); + JavaClassWriterHelper.addGenericMethod(m, createName, pkClass, body, concreteImplWriter); - body = getEJBPostCreateMethodBody(postCreateName, - parametersList, parametersListWithSeparator); + body = getEJBPostCreateMethodBody(postCreateName, parametersList, parametersListWithSeparator); - CMPTemplateFormatter.addGenericMethod( - m1, postCreateName, CMPTemplateFormatter.void_, - body, concreteImplWriter); + JavaClassWriterHelper.addGenericMethod(m1, postCreateName, JavaClassWriterHelper.void_, body, concreteImplWriter); } } @@ -679,20 +667,20 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) concreteImplWriter.addMethod(mname, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType null, // parameterNames null,// parameterTypes exc,// exceptions - CMPTemplateFormatter.getBodyAsStrings(body), // body + JavaClassWriterHelper.getBodyAsStrings(body), // body null);// comments } // This is a cleanup method that is public, but has int param. - oneParam[0] = CMPTemplateFormatter.int_; + oneParam[0] = JavaClassWriterHelper.int_; concreteImplWriter.addMethod(CMPTemplateFormatter.afterCompletion_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames oneParam,// parameterTypes null,// exceptions @@ -701,7 +689,7 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) concreteImplWriter.addMethod(CMPTemplateFormatter.ejb__remove_, // name Modifier.PUBLIC , // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames objectType, //parameterTypes null,// exceptions @@ -716,30 +704,30 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) String mname = st[i]; body = CMPTemplateFormatter.helpers.getProperty(mname); - CMPTemplateFormatter.addGenericMethod(mname, - CMPTemplateFormatter.getBodyAsStrings(body), concreteImplWriter); + JavaClassWriterHelper.addGenericMethod(mname, + JavaClassWriterHelper.getBodyAsStrings(body), concreteImplWriter); } // Add jdoArrayCopy to return byte[]. - oneParam[0] = CMPTemplateFormatter.byte_; + oneParam[0] = JavaClassWriterHelper.byte_; body = CMPTemplateFormatter.jdoarraycopyformatter.format(oneParam); - oneParam[0] = CMPTemplateFormatter.byteArray_; + oneParam[0] = JavaClassWriterHelper.byteArray_; concreteImplWriter.addMethod( CMPTemplateFormatter.jdoArrayCopy_, // name Modifier.PRIVATE, // modifiers - CMPTemplateFormatter.byteArray_, // returnType + JavaClassWriterHelper.byteArray_, // returnType param0, // parameterNames oneParam,// parameterTypes null,// exceptions - CMPTemplateFormatter.getBodyAsStrings(body), // body + JavaClassWriterHelper.getBodyAsStrings(body), // body null);// comments // Add setEntityContext oneParam[0] = CMPTemplateFormatter.EntityContext_; concreteImplWriter.addMethod(CMPTemplateFormatter.setEntityContext_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames oneParam,// parameterTypes getExceptionList(methodHelper, @@ -755,21 +743,21 @@ void generateKnownMethods(AbstractMethodHelper methodHelper) concreteImplWriter.addMethod(CMPTemplateFormatter.getObjectId_, // name Modifier.PRIVATE , // modifiers - CMPTemplateFormatter.Object_, // returnType + JavaClassWriterHelper.Object_, // returnType oneParam, // parameterNames pkClassParam,// parameterTypes null,// exceptions - CMPTemplateFormatter.getBodyAsStrings( + JavaClassWriterHelper.getBodyAsStrings( CMPTemplateFormatter.goidformatter.format(param)), // body null);// comments // Add jdoGetJdoInstanceClass oneParam[0] = CMPTemplateFormatter.jdoGetJdoInstanceClassTemplate; - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.jdoGetJdoInstanceClass_, Modifier.PUBLIC + Modifier.STATIC, - CMPTemplateFormatter.Class_, oneParam, + JavaClassWriterHelper.Class_, oneParam, concreteImplWriter); generateSpecialKnownMethods(); @@ -789,17 +777,17 @@ void generateSpecialKnownMethods() throws IOException { if (isUpdateable) { body = CMPTemplateFormatter.assertPersistenceManagerIsNullBody; } - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.assertPersistenceManagerIsNull_, body, concreteImplWriter); // assertInTransaction if (isUpdateable) { - oneParam[0] = I18NHelper.getMessage(messages, "EXC_TransactionNotActive"); // NOI18N - body = CMPTemplateFormatter.getBodyAsStrings( + oneParam[0] = I18NHelper.getMessage(messages, "EXC_TransactionNotActive"); + body = JavaClassWriterHelper.getBodyAsStrings( CMPTemplateFormatter.intxformatter.format(oneParam)); } - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.assertInTransaction_, body, concreteImplWriter); @@ -813,7 +801,7 @@ void generateSpecialKnownMethods() throws IOException { body = CMPROTemplateFormatter.jdoClosePersistenceManagerBody; } - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.jdoClosePersistenceManager_, body, concreteImplWriter); @@ -823,7 +811,7 @@ void generateSpecialKnownMethods() throws IOException { } else { body = CMPROTemplateFormatter.jdoGetPersistenceManagerBody; } - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.jdoGetPersistenceManager_, CMPTemplateFormatter.jdoPersistenceManagerClass_, body, concreteImplWriter); @@ -867,17 +855,17 @@ void generateSpecialKnownMethods() throws IOException { concreteImplWriter.addMethod( CMPTemplateFormatter.jdoLookupPersistenceManagerFactory_, Modifier.PRIVATE + Modifier.STATIC + Modifier.SYNCHRONIZED, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames objectType, // parameterTypes null,// exceptions - CMPTemplateFormatter.getBodyAsStrings(mformat.format(oneParam)), + JavaClassWriterHelper.getBodyAsStrings(mformat.format(oneParam)), null);// comments // Add jdoGetInstance threeParams[0] = pkClass; threeParams[1] = pcname; - threeParams[2] = CMPTemplateFormatter.none_; // will be ignored for updateable beans + threeParams[2] = JavaClassWriterHelper.none_; // will be ignored for updateable beans if (isUpdateable) { mformat = CMPTemplateFormatter.giformatter; } else { @@ -886,9 +874,9 @@ void generateSpecialKnownMethods() throws IOException { } mformat = CMPROTemplateFormatter.giformatter; } - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.getInstance_, - CMPTemplateFormatter.getBodyAsStrings(mformat.format(threeParams)), + JavaClassWriterHelper.getBodyAsStrings(mformat.format(threeParams)), concreteImplWriter); // These are methods that do have arguments. @@ -898,12 +886,12 @@ void generateSpecialKnownMethods() throws IOException { body = null; } else { // Reuse threeParams from getInstance_ - body = CMPTemplateFormatter.getBodyAsStrings( + body = JavaClassWriterHelper.getBodyAsStrings( CMPROTemplateFormatter.ejb__refreshformatter.format(threeParams)); } concreteImplWriter.addMethod(CMPTemplateFormatter.ejb__refresh_, // name Modifier.PUBLIC , // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames objectType, //parameterTypes null,// exceptions @@ -915,7 +903,7 @@ void generateSpecialKnownMethods() throws IOException { oneParam[0] = CMPTemplateFormatter.jdoPersistenceManagerClass_; concreteImplWriter.addMethod(CMPTemplateFormatter.jdoReleasePersistenceManager_, // name Modifier.PRIVATE, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames oneParam,// parameterTypes null,// exceptions @@ -932,7 +920,7 @@ void generateSpecialKnownMethods() throws IOException { } concreteImplWriter.addMethod(CMPTemplateFormatter.jdoReleasePersistenceManager0_, // name Modifier.PRIVATE, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames oneParam,// parameterTypes null,// exceptions @@ -950,7 +938,7 @@ void generateHelperClassMethods() throws IOException { jdoHelperWriter.addMethod(CMPTemplateFormatter.assertInstanceOfRemoteInterfaceImpl_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.void_, // returnType + JavaClassWriterHelper.void_, // returnType param0, // parameterNames objectType,// parameterTypes null,// exceptions @@ -959,42 +947,43 @@ void generateHelperClassMethods() throws IOException { // Add Helper.getHelperInstance() method. oneParam[0] = CMPTemplateFormatter.getHelperInstanceTemplate; - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.getHelperInstance_, Modifier.PUBLIC + Modifier.STATIC, helperName, oneParam, jdoHelperWriter); // Add Helper.getContainer() method. - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.getContainer_, - Modifier.PUBLIC, CMPTemplateFormatter.Object_, + Modifier.PUBLIC, JavaClassWriterHelper.Object_, CMPTemplateFormatter.getContainerBody, jdoHelperWriter); // Add getPCCLass to the helper class oneParam[0] = concreteImplName; - CMPTemplateFormatter.addGenericMethod( + JavaClassWriterHelper.addGenericMethod( CMPTemplateFormatter.getPCClass_, - Modifier.PUBLIC, CMPTemplateFormatter.Class_, - CMPTemplateFormatter.getBodyAsStrings( + Modifier.PUBLIC, JavaClassWriterHelper.Class_, + JavaClassWriterHelper.getBodyAsStrings( CMPTemplateFormatter.pcclassgetterformatter.format( oneParam)), jdoHelperWriter); } private String[] getKeyFields(PersistenceFieldElement[] fields) { - List returnList = new ArrayList(); + List returnList = new ArrayList<>(); int i, count = ((fields != null) ? fields.length : 0); for (i = 0; i < count; i++) { PersistenceFieldElement pfe = fields[i]; - if (pfe.isKey()) + if (pfe.isKey()) { returnList.add(pfe.getName()); + } } - return (String[])returnList.toArray(new String[returnList.size()]); + return (String[])returnList.toArray(String[]::new); } /** Adds ObjectId/PrimaryKey conversion methods to the helper class. @@ -1014,7 +1003,6 @@ private void generatePKObjectIdConversion(String[] keyFields) getPK.append(CMPTemplateFormatter.assertOidNotNullTemplate). append(CMPTemplateFormatter.oidcformatter.format(pcnameParam)); - boolean debug = logger.isLoggable(Logger.FINE); if (length == 1) { // only one key field - we don't know yet if there is a special PK class. @@ -1023,9 +1011,7 @@ private void generatePKObjectIdConversion(String[] keyFields) String pkfieldType = model.getFieldType(pcname, pkfield); pkfieldParam[0] = pkfield; - if (debug) { - logger.fine("pkfield: " + pkfield); // NOI18N - } + LOG.log(DEBUG, () -> "pkfield: " + pkfield); if (model.isPrimitive(pcname, pkfield) || (!pkClass.equals(pkfieldType) && @@ -1078,9 +1064,7 @@ private void generatePKObjectIdConversion(String[] keyFields) String pkfield = keyFields[i]; pkfieldParam[0] = pkfield; - if (debug) { - logger.fine("pkfield: " + pkfield); // NOI18N - } + LOG.log(DEBUG, () -> "pkfield: " + pkfield); if (!model.isPrimitive(pcname, pkfield)) { getOid.append( @@ -1110,20 +1094,20 @@ private void generatePKObjectIdConversion(String[] keyFields) // Add ones that can be used for Collection conversion. jdoHelperWriter.addMethod(CMPTemplateFormatter.convertPrimaryKeyToObjectId_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.Object_, // returnType + JavaClassWriterHelper.Object_, // returnType param0, // parameterNames objectType,// parameterTypes null,// exceptions - CMPTemplateFormatter.getBodyAsStrings(getOid.toString()), // body + JavaClassWriterHelper.getBodyAsStrings(getOid.toString()), // body null);// comments jdoHelperWriter.addMethod(CMPTemplateFormatter.convertObjectIdToPrimaryKey_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.Object_, // returnType + JavaClassWriterHelper.Object_, // returnType param0, // parameterNames objectType,// parameterTypes null,// exceptions - CMPTemplateFormatter.getBodyAsStrings(getPK.toString()), // body + JavaClassWriterHelper.getBodyAsStrings(getPK.toString()), // body null);// comments } @@ -1146,7 +1130,7 @@ String getConcreteBeanForPCClass(String pcClass) { void generateConversions() throws IOException { String[] pcParams = new String[] {CMPTemplateFormatter.pc_, CMPTemplateFormatter.jdoPersistenceManager_}; - String[] pcParamTypes = new String[] {CMPTemplateFormatter.Object_, + String[] pcParamTypes = new String[] {JavaClassWriterHelper.Object_, CMPTemplateFormatter.jdoPersistenceManagerClass_}; // For PC - PK conversion. @@ -1154,8 +1138,8 @@ void generateConversions() throws IOException { // Generate for Remote object conversion. if (hasRemoteInterface == false) { - body = CMPTemplateFormatter.getBodyAsStrings( - CMPTemplateFormatter.returnNull_ ); + body = JavaClassWriterHelper.getBodyAsStrings( + JavaClassWriterHelper.returnNull_ ); jdoHelperWriter.addMethod(CMPTemplateFormatter.convertPCToEJBObject_, // name Modifier.PUBLIC, // modifiers @@ -1170,7 +1154,7 @@ void generateConversions() throws IOException { twoParams[1] = CMPTemplateFormatter.jdoPersistenceManagerClass_; jdoHelperWriter.addMethod(CMPTemplateFormatter.convertEJBObjectToPC_, // name Modifier.PUBLIC, // modifiers - CMPTemplateFormatter.Object_, // returnType + JavaClassWriterHelper.Object_, // returnType param0PM, // parameterNames twoParams,// parameterTypes null,// exceptions @@ -1269,7 +1253,7 @@ private String generateFinderMethodBody(AbstractMethodHelper methodHelper, StringBuffer body = new StringBuffer(); body.append(CMPTemplateFormatter.assertPersistenceManagerIsNullTemplate); - body.append(CMPTemplateFormatter.endLine_); + body.append(JavaClassWriterHelper.endLine_); body.append(generateFinderSelectorCommonBody(methodHelper, jdoqlElements, mname, @@ -1334,11 +1318,11 @@ String generateFinderSelectorCommonBody(AbstractMethodHelper methodHelper, // add private static query variables and their monitors // no need to check ejbFindByPrimaryKey here oneParam[0] = queryVariableQualifier; - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.finderselectorstaticvformatter.format(oneParam), Modifier.STATIC, concreteImplWriter); - CMPTemplateFormatter.addPrivateField( + JavaClassWriterHelper.addPrivateField( CMPTemplateFormatter.finderselectorstaticfinalvformatter.format(oneParam), Modifier.STATIC + Modifier.FINAL, concreteImplWriter); @@ -1371,7 +1355,7 @@ String generateFinderSelectorCommonBody(AbstractMethodHelper methodHelper, if (jdoqlElements.isAggregate()) { if (queryParam == null) { - oneParam[0] = CMPTemplateFormatter.none_; + oneParam[0] = JavaClassWriterHelper.none_; body.append(CMPTemplateFormatter.aggqueryexecformatter.format(oneParam)); } else { oneParam[0] = queryParam; @@ -1380,7 +1364,7 @@ String generateFinderSelectorCommonBody(AbstractMethodHelper methodHelper, } } else { if (queryParam == null) { - oneParam[0] = CMPTemplateFormatter.none_; + oneParam[0] = JavaClassWriterHelper.none_; body.append(CMPTemplateFormatter.queryexecformatter.format(oneParam)); } else { oneParam[0] = queryParam; @@ -1414,7 +1398,7 @@ String generateFinderSelectorParamCheck(Method m, */ String generateQueryIgnoreCache() { - return CMPTemplateFormatter.none_; + return JavaClassWriterHelper.none_; } /** @@ -1437,7 +1421,7 @@ String generateQueryIgnoreCache() private String generateParamConvBody(Method m, String[] parameterEjbNames) { StringBuffer paramString = new StringBuffer(); - Class[] paramTypes = m.getParameterTypes(); + Class[] paramTypes = m.getParameterTypes(); int paramLength = paramTypes.length; MessageFormat mformat = null; String paramClassName = null; @@ -1464,7 +1448,7 @@ private String generateParamConvBody(Method m, String[] parameterEjbNames) { CMPTemplateFormatter.convertEJBObjectToPC_; paramString.append(mformat.format(threeParams)); } else { - paramString.append(CMPTemplateFormatter.param_ + i); + paramString.append(JavaClassWriterHelper.param_ + i); } // if primitive type, do some wrapping @@ -1477,13 +1461,17 @@ private String generateParamConvBody(Method m, String[] parameterEjbNames) { // else take the param as it is } else { - paramString.append(CMPTemplateFormatter.param_ + i); + paramString.append(JavaClassWriterHelper.param_ + i); } // normal delimiter - if (i < paramLength - 1) paramString.append( - CMPTemplateFormatter.paramSeparator_); + if (i < paramLength - 1) { + paramString.append( + JavaClassWriterHelper.paramSeparator_); + } } - } else return null; + } else { + return null; + } return paramString.toString(); } @@ -1502,15 +1490,14 @@ String[] getExceptionList(AbstractMethodHelper methodHelper, String mname, String[] paramTypeNames) { String[] rc = null; - Class[] paramTypes = null; + Class[] paramTypes = null; - Map methodNames = methodHelper.getMethodNames(); - Method m = (Method) methodNames.get(mname); + Map methodNames = methodHelper.getMethodNames(); + Method m = methodNames.get(mname); - boolean debug = logger.isLoggable(Logger.FINE); - if (debug) { - logger.fine("Processing method: " + mname); - logger.fine("Known method: " + m); + if (LOG.isLoggable(DEBUG)) { + LOG.log(DEBUG, "Processing method: " + mname); + LOG.log(DEBUG, "Known method: " + m); } if (m == null) { @@ -1527,11 +1514,9 @@ String[] getExceptionList(AbstractMethodHelper methodHelper, } try { - Class beanClass = Class.forName(abstractBean, true, loader); + Class beanClass = Class.forName(abstractBean, true, loader); m = beanClass.getMethod(mname, paramTypes); - if (debug) { - logger.fine("Found method: " + m); - } + LOG.log(DEBUG, "Found method: " + m); } catch (Exception e) { // Ignore. Generate what we know. @@ -1539,7 +1524,7 @@ String[] getExceptionList(AbstractMethodHelper methodHelper, } if (m != null) { - rc = CMPTemplateFormatter.getExceptionNames(m); + rc = JavaClassWriterHelper.getExceptionNames(m); } return rc; @@ -1565,8 +1550,8 @@ String[] getExceptionList( AbstractMethodHelper methodHelper, String mname ) { */ private String makeLiteral(String st) { return (StringHelper.isEmpty(st)) ? - CMPTemplateFormatter.escapedEmptyString_ : - CMPTemplateFormatter.paramInitializer_ + st; + JavaClassWriterHelper.escapedEmptyString_ : + JavaClassWriterHelper.paramInitializer_ + st; } /** @@ -1598,10 +1583,10 @@ String getSignaturesOfGeneratorClasses() * @return true if field type requires clone. */ boolean requireCloneOnGetAndSet(String fieldType) { - return (CMPTemplateFormatter.Date_.equals(fieldType) || - CMPTemplateFormatter.SqlDate_.equals(fieldType) || - CMPTemplateFormatter.SqlTime_.equals(fieldType) || - CMPTemplateFormatter.SqlTimestamp_.equals(fieldType)); + return (JavaClassWriterHelper.Date_.equals(fieldType) || + JavaClassWriterHelper.SqlDate_.equals(fieldType) || + JavaClassWriterHelper.SqlTime_.equals(fieldType) || + JavaClassWriterHelper.SqlTimestamp_.equals(fieldType)); } /** Verifies if this field type requires trim on set operation. @@ -1610,7 +1595,7 @@ boolean requireCloneOnGetAndSet(String fieldType) { */ boolean requireTrimOnSet(String fieldType) { // Strings require trim on set - boolean requireTrimOnSet = CMPTemplateFormatter.String_.equals(fieldType); + boolean requireTrimOnSet = JavaClassWriterHelper.String_.equals(fieldType); // do not trim if user has overriden it by specifying to support trailing spaces in pk columns // See https://glassfish.dev.java.net/issues/show_bug.cgi?id=7491 for more details return requireTrimOnSet && !SUPPORT_TRAILING_SPACES_IN_STRING_PK_COLUMNS; @@ -1658,13 +1643,10 @@ class FieldInfo { name = nameMapper.getEjbFieldForPersistenceField(pcname, pfn); String fname = StringHelper.getCapitalizedString(name); - getter = CMPTemplateFormatter.get_ + fname; - setter = CMPTemplateFormatter.set_ + fname; + getter = JavaClassWriterHelper.get_ + fname; + setter = JavaClassWriterHelper.set_ + fname; - boolean debug = logger.isLoggable(Logger.FINE); - if (debug) { - logger.fine("-Methods: " + getter + " " + setter); // NOI18N - } + LOG.log(DEBUG, () -> "-Methods: " + getter + " " + setter); isKey = pfe.isKey(); isPrimitive = model.isPrimitive(pcname, pfn); @@ -1678,9 +1660,7 @@ class FieldInfo { type = model.getFieldType(beanName, name); } - if (debug) { - logger.fine("Field: " + name + " " + type); // NOI18N - } + LOG.log(DEBUG, () -> "Field: " + name + " " + type); requireCloneOnGetAndSet = requireCloneOnGetAndSet(type); isGeneratedField = nameMapper.isGeneratedField(beanName, name); diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/LogHelperEJBCompiler.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/LogHelperEJBCompiler.java index 5b34cf59127..c34e0d20620 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/LogHelperEJBCompiler.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/LogHelperEJBCompiler.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.ejbc; -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 LogHelperEJBCompiler { protected static final String bundleName = "com.sun.jdo.spi.persistence.support.ejb.ejbc.Bundle"; // NOI18N - /** Return the logger for the ejbc 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/MappingGenerator.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/MappingGenerator.java index 52a22b9bbb5..b8142899ba1 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/MappingGenerator.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/MappingGenerator.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 @@ -34,7 +34,6 @@ import com.sun.jdo.spi.persistence.support.ejb.codegen.GeneratorException; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.DeploymentHelper; import com.sun.jdo.spi.persistence.utility.StringHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.BufferedInputStream; import java.io.File; @@ -43,6 +42,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; @@ -73,6 +73,9 @@ import org.netbeans.modules.schema2beans.Schema2BeansException; import org.netbeans.modules.schema2beans.ValidateException; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.WARNING; + /* * This class will generate mapping classes from sun-cmp-mappings.xml * and dbschema if they are available in the jar, or it will generate mapping @@ -88,11 +91,11 @@ public class MappingGenerator extends // DatabaseConstants.JAVA_TO_DB_FLAG directly. public static final String JAVA_TO_DB_FLAG = DatabaseConstants.JAVA_TO_DB_FLAG; - private static final String DBSCHEMA_EXTENSION = ".dbschema"; // NOI18N - private static final char DOT = '.'; // NOI18N + private static final String DBSCHEMA_EXTENSION = ".dbschema"; + private static final char DOT = '.'; /** The logger */ - private static final Logger logger = LogHelperEJBCompiler.getLogger(); + private static final Logger LOG = System.getLogger(MappingGenerator.class.getName()); private final EjbBundleDescriptorImpl bundle; @@ -154,24 +157,19 @@ public SchemaElement generateMapping( return null; } File cmpMappingFile = getSunCmpMappingFile(inputFilesPath); - boolean mappedBeans = !ignoreSunDeploymentDescriptors - && cmpMappingFile.exists(); - ResourceReferenceDescriptor cmpResource = checkOrCreateCMPResource( - mappedBeans); + boolean mappedBeans = !ignoreSunDeploymentDescriptors && cmpMappingFile.exists(); + ResourceReferenceDescriptor cmpResource = checkOrCreateCMPResource(mappedBeans); // Remember whether or not this mapping was created by Java2DB. - isJavaToDatabaseFlag = DeploymentHelper.isJavaToDatabase( - cmpResource.getSchemaGeneratorProperties()); + isJavaToDatabaseFlag = DeploymentHelper.isJavaToDatabase(cmpResource.getSchemaGeneratorProperties()); // We *must* get a vendor name if either the beans are not mapped, or // they are mapped and the javaToDatabase flag is set. - boolean mustHaveDBVendorName = - !mappedBeans || (mappedBeans && isJavaToDatabaseFlag); + boolean mustHaveDBVendorName = !mappedBeans || (mappedBeans && isJavaToDatabaseFlag); // Read deployment settings from the deployment descriptor // and CLI options. - Results deploymentArguments = getDeploymentArguments( - ctx, cmpResource, mustHaveDBVendorName); + Results deploymentArguments = getDeploymentArguments(ctx, cmpResource, mustHaveDBVendorName); dbVendorName = deploymentArguments.getDatabaseVendorName(); SchemaElement schema = null; if (mappedBeans) { @@ -191,10 +189,9 @@ public SchemaElement generateMapping( warning = I18NHelper.getMessage( messages, - "EXC_DisallowJava2DBUniqueTableNames", //NOI18N + "EXC_DisallowJava2DBUniqueTableNames", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle)); - logger.warning(warning); } } else if (deploymentArguments.hasJavaToDatabaseArgs()) { @@ -204,13 +201,13 @@ public SchemaElement generateMapping( warning = I18NHelper.getMessage( messages, - "EXC_DisallowJava2DBCLIOverrides", //NOI18N + "EXC_DisallowJava2DBCLIOverrides", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle)); - logger.warning(warning); } if (warning != null) { + LOG.log(WARNING, warning); ActionReport subActionReport = ctx.getActionReport().addSubActionsReport(); // Propagte warning to client side so that the deployer can see the warning. Java2DBProcessorHelper.warnUser(subActionReport, warning); @@ -225,7 +222,7 @@ public SchemaElement generateMapping( classout); // load real mapping model and jdo model in memory - Map mappingClasses = loadMappingClasses(sunCmpMappings, getClassLoader()); + Map mappingClasses = loadMappingClasses(sunCmpMappings, getClassLoader()); // Get schema from one of the mapping classes. // The mapping class element may be null if there is inconsistency @@ -234,20 +231,18 @@ public SchemaElement generateMapping( // no definition in the ejb-jar.xml. // So iterate over the mappings until the 1st non-null is found. MappingClassElement mc = null; - Iterator iter = mappingClasses.values().iterator(); + Iterator iter = mappingClasses.values().iterator(); while (iter.hasNext()) { - mc = (MappingClassElement)iter.next(); + mc = iter.next(); if (mc != null) { schema = SchemaElement.forName(mc.getDatabaseRoot()); break; } } - if (logger.isLoggable(Logger.FINE)){ - logger.fine("Loaded mapped beans for " // NOI18N + LOG.log(DEBUG, () -> "Loaded mapped beans for " + cmpResource.getJndiName() - + ", isJavaToDatabase=" + isJavaToDatabaseFlag); // NOI18N - } + + ", isJavaToDatabase=" + isJavaToDatabaseFlag); } else { // Generate mapping file and dbschema, since either // sun-cmp-mappings.xml does not exist (e.g. user didn't yet map) @@ -260,14 +255,10 @@ public SchemaElement generateMapping( if (!isVerifyFlag) { // save SunCmpMapping to sun-cmp-mappings.xml // in generated XML dir - writeSunCmpMappingFile(results.getMappingClasses(), - getSunCmpMappingFile(generatedXmlsPath)); - + writeSunCmpMappingFile(results.getMappingClasses(), getSunCmpMappingFile(generatedXmlsPath)); schema = results.getSchema(); - // save schema to dbschema file in generated XML dir writeSchemaFile(schema, classout); - setJavaToDatabase(cmpResource, true); } } @@ -292,22 +283,16 @@ public boolean isJavaToDatabase() { * @param cmpResource a ResourceReferenceDescriptor * @param value a string containing true or false */ - private void setJavaToDatabase(ResourceReferenceDescriptor - cmpResource, boolean value) { + private void setJavaToDatabase(ResourceReferenceDescriptor cmpResource, boolean value) { + LOG.log(DEBUG, () -> "set javatodb flag to " + value + " in cmpResource"); - if (logger.isLoggable(Logger.FINE)) { - logger.fine("set javatodb flag to " + value + " in cmpResource"); // NOI18N - } - - Properties schemaGeneratorProperties = cmpResource. - getSchemaGeneratorProperties(); + Properties schemaGeneratorProperties = cmpResource.getSchemaGeneratorProperties(); if (schemaGeneratorProperties == null) { schemaGeneratorProperties = new Properties(); cmpResource.setSchemaGeneratorProperties(schemaGeneratorProperties); } - schemaGeneratorProperties.setProperty(DatabaseConstants.JAVA_TO_DB_FLAG, - String.valueOf(value)); + schemaGeneratorProperties.setProperty(DatabaseConstants.JAVA_TO_DB_FLAG, String.valueOf(value)); isJavaToDatabaseFlag = value; } @@ -327,7 +312,7 @@ private SunCmpMappings getSunCmpMappings(File cmpMappingFile) if (cmpMappingFile.length() == 0) { throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.BeansFileSizeIsZero", bundle); // NOI18N + "CMG.BeansFileSizeIsZero", bundle); } try { @@ -341,18 +326,14 @@ private SunCmpMappings getSunCmpMappings(File cmpMappingFile) try { is.close(); } catch(Exception ex) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine(ex.toString()); - } + LOG.log(DEBUG, "Close failed.", ex); } } if (iasMapping != null) { try { iasMapping.close(); } catch(Exception ex) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine(ex.toString()); - } + LOG.log(DEBUG, "Close failed.", ex); } } } @@ -361,7 +342,7 @@ private SunCmpMappings getSunCmpMappings(File cmpMappingFile) sunCmpMapping.validate(); } catch (ValidateException ex) { throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.InvalidSunCmpMappingsFile", bundle, ex); // NOI18N + "CMG.InvalidSunCmpMappingsFile", bundle, ex); } return sunCmpMapping; @@ -373,15 +354,12 @@ private SunCmpMappings getSunCmpMappings(File cmpMappingFile) * @return a file of sun-cmp-mappings.xml */ private static File getSunCmpMappingFile(String filesPath) { - String cmpMappingFile = (new StringBuffer(filesPath). - append(File.separator). - append(MappingFile.DEFAULT_LOCATION_IN_EJB_JAR)).toString(); + String cmpMappingFile = filesPath + File.separator + MappingFile.DEFAULT_LOCATION_IN_EJB_JAR; // if the file contains directory structure, we need // to create those directories if they do not exist. if (cmpMappingFile.lastIndexOf(File.separatorChar) != -1) { - String dirs = cmpMappingFile.substring( - 0, cmpMappingFile.lastIndexOf(File.separatorChar)); + String dirs = cmpMappingFile.substring(0, cmpMappingFile.lastIndexOf(File.separatorChar)); File fileDirs = new File(dirs); if (!fileDirs.exists()) { fileDirs.mkdirs(); @@ -400,28 +378,25 @@ private static File getSunCmpMappingFile(String filesPath) { * @throws ConversionException * @throws Schema2BeansException */ - private void writeSunCmpMappingFile(Set mappingClasses, File cmpMappingFile) + private void writeSunCmpMappingFile(Set mappingClasses, File cmpMappingFile) throws IOException, ConversionException, Schema2BeansException { // Construct the input to MappingFile.fromMappingClasses(): a Map // object containing ejbName and MappingClassElement. Use the // elements of iteration and NameMapper to create the input for // MappingFile. - Map mappingMap = new HashMap(); + Map mappingMap = new HashMap<>(); AbstractNameMapper nameMapper = getNameMapper(); - Iterator iter = mappingClasses.iterator(); + Iterator iter = mappingClasses.iterator(); while (iter.hasNext()) { - MappingClassElement mappingClass = (MappingClassElement)iter.next(); - String ejbName = nameMapper.getEjbNameForPersistenceClass( - mappingClass.getName()); + MappingClassElement mappingClass = iter.next(); + String ejbName = nameMapper.getEjbNameForPersistenceClass(mappingClass.getName()); mappingMap.put(ejbName, mappingClass); } MappingFile mf = new MappingFile(); OutputStream sunCmpMapping = null; try { - sunCmpMapping = new FileOutputStream( - cmpMappingFile); - mf.fromMappingClasses(sunCmpMapping, mappingMap, - getConversionHelper()); + sunCmpMapping = new FileOutputStream(cmpMappingFile); + mf.fromMappingClasses(sunCmpMapping, mappingMap, getConversionHelper()); } catch (IOException ex) { throw ex; } finally { @@ -430,9 +405,7 @@ private void writeSunCmpMappingFile(Set mappingClasses, File cmpMappingFile) sunCmpMapping.close(); } } catch (IOException ex) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine(ex.toString()); - } + LOG.log(DEBUG, "Close failed.", ex); } } } @@ -443,25 +416,21 @@ private void writeSunCmpMappingFile(Set mappingClasses, File cmpMappingFile) * @param filePath a directory where *.dbschema is located * @throws IOException */ - private static void writeSchemaFile(SchemaElement schema, File filePath) - throws IOException { + private static void writeSchemaFile(SchemaElement schema, File filePath) throws IOException { OutputStream schemaStream = null; try { schemaStream = new FileOutputStream( - new File(filePath, NameUtil.getSchemaResourceName( - schema.getName().getName()))); + new File(filePath, NameUtil.getSchemaResourceName(schema.getName().getName()))); schema.save(schemaStream); } catch (IOException ex) { - throw ex; + throw ex; } finally { try { if (schemaStream != null) { schemaStream.close(); } } catch (IOException ex) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine(ex.toString()); - } + LOG.log(DEBUG, "Close failed.", ex); } } } @@ -598,6 +567,7 @@ private Results getDeploymentArguments( return new Results(useUniqueTableNames, dbVendorName, userPolicy, javaToDatabaseArgs); } + /** * Check if cmp resource is specified in the deployment descriptor. * If the beans are mapped (sun-cmp-mapping.xml is present), the cmp @@ -607,19 +577,15 @@ private Results getDeploymentArguments( * * @param mappedBeans true if beans are mapped in this module. * @throws GeneratorException if beans are mapped but cmp resource is not - * specified. + * specified. */ - private ResourceReferenceDescriptor checkOrCreateCMPResource( - boolean mappedBeans) - throws GeneratorException { - ResourceReferenceDescriptor cmpResource = - bundle.getCMPResourceReference(); + private ResourceReferenceDescriptor checkOrCreateCMPResource(boolean mappedBeans) throws GeneratorException { + ResourceReferenceDescriptor cmpResource = bundle.getCMPResourceReference(); if (mappedBeans) { if (cmpResource == null) { // If mapping exists, the cmpResource must specify a // database or a PMF JNDI name. - throw JDOCodeGeneratorHelper.createGeneratorException( - "EXC_MissingCMPResource", bundle); //NOI18N + throw JDOCodeGeneratorHelper.createGeneratorException("EXC_MissingCMPResource", bundle); } } else { if (cmpResource == null) { @@ -656,7 +622,7 @@ private void ensureDBSchemaExistence( throws DBException, SQLException, GeneratorException { String generatedSchemaName = getInfoHelper().getSchemaNameToGenerate(); - Set tables = new HashSet(); + Set tables = new HashSet<>(); int size = sunCmpMappings.sizeSunCmpMapping(); // Sweep through the mappings to check dbschema existence. If a @@ -689,7 +655,7 @@ private void ensureDBSchemaExistence( && dbschemaFile.canRead())) { throw new GeneratorException( I18NHelper.getMessage( - messages, "CMG.MissingDBSchema", // NOI18N + messages, "CMG.MissingDBSchema", bundle.getApplication().getRegistrationName(), JDOCodeGeneratorHelper.getModuleName(bundle), schemaName)); @@ -720,9 +686,9 @@ private void ensureDBSchemaExistence( schemaElement.setName(DBIdentifier.create(generatedSchemaName)); if(dmd.getDatabaseProductName().compareToIgnoreCase("MYSQL") == 0) { - outSchemaImpl.initTables(cp, new LinkedList(tables), new LinkedList(), true); + outSchemaImpl.initTables(cp, new LinkedList<>(tables), new LinkedList<>(), true); } else { - outSchemaImpl.initTables(cp, new LinkedList(tables), new LinkedList(), false); + outSchemaImpl.initTables(cp, new LinkedList<>(tables), new LinkedList<>(), false); } outstream = new FileOutputStream( new File(classout, @@ -737,7 +703,7 @@ private void ensureDBSchemaExistence( } catch (IOException ex) { // Catch FileNotFound, etc. throw JDOCodeGeneratorHelper.createGeneratorException( - "CMG.CannotSaveDBSchema", bundle, ex); // NOI18N + "CMG.CannotSaveDBSchema", bundle, ex); } finally { cp.closeConnection(); try { @@ -745,9 +711,7 @@ private void ensureDBSchemaExistence( outstream.close(); } } catch (IOException ex) { - if (logger.isLoggable(Logger.FINE)) { - logger.fine(ex.toString()); - } + LOG.log(DEBUG, "Close failed.", ex); } } } @@ -760,7 +724,7 @@ private void ensureDBSchemaExistence( * @param sunCmpMapping the SunCmpMapping element to check. * @param tables the Set to update. */ - private void addAllTables(SunCmpMapping sunCmpMapping, Set tables) { + private void addAllTables(SunCmpMapping sunCmpMapping, Set tables) { EntityMapping[] beans = sunCmpMapping.getEntityMapping(); for (EntityMapping bean : beans) { // Always add the table name. @@ -799,12 +763,9 @@ private void addAllTables(SunCmpMapping sunCmpMapping, Set tables) { * @param name the table name to add if it's a valid name. * @param tables the Set to update. */ - private void addTableName(String name, Set tables) { + private void addTableName(String name, Set tables) { if (!StringHelper.isEmpty(name)) { - if (logger.isLoggable(Logger.FINE)){ - logger.fine("Adding Table to Capture Set: " + name); // NOI18N - } - + LOG.log(DEBUG, "Adding Table to Capture Set: " + name); tables.add(name); } } diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/NameMapper.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/NameMapper.java index b911ef94091..cc1229d276c 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/NameMapper.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/NameMapper.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 */ -/* - * NameMapper.java - * - * Created on December 3, 2001, 5:09 PM - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; import com.sun.jdo.spi.persistence.utility.JavaTypeHelper; @@ -34,6 +29,7 @@ import org.glassfish.ejb.deployment.descriptor.CMRFieldInfo; import org.glassfish.ejb.deployment.descriptor.EjbBundleDescriptorImpl; import org.glassfish.ejb.deployment.descriptor.EjbCMPEntityDescriptor; +import org.glassfish.ejb.deployment.descriptor.EjbDescriptor; import org.glassfish.ejb.deployment.descriptor.IASEjbCMPEntityDescriptor; import org.glassfish.ejb.deployment.descriptor.PersistenceDescriptor; @@ -43,7 +39,7 @@ * package) which implements the abstract methods based on an IAS * implementation. * - * @author Rochelle Raccah + * @author Rochelle Raccah 2001 */ public class NameMapper extends com.sun.jdo.spi.persistence.support.ejb.model.util.NameMapper @@ -55,7 +51,7 @@ public class NameMapper extends private static String REMOTE_NAME = "REMOTE_NAME"; // NOI18N private final boolean _expandPCNames; - private Map _nameTypeToNameMap; + private Map _nameTypeToNameMap; /** * Signature with CVS keyword substitution for identifying the generated code @@ -87,14 +83,14 @@ public NameMapper (EjbBundleDescriptorImpl bundleDescriptor, private void initMap () { - Iterator iterator = getBundleDescriptor().getEjbs().iterator(); - Map ejbMap = new HashMap(); - Map persistenceClassMap = new HashMap(); - Set localNames = new HashSet(); - Set remoteNames = new HashSet(); - Map abstractSchemaMap = new HashMap(); + Iterator iterator = getBundleDescriptor().getEjbs().iterator(); + Map ejbMap = new HashMap<>(); + Map persistenceClassMap = new HashMap<>(); + Set localNames = new HashSet<>(); + Set remoteNames = new HashSet<>(); + Map abstractSchemaMap = new HashMap<>(); - _nameTypeToNameMap = new HashMap(); + _nameTypeToNameMap = new HashMap<>(); while (iterator.hasNext()) { @@ -123,25 +119,28 @@ private void initMap () } // puts a key-value pair in a map as long as the key is not null - private void safePut (Map map, Object key, Object value) + private void safePut (Map map, String key, String value) { - if ((key != null) && (map != null)) + if ((key != null) && (map != null)) { map.put(key, value); + } } // puts a value in a set as long as the object is not null - private void safeAdd (Set set, Object value) + private void safeAdd (Set set, String value) { - if ((value != null) && (set != null)) + if ((value != null) && (set != null)) { set.add(value); + } } - private Map getMap () { return _nameTypeToNameMap; } + private Map getMap () { return _nameTypeToNameMap; } /** Determines if the specified name represents an ejb. * @param name the fully qualified name to be checked * @return true if this name represents an ejb; * false otherwise. */ + @Override public boolean isEjbName (String name) { return mapContainsKey(EJB_NAME, name); @@ -152,30 +151,32 @@ public boolean isEjbName (String name) * @param name the name of the ejb * @return the EjbCMPEntityDescriptor which represents the ejb. */ - public EjbCMPEntityDescriptor getDescriptorForEjbName (String name) - { - Map ejbMap = (Map)getMap().get(EJB_NAME); + @Override + public EjbCMPEntityDescriptor getDescriptorForEjbName(String name) { + Map ejbMap = (Map) getMap().get(EJB_NAME); Object descriptor = ejbMap.get(name); - return (((descriptor != null) && - (descriptor instanceof EjbCMPEntityDescriptor)) ? - (EjbCMPEntityDescriptor)descriptor : null); + return (((descriptor != null) && (descriptor instanceof EjbCMPEntityDescriptor)) + ? (EjbCMPEntityDescriptor) descriptor + : null); } - private IASEjbCMPEntityDescriptor getIASDescriptorForEjbName (String name) - { + + private IASEjbCMPEntityDescriptor getIASDescriptorForEjbName(String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); - return (((descriptor != null) && - (descriptor instanceof IASEjbCMPEntityDescriptor)) ? - (IASEjbCMPEntityDescriptor)descriptor : null); + return (((descriptor != null) && (descriptor instanceof IASEjbCMPEntityDescriptor)) + ? (IASEjbCMPEntityDescriptor) descriptor + : null); } + /** Gets the name of the abstract bean class which corresponds to the * specified ejb name. * @param name the name of the ejb * @return the name of the abstract bean for the specified ejb */ + @Override public String getAbstractBeanClassForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -188,6 +189,7 @@ public String getAbstractBeanClassForEjbName (String name) * @param name the name of the ejb * @return the name of the key class for the ejb */ + @Override public String getKeyClassForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -201,6 +203,7 @@ public String getKeyClassForEjbName (String name) * @param schemaName the name of the abstract schema * @return the name of the ejb for the specified abstract schema */ + @Override public String getEjbNameForAbstractSchema (String schemaName) { Map abstractSchemaMap = (Map)getMap().get(ABSTRACT_SCHEMA_NAME); @@ -213,6 +216,7 @@ public String getEjbNameForAbstractSchema (String schemaName) * @param name the name of the ejb * @return the name of the abstract schema for the specified ejb */ + @Override public String getAbstractSchemaForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -226,6 +230,7 @@ public String getAbstractSchemaForEjbName (String name) * @param name the name of the ejb * @return the name of the concrete bean for the specified ejb */ + @Override public String getConcreteBeanClassForEjbName (String name) { IASEjbCMPEntityDescriptor descriptor = @@ -249,8 +254,9 @@ private String getQualifiedName (String classNameWithPackage, packageName = JavaTypeHelper.getPackageName(classNameWithPackage); - if (!StringHelper.isEmpty(packageName)) + if (!StringHelper.isEmpty(packageName)) { return packageName + '.' + classNameToQualify; + } } } @@ -262,6 +268,7 @@ private String getQualifiedName (String classNameWithPackage, * @param className the name of the persistence-capable * @return the name of the ejb for the specified persistence-capable */ + @Override public String getEjbNameForPersistenceClass (String className) { Map pcMap = (Map)getMap().get(PERSISTENCE_NAME); @@ -274,6 +281,7 @@ public String getEjbNameForPersistenceClass (String className) * @param name the name of the ejb * @return the name of the persistence-capable for the specified ejb */ + @Override public String getPersistenceClassForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -313,6 +321,7 @@ private boolean mapContainsKey (String stringIndex, String name) * @return true if this name represents a local interface; * false otherwise. */ + @Override public boolean isLocalInterface (String name) { return mapContainsKey(LOCAL_NAME, name); @@ -326,6 +335,7 @@ public boolean isLocalInterface (String name) * @param interfaceName the name of the local interface * @return the name of the ejb for the specified local interface */ + @Override public String getEjbNameForLocalInterface (String ejbName, String fieldName, String interfaceName) { @@ -342,6 +352,7 @@ public String getEjbNameForLocalInterface (String ejbName, * @param name the name of the ejb * @return the name of the local interface for the specified ejb */ + @Override public String getLocalInterfaceForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -354,6 +365,7 @@ public String getLocalInterfaceForEjbName (String name) * @return true if this name represents a remote interface; * false otherwise. */ + @Override public boolean isRemoteInterface (String name) { return mapContainsKey(REMOTE_NAME, name); @@ -367,6 +379,7 @@ public boolean isRemoteInterface (String name) * @param interfaceName the name of the remote interface * @return the name of the ejb for the specified remote interface */ + @Override public String getEjbNameForRemoteInterface (String ejbName, String fieldName, String interfaceName) { @@ -383,6 +396,7 @@ public String getEjbNameForRemoteInterface (String ejbName, * @param name the name of the ejb * @return the name of the remote interface for the specified ejb */ + @Override public String getRemoteInterfaceForEjbName (String name) { EjbCMPEntityDescriptor descriptor = getDescriptorForEjbName(name); @@ -416,6 +430,7 @@ private EjbCMPEntityDescriptor getRelatedEjbDescriptor ( * @return the name of the field in the ejb for the specified * persistence-capable field */ + @Override public String getEjbFieldForPersistenceField (String className, String fieldName) { @@ -429,6 +444,7 @@ public String getEjbFieldForPersistenceField (String className, * @return the name of the field in the persistence-capable for the * specified ejb field */ + @Override public String getPersistenceFieldForEjbField (String name, String fieldName) { return fieldName; diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/PersistenceManagerServiceImpl.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/PersistenceManagerServiceImpl.java index 5cddc88231a..69842a4824f 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/PersistenceManagerServiceImpl.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbc/PersistenceManagerServiceImpl.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,18 +15,10 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * PersistenceManagerServiceImpl.java - * - * Created on January 24, 2002 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbc; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.CMPHelper; -import com.sun.jdo.spi.persistence.support.sqlstore.ejb.LoggerFactoryiAS; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.SunContainerHelper; -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; import org.glassfish.ejb.spi.CMPService; import org.jvnet.hk2.annotations.Service; @@ -39,13 +32,10 @@ public class PersistenceManagerServiceImpl implements CMPService { // Initialize the appserver loggers. static { - LogHelper.registerLoggerFactory(new LoggerFactoryiAS()); + forceInit(SunContainerHelper.class); } - // Reference and force the initialization of the Sun specific - // implementation of the TransactionHelper and the ContainerHelper. - private static final Class helper = forceInit(SunContainerHelper.class); - + @Override public boolean isReady() { // Checks that SunContainerHelper regeistered with CMPHelper return CMPHelper.isContainerReady(); @@ -63,9 +53,8 @@ private static Class forceInit(Class klass) { try { Class.forName(klass.getName(), true, klass.getClassLoader()); } catch (ClassNotFoundException e) { - throw new AssertionError(e); // Can't happen + throw new AssertionError(e); } return klass; } - } diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/Bundle.properties b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/Bundle.properties index 6b614c950de..efc802d4b84 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/Bundle.properties +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/Bundle.properties @@ -48,19 +48,7 @@ # Message ID Range: JDO75000 - JDO75099 ############################################################################# -# {0} - bean name -# {1} - finder/selector method signature -# {2} - EJBQL query text -LOG_EJBQLCCompile=JDO75000: EJBQLC compile query\n\ -Bean: {0}\n\ -Method: {1}\n\ -EJBQL: {2} -# {0} - name of the compiler pass -LOG_EJBQLCStartPass=JDO75001: EJBQLC start {0} -# {0} - name of the compiler pass -LOG_EJBQLCDumpTree=JDO75002: EJBQLC dump tree {0} # {0} - String repr of the EJBQLC compile result -LOG_EJBQLCResult=JDO75003: EJBQLC result {0} ERR_MissingMethodInstance=JDO75004: Missing finder/selector method instance. # {0} - bean name # {1} - finder/selector method signature @@ -76,18 +64,6 @@ Method: {1}\n\ EJBQL: {2}\n\ Error: {3} -# {0} - bean name -# {1} - finder/selector method signature -# {2} - EJBQL query text -# {3} - detailed error message -EXC_EJBQLQueryInternalError=JDO75007: Fatal internal exception while parsing EJBQL:\n\ -Bean: {0}\n\ -Method: {1}\n\ -EJBQL: {2}\n\ -Error: {3} -JDO75007.diag.cause.1=Internal error in CMP module. -JDO75007.diag.check.1=This is an Unexpected Internal Error. Please contact Sun with your application and the complete error log message. - ERR_UnexpectedException=JDO75008: Unexpected exception during {0} ############################################################################# diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/EJBQLC.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/EJBQLC.java index 44cdbc9f01c..19fc2e5176e 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/EJBQLC.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/EJBQLC.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,21 +15,15 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * EJBQLC.java - * - * Created on November 12, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbqlc; import com.sun.jdo.api.persistence.model.Model; import com.sun.jdo.spi.persistence.support.ejb.model.util.NameMapper; import com.sun.jdo.spi.persistence.utility.generator.JavaClassWriterHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.Reader; import java.io.StringReader; +import java.lang.System.Logger; import java.lang.reflect.Method; import java.util.ResourceBundle; @@ -36,6 +31,8 @@ import antlr.TokenBuffer; +import static java.lang.System.Logger.Level.DEBUG; + /** * This class is the driver of the EJBQL compiler. It controls the compiler * passes: syntax analysis, semantic analysis and generation of the JDOQL query. @@ -48,8 +45,8 @@ * finder/selector method. The result is a JDOQLElements instance, that can be * used to construct a JDOQL query instance. * - * @author Michael Bouschen - * @author Shing Wai Chan + * @author Michael Bouschen 2001 + * @author Shing Wai Chan 2001 */ public class EJBQLC { @@ -63,7 +60,7 @@ public class EJBQLC protected EJBQLAST ast; /** The logger */ - private static Logger logger = LogHelperQueryCompilerEJB.getLogger(); + private static final Logger LOG = System.getLogger(EJBQLC.class.getName()); /** I18N support. */ protected final static ResourceBundle msgs = I18NHelper.loadBundle( @@ -72,7 +69,7 @@ public class EJBQLC /** * Signature with CVS keyword substitution for identifying the generated code */ - public static final String SIGNATURE = "$RCSfile: EJBQLC.java,v $ $Revision: 1.3 $"; //NOI18N + public static final String SIGNATURE = "$RCSfile: EJBQLC.java,v $ $Revision: 1.3 $"; /** * Constructor. @@ -101,68 +98,62 @@ public JDOQLElements compile(String ejbqlQuery, Method method, boolean finderNotSelector, String ejbName) throws EJBQLException { - boolean finer = logger.isLoggable(Logger.FINER); - boolean finest = logger.isLoggable(Logger.FINEST); - if (method == null) + if (method == null) { ErrorMsg.fatal(I18NHelper.getMessage(msgs, - "ERR_MissingMethodInstance")); //NOI18N - if ((ejbqlQuery == null) || ejbqlQuery.trim().length() == 0) + "ERR_MissingMethodInstance")); + } + if ((ejbqlQuery == null) || ejbqlQuery.isBlank()) { ErrorMsg.error(I18NHelper.getMessage(msgs, - "EXC_MissingEjbqlQueryText", ejbName, //NOI18N + "EXC_MissingEjbqlQueryText", ejbName, getMethodSignature(method))); - if (finer) - logger.finer("LOG_EJBQLCCompile", ejbName, //NOI18N - getMethodSignature(method), ejbqlQuery); + } + LOG.log(DEBUG, "EJBQLC compile query\n" + + "Bean: {0}\n" + + "Method: {1}\n" + + "EJBQL: {2}", + ejbName, getMethodSignature(method), ejbqlQuery); JDOQLElements result = null; TypeSupport typeSupport = new TypeSupport(model, nameMapper); ParameterSupport paramSupport = new ParameterSupport(method); - String pass = null; - try - { - // syntax analysis - pass = "syntax analysis"; //NOI18N - if (finer) logger.finer("LOG_EJBQLCStartPass", pass); //NOI18N + try { + LOG.log(DEBUG, "EJBQLC start syntax analysis"); EJBQLParser parser = createStringParser(ejbqlQuery); parser.query(); - ast = (EJBQLAST)parser.getAST(); - if (finest) logger.finest("LOG_EJBQLCDumpTree", ast.getTreeRepr("(AST)")); //NOI18N + ast = (EJBQLAST) parser.getAST(); + LOG.log(DEBUG, "EJBQLC dump tree {0}", ast.getTreeRepr("(AST)")); // semantic analysis - pass = "semantic analysis"; //NOI18N - if (finer) logger.finer("LOG_EJBQLCStartPass", pass); //NOI18N + LOG.log(DEBUG, "EJBQLC start semantic analysis"); Semantic semantic = new Semantic(); semantic.init(typeSupport, paramSupport, method, resultTypeMapping, finderNotSelector, ejbName); semantic.setASTFactory(EJBQLASTFactory.getInstance()); semantic.query(ast); ast = (EJBQLAST)semantic.getAST(); - if (finest) logger.finest("LOG_EJBQLCDumpTree", ast.getTreeRepr("(typed AST)")); //NOI18N + LOG.log(DEBUG, "EJBQLC dump tree {0}", ast.getTreeRepr("(typed AST)")); // JDOQL code generation - pass = "code generation"; //NOI18N - if (finer) logger.finer("LOG_EJBQLCStartPass", pass); //NOI18N + LOG.log(DEBUG, "EJBQLC start code generation"); JDOQLCodeGeneration codeGen = new JDOQLCodeGeneration(); codeGen.init(typeSupport, paramSupport); codeGen.setASTFactory(EJBQLASTFactory.getInstance()); codeGen.query(ast); result = codeGen.getJDOQLElements(); - if (finer) logger.finer("LOG_EJBQLCResult", result.toString()); //NOI18N - } - catch (EJBQLException ex) { + LOG.log(DEBUG, "EJBQLC result {0}", result); + } catch (EJBQLException ex) { // add EJB name, finder/selector, EJBQL to error message. - Object[] msgArgs = { ejbName, getMethodSignature(method), - ejbqlQuery, ex.getMessage() }; - ErrorMsg.error(I18NHelper.getMessage(msgs, - "EXC_InvalidEJBQLQuery", msgArgs)); //NOI18N - } - catch (Throwable t) { - Object[] msgArgs = { ejbName, getMethodSignature(method), - ejbqlQuery, t.toString() }; - // log a SEVERE message with nested exception - ErrorMsg.log(Logger.SEVERE, I18NHelper.getMessage(msgs, - "EXC_EJBQLQueryInternalError", msgArgs), t); //NOI18N + Object[] msgArgs = {ejbName, getMethodSignature(method), ejbqlQuery, ex.getMessage()}; + ErrorMsg.error(I18NHelper.getMessage(msgs, "EXC_InvalidEJBQLQuery", msgArgs)); + } catch (Throwable t) { + throw new EJBQLException(I18NHelper.getMessage( + msgs, "Fatal internal exception while parsing EJBQL:\n" + + "Bean: {0}\n" + + "Method: {1}\n" + + "EJBQL: {2}\n" + + "Error: {3}", + ejbName, getMethodSignature(method), ejbqlQuery, t), t); } // return the JDOQLElements instance representing the elements @@ -191,8 +182,9 @@ private EJBQLParser createStringParser(String text) */ private String getMethodSignature(Method m) { - if (m == null) - return ""; //NOI18N + if (m == null) { + return ""; + } return m.getReturnType().getName() + ' ' + m.getName() + JavaClassWriterHelper.parenleft_ + diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ErrorMsg.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ErrorMsg.java index 33e7bd2282b..242d291b710 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ErrorMsg.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ErrorMsg.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 */ -/* - * ErrorMsg.java - * - * Created on November 12, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbqlc; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; /** * This is a helper class to report error messages from the EJBQL compiler. - * @author Michael Bouschen - * @author Shing Wai Chan + * @author Michael Bouschen 2001 + * @author Shing Wai Chan 2001 */ public class ErrorMsg { @@ -39,9 +32,6 @@ public class ErrorMsg private final static ResourceBundle msgs = I18NHelper.loadBundle( ErrorMsg.class); - /** The logger */ - private static Logger logger = LogHelperQueryCompilerEJB.getLogger(); - /** * This method throws an EJBQLException indicating an user error. * @param line line number @@ -153,19 +143,4 @@ public static void fatal(String text, Throwable nested) throw new EJBQLException(I18NHelper.getMessage( msgs, "ERR_FatalInternalError", text), nested); //NOI18N } - - /** - * This method is called when we want to log an exception in a given level. - * Note that all other methods in this class do not log a stack trace. - * @param level log level - * @param text error message - * @param nested the cause of the error - * @exception EJBQLException describes the fatal internal error. - */ - public static void log(int level, String text, Throwable nested) - throws EJBQLException - { - logger.log(level, text, nested); - throw new EJBQLException(text, nested); - } } diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/LogHelperQueryCompilerEJB.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/LogHelperQueryCompilerEJB.java index 65803fdac17..a1dd352012a 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/LogHelperQueryCompilerEJB.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/LogHelperQueryCompilerEJB.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.ejbqlc; -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - /** * * @author Michael Bouschen @@ -39,10 +37,4 @@ public class LogHelperQueryCompilerEJB { protected static final String bundleName = "com.sun.jdo.spi.persistence.support.ejb.ejbqlc.Bundle"; // NOI18N - /** Return the logger for the sqlstore 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/ejbqlc/ParameterSupport.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ParameterSupport.java index a9b7e0ba758..e9be68a92f5 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ParameterSupport.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/ParameterSupport.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 */ -/* - * ParameterSupport.java - * - * Created on December 07, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbqlc; import java.lang.reflect.Method; @@ -36,7 +31,7 @@ public class ParameterSupport { /** The types of the parameters of the finder/selector method. */ - private Class[] parameterTypes; + private Class[] parameterTypes; /** * The EJB names corresponding to types of parameters of the @@ -66,7 +61,7 @@ public ParameterSupport(Method method) * starting with 1. * @return class instance representing the parameter type. */ - public Class getParameterType(String ejbqlParamDecl) + public Class getParameterType(String ejbqlParamDecl) { return getParameterType(getParamNumber(ejbqlParamDecl)); } @@ -77,7 +72,7 @@ public Class getParameterType(String ejbqlParamDecl) * so the method expects 1 as the number of the first parameter. * @return class instance representing the parameter type. */ - public Class getParameterType(int paramNumber) + public Class getParameterType(int paramNumber) { // InputParams are numbered starting at 1, so adjust for // array indexing. diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/SymbolTable.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/SymbolTable.java index 964f330e0b1..1bcab45b545 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/SymbolTable.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/SymbolTable.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 */ -/* - * SymbolTable.java - * - * Created on November 19, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbqlc; import java.util.HashMap; @@ -28,14 +23,14 @@ /** * The symbol table handling declared identifies. * - * @author Michael Bouschen + * @author Michael Bouschen 2001 */ public class SymbolTable { /** * The table of declared identifier (symbols). */ - protected Map symbols = new HashMap(); + protected Map symbols = new HashMap<>(); /** * This method adds the specified identifier to this SymbolTable. diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/TypeSupport.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/TypeSupport.java index 52e35c6c929..2909875507f 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/TypeSupport.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/ejbqlc/TypeSupport.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 */ -/* - * TypeSupport.java - * - * Created on November 22, 2001 - */ - package com.sun.jdo.spi.persistence.support.ejb.ejbqlc; import com.sun.jdo.api.persistence.model.Model; @@ -39,8 +34,8 @@ * as type info. The helper uses a model instance to access meta model info and * uses a NameMapper to map EJB names to JDO names and vice versa. * - * @author Michael Bouschen - * @author Shing Wai Chan + * @author Michael Bouschen 2001 + * @author Shing Wai Chan 2001 */ public class TypeSupport { @@ -105,13 +100,13 @@ public class TypeSupport public static final Object bigIntegerType = "java.math.BigInteger"; /** Set of names of numeric types. */ - protected static final Set numericTypes = new HashSet(); + protected static final Set numericTypes = new HashSet<>(); /** Set of names of numeric wrapper classes. */ - protected static final Set numericWrapperTypes = new HashSet(); + protected static final Set numericWrapperTypes = new HashSet<>(); /** Set of names of date and time types. */ - protected static final Set dateTimeTypes = new HashSet(); + protected static final Set dateTimeTypes = new HashSet<>(); /** Meta data access. */ protected Model model; @@ -142,10 +137,10 @@ public class TypeSupport numericWrapperTypes.add(floatClassType); numericWrapperTypes.add(doubleClassType); - dateTimeTypes.add("java.util.Date"); //NOI18N - dateTimeTypes.add("java.sql.Date"); //NOI18N - dateTimeTypes.add("java.sql.Time"); //NOI18N - dateTimeTypes.add("java.sql.Timestamp"); //NOI18N + dateTimeTypes.add("java.util.Date"); + dateTimeTypes.add("java.sql.Date"); + dateTimeTypes.add("java.sql.Time"); + dateTimeTypes.add("java.sql.Timestamp"); } /** @@ -172,7 +167,7 @@ public Object getTypeInfo(String name) /** * The method returns a type info by type name by class object. */ - public Object getTypeInfo(Class clazz) + public Object getTypeInfo(Class clazz) { return getTypeInfo(clazz.getName()); } @@ -294,22 +289,23 @@ public boolean isOrderableType(Object type) public static Object getPrimitiveType(Object type) { Object result = errorType; - if (type.equals(booleanClassType)) + if (type.equals(booleanClassType)) { result = booleanType; - else if (type.equals(integerClassType)) + } else if (type.equals(integerClassType)) { result = intType; - else if (type.equals(longClassType)) + } else if (type.equals(longClassType)) { result = longType; - else if (type.equals(floatClassType)) + } else if (type.equals(floatClassType)) { result = floatType; - else if (type.equals(doubleClassType)) + } else if (type.equals(doubleClassType)) { result = doubleType; - else if (type.equals(byteClassType)) + } else if (type.equals(byteClassType)) { result = byteType; - else if (type.equals(shortClassType)) + } else if (type.equals(shortClassType)) { result = shortType; - else if (type.equals(characterClassType)) + } else if (type.equals(characterClassType)) { result = charType; + } return result; } @@ -320,22 +316,23 @@ else if (type.equals(characterClassType)) public static Object getWrapperType(Object type) { Object result = errorType; - if (type.equals(booleanType)) + if (type.equals(booleanType)) { result = booleanClassType; - else if (type.equals(intType)) + } else if (type.equals(intType)) { result = integerClassType; - else if (type.equals(longType)) + } else if (type.equals(longType)) { result = longClassType; - else if (type.equals(floatType)) + } else if (type.equals(floatType)) { result = floatClassType; - else if (type.equals(doubleType)) + } else if (type.equals(doubleType)) { result = doubleClassType; - else if (type.equals(byteType)) + } else if (type.equals(byteType)) { result = byteClassType; - else if (type.equals(shortType)) + } else if (type.equals(shortType)) { result = shortClassType; - else if (type.equals(charType)) + } else if (type.equals(charType)) { result = characterClassType; + } return result; } @@ -346,14 +343,15 @@ else if (type.equals(charType)) public static Object binaryNumericPromotion(Object left, Object right) { if (isNumericType(left) && isNumericType(right)) { - if (left.equals(doubleType) || right.equals(doubleType)) + if (left.equals(doubleType) || right.equals(doubleType)) { return doubleType; - else if (left.equals(floatType) || right.equals(floatType)) + } else if (left.equals(floatType) || right.equals(floatType)) { return floatType; - else if (left.equals(longType) || right.equals(longType)) + } else if (left.equals(longType) || right.equals(longType)) { return longType; - else + } else { return intType; + } } return errorType; } @@ -388,17 +386,18 @@ public boolean isCompatibleWith(Object left, Object right) String rightTypeName = getTypeName(right); if (nameMapper.isLocalInterface(leftTypeName) && - nameMapper.isEjbName(rightTypeName)) + nameMapper.isEjbName(rightTypeName)) { rightTypeName = nameMapper.getLocalInterfaceForEjbName(rightTypeName); - else if (nameMapper.isRemoteInterface(leftTypeName) && - nameMapper.isEjbName(rightTypeName)) + } else if (nameMapper.isRemoteInterface(leftTypeName) && + nameMapper.isEjbName(rightTypeName)) { rightTypeName = nameMapper.getRemoteInterfaceForEjbName(rightTypeName); - else if (nameMapper.isLocalInterface(rightTypeName) && - nameMapper.isEjbName(leftTypeName)) + } else if (nameMapper.isLocalInterface(rightTypeName) && + nameMapper.isEjbName(leftTypeName)) { leftTypeName = nameMapper.getLocalInterfaceForEjbName(leftTypeName); - else if (nameMapper.isRemoteInterface(rightTypeName) && - nameMapper.isEjbName(leftTypeName)) + } else if (nameMapper.isRemoteInterface(rightTypeName) && + nameMapper.isEjbName(leftTypeName)) { leftTypeName = nameMapper.getRemoteInterfaceForEjbName(leftTypeName); + } // does not handle inheritance! return leftTypeName.equals(rightTypeName); @@ -431,8 +430,8 @@ public Object getFieldType(Object typeInfo, String fieldName) String typeName = getTypeName(typeInfo); if (!nameMapper.isEjbName(typeName)) { ErrorMsg.fatal(I18NHelper.getMessage( - msgs, "ERR_EjbNameExpected", //NOI18N - "TypeSupport.getFieldType", typeName)); //NOI18N + msgs, "ERR_EjbNameExpected", + "TypeSupport.getFieldType", typeName)); } String fieldType = model.getFieldType(typeName, fieldName); @@ -460,8 +459,8 @@ public Object getFieldInfo(Object typeInfo, String fieldName) String typeName = getTypeName(typeInfo); if (!nameMapper.isEjbName(typeName)) { ErrorMsg.fatal(I18NHelper.getMessage( - msgs, "ERR__EjbNameExpected", //NOI18N - "TypeSupport.getFieldInfo", typeName)); //NOI18N + msgs, "ERR__EjbNameExpected", + "TypeSupport.getFieldInfo", typeName)); } String pcClassName = nameMapper.getPersistenceClassForEjbName(typeName); String pcFieldName = nameMapper.getPersistenceFieldForEjbField( @@ -491,9 +490,9 @@ public Object getElementType(Object fieldInfo) if ((fieldInfo != null) && (fieldInfo instanceof RelationshipElement)) { String elementClass = ((RelationshipElement)fieldInfo).getElementClass(); return nameMapper.getEjbNameForPersistenceClass(elementClass); - } - else + } else { return null; + } } /** diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/enhancer/meta/EJBMetaDataModelImpl.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/enhancer/meta/EJBMetaDataModelImpl.java index 5be08e1fdb1..f7f381b8d0d 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/enhancer/meta/EJBMetaDataModelImpl.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/enhancer/meta/EJBMetaDataModelImpl.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 @@ -52,16 +53,19 @@ public EJBMetaDataModelImpl(Model model) //methods from ExtendedJDOMetaData, not in JDOMetaData + @Override public String[] getKnownClasses() throws JDOMetaDataUserException, JDOMetaDataFatalError { throw new UnsupportedOperationException(); } + @Override public String[] getKnownFields(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError { return getManagedFields(classPath); } + @Override public String getFieldType(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { final String className = pathToName(classPath); @@ -70,17 +74,20 @@ public String getFieldType(String classPath, String fieldName) return nameToPath(ftype); } + @Override public int getClassModifiers(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError { return Modifier.PUBLIC; } + @Override public int getFieldModifiers(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { final String className = pathToName(classPath); return model.getModifiers(model.getField(className, fieldName)); } + @Override public String getKeyClass(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError { final String className = pathToName(classPath); @@ -92,23 +99,27 @@ public String getKeyClass(String classPath) return nameToPath(keyClass); } + @Override public boolean isKnownNonManagedField(String classPath, String fieldName, String fieldSig) throws JDOMetaDataUserException, JDOMetaDataFatalError { return !isPersistentField(classPath, fieldName); } + @Override public boolean isManagedField(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { return (isPersistentField(classPath, fieldName) || isTransactionalField(classPath, fieldName)); } + @Override public boolean isKeyField(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { return isPrimaryKeyField(classPath, fieldName); } + @Override public boolean isPrimaryKeyField(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { @@ -122,6 +133,7 @@ public boolean isPrimaryKeyField(String classPath, String fieldName) } } + @Override public int getFieldFlags(String classPath, String fieldName) throws JDOMetaDataUserException, JDOMetaDataFatalError { if (!isManagedField(classPath, fieldName)) { @@ -161,6 +173,7 @@ public int getFieldFlags(String classPath, String fieldName) return MEDIATE_READ | MEDIATE_WRITE; } + @Override public int[] getFieldFlags(String classPath, String[] fieldNames) throws JDOMetaDataUserException, JDOMetaDataFatalError { final int n = (fieldNames != null ? fieldNames.length : 0); @@ -171,6 +184,7 @@ public int[] getFieldFlags(String classPath, String[] fieldNames) return flags; } + @Override public String[] getFieldType(String className, String[] fieldNames) throws JDOMetaDataUserException, JDOMetaDataFatalError { final int n = (fieldNames != null ? fieldNames.length : 0); @@ -181,6 +195,7 @@ public String[] getFieldType(String className, String[] fieldNames) return types; } + @Override public int[] getFieldNo(String classPath, String[] fieldNames) throws JDOMetaDataUserException, JDOMetaDataFatalError { final int n = (fieldNames != null ? fieldNames.length : 0); @@ -191,9 +206,10 @@ public int[] getFieldNo(String classPath, String[] fieldNames) return flags; } + @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++) { @@ -204,11 +220,13 @@ public String[] getKeyFields(String classPath) return (String[])keys.toArray(new String[keys.size()]); } + @Override public String getPersistenceCapableSuperClass(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError { return null; } + @Override public String getSuperKeyClass(String classPath) throws JDOMetaDataUserException, JDOMetaDataFatalError { return null; diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/DeploymentDescriptorModel.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/DeploymentDescriptorModel.java index 40ee2f05ff4..328a0b440be 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/DeploymentDescriptorModel.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/DeploymentDescriptorModel.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Contributors to the Eclipse Foundation + * Copyright (c) 2023, 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 @@ -175,7 +175,7 @@ protected void deleteFile(String className, String fileName) throws IOException * @return the class element for the specified className */ @Override - public Object getClass(final String className, final ClassLoader classLoader) { + public Class getClass(final String className, final ClassLoader classLoader) { String testClass = className; // translate the class name to corresponding ejb name's abstract @@ -221,7 +221,7 @@ public Object getClass(final String className, final ClassLoader classLoader) { public Object getConstructor(final String className, String[] argTypeNames) { if ((AbstractNameMapper.PRIMARY_KEY_FIELD == getPersistenceKeyClassType(className)) && Arrays.equals(argTypeNames, NO_ARGS)) { - return new MemberWrapper(className, null, Modifier.PUBLIC, (Class) getClass(className)); + return new MemberWrapper(className, null, Modifier.PUBLIC, getClass(className)); } Object returnObject = super.getConstructor(className, argTypeNames); if (returnObject instanceof Constructor) { @@ -257,17 +257,17 @@ public Object getMethod(final String className, final String methodName, String[ if (isPCClassName(className)) { if ((methodName.equals("readObject") && Arrays.equals(argTypeNames, getReadObjectArgs())) || (methodName.equals("writeObject") && Arrays.equals(argTypeNames, getWriteObjectArgs()))) { - returnObject = new MemberWrapper(methodName, Void.TYPE, Modifier.PRIVATE, (Class) getClass(className)); + returnObject = new MemberWrapper(methodName, Void.TYPE, Modifier.PRIVATE, getClass(className)); } } if ((AbstractNameMapper.UNKNOWN_KEY_CLASS == keyClassType) || (AbstractNameMapper.PRIMARY_KEY_FIELD == keyClassType)) { if (methodName.equals("equals") && Arrays.equals(argTypeNames, getEqualsArgs())) { returnObject = new MemberWrapper(methodName, Boolean.TYPE, Modifier.PUBLIC, - (Class) getClass(className)); + getClass(className)); } else if (methodName.equals("hashCode") && Arrays.equals(argTypeNames, NO_ARGS)) { returnObject = new MemberWrapper(methodName, Integer.TYPE, Modifier.PUBLIC, - (Class) getClass(className)); + getClass(className)); } } @@ -319,7 +319,7 @@ public Object getInheritedMethod(String className, String methodName, String[] a * @return the names of the field elements for the specified class */ @Override - public List getFields(final String className) { + public List getFields(final String className) { final EjbCMPEntityDescriptor descriptor = getCMPDescriptor(className); String testClass = className; if (descriptor != null) { @@ -371,7 +371,7 @@ public List getFields(final String className) { * @return the names of the field elements for the specified class */ @Override - public List getAllFields(String className) { + public List getAllFields(String className) { // If the class name corresponds to a pk field (which means that // there is no user defined primary key class, we don't want to // climb the inheritance hierarchy, we only process this class. @@ -600,7 +600,7 @@ public boolean isValidKeyType(String className, String fieldName) { * @see RuntimeModel#getMethod */ @Override - protected Class getTypeObject(Object element) { + protected Class getTypeObject(Object element) { Class type = super.getTypeObject(element); if ((element != null) && (element instanceof MemberWrapper)) { type = ((MemberWrapper) element).getType(); @@ -670,7 +670,7 @@ private MemberWrapper getFieldWrapper(String className, String fieldName) { // fieldType will be null - there is no such field } return fieldType == null ? null - : new MemberWrapper(fieldName, fieldType, Modifier.PRIVATE, (Class) getClass(className)); + : new MemberWrapper(fieldName, fieldType, Modifier.PRIVATE, getClass(className)); } @@ -691,7 +691,7 @@ private MemberWrapper updateFieldWrapper(MemberWrapper returnObject, String clas if (field.isKey() && (ejbName != null) && (nameMapper.getKeyClassTypeForEjbName(ejbName) == AbstractNameMapper.UNKNOWN_KEY_CLASS)) { returnObject = new MemberWrapper(ejbFieldName, Long.class, Modifier.PRIVATE, - (Class) getClass(className)); + getClass(className)); } else if ((field instanceof RelationshipElement) && nameMapper.isGeneratedEjbRelationship(ejbName, ejbFieldName)) { // Check if this is the auto-added field for 2 way managed rels @@ -705,19 +705,19 @@ private MemberWrapper updateFieldWrapper(MemberWrapper returnObject, String clas classType = java.util.HashSet.class; } else { String[] inverse = nameMapper.getEjbFieldForGeneratedField(ejbName, ejbFieldName); - classType = (Class) getClass(inverse[0]); + classType = getClass(inverse[0]); } if (classType != null) { returnObject = new MemberWrapper(ejbFieldName, classType, Modifier.PRIVATE, - (Class) getClass(className)); + getClass(className)); } } else if (ejbFieldName.startsWith(AbstractNameMapper.GENERATED_VERSION_FIELD_PREFIX) && nameMapper.isGeneratedField(ejbName, ejbFieldName)) { // Check if this is the auto-added version field. // If so, return a private field of type long. returnObject = new MemberWrapper(ejbFieldName, Long.TYPE, Modifier.PRIVATE, - (Class) getClass(className)); + getClass(className)); } else { return null; } diff --git a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/util/NameMapper.java b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/util/NameMapper.java index 326d19149a1..cad2154fc27 100644 --- a/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/util/NameMapper.java +++ b/appserver/persistence/cmp/support-ejb/src/main/java/com/sun/jdo/spi/persistence/support/ejb/model/util/NameMapper.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 */ -/* - * NameMapper.java - * - * Created on December 11, 2001, 9:51 AM - */ - package com.sun.jdo.spi.persistence.support.ejb.model.util; import com.sun.jdo.api.persistence.mapping.ejb.AbstractNameMapper; @@ -47,13 +42,13 @@ * also adds methods which are used during deployment time but not needed * during development time and therefore, not in the abstract superclass. * - * @author Rochelle Raccah + * @author Rochelle Raccah 2001 */ public abstract class NameMapper extends AbstractNameMapper { private EjbBundleDescriptorImpl _bundleDescriptor; - private Map _generatedRelToInverseRelMap; - private Map _relToInverseGeneratedRelMap; + private Map, List> _generatedRelToInverseRelMap; + private Map, List> _relToInverseGeneratedRelMap; /** Creates a new instance of NameMapper * @param bundleDescriptor the EjbBundleDescriptor which defines the @@ -68,31 +63,33 @@ protected NameMapper (EjbBundleDescriptorImpl bundleDescriptor) private void initGeneratedRelationshipMaps () { EjbBundleDescriptorImpl bundleDescriptor = getBundleDescriptor(); - Set relationships = bundleDescriptor.getRelationships(); + Set relationships = bundleDescriptor.getRelationships(); - _generatedRelToInverseRelMap = new HashMap(); - _relToInverseGeneratedRelMap = new HashMap(); + _generatedRelToInverseRelMap = new HashMap<>(); + _relToInverseGeneratedRelMap = new HashMap<>(); // during development time this code may attempt to get the // iterator even with no relationships, so protect it by a // null check if (relationships != null) { - Iterator iterator = relationships.iterator(); - List generatedRels = new ArrayList(); + Iterator iterator = relationships.iterator(); + List generatedRels = new ArrayList<>(); int counter = 0; // gather list of generated cmr fields by examining source and sink while (iterator.hasNext()) { RelationshipDescriptor relationship = - (RelationshipDescriptor)iterator.next(); + iterator.next(); - if (relationship.getSource().getCMRField() == null) + if (relationship.getSource().getCMRField() == null) { generatedRels.add(relationship); + } - if (relationship.getSink().getCMRField() == null) + if (relationship.getSink().getCMRField() == null) { generatedRels.add(relationship); + } } // now update the maps to contain this info @@ -100,7 +97,7 @@ private void initGeneratedRelationshipMaps () while (iterator.hasNext()) { RelationshipDescriptor relationship = - (RelationshipDescriptor)iterator.next(); + iterator.next(); RelationRoleDescriptor source = relationship.getSource(); String sourceEjbName = source.getOwner().getName(); String sourceCMRField = source.getCMRField(); @@ -110,12 +107,12 @@ private void initGeneratedRelationshipMaps () String ejbName = (sourceIsNull ? sourceEjbName : sinkEjbName); String otherEjbName = (sourceIsNull ? sinkEjbName : sourceEjbName); - List ejbField = Arrays.asList(new String[]{otherEjbName, + List ejbField = Arrays.asList(new String[]{otherEjbName, (sourceIsNull ? sink.getCMRField() : sourceCMRField)}); PersistenceDescriptor pDescriptor = ((EjbCMPEntityDescriptor) bundleDescriptor.getEjbByName(ejbName)). getPersistenceDescriptor(); - List generatedField = null; + List generatedField = null; String uniqueName = null; // make sure the user doesn't already have a field @@ -134,17 +131,24 @@ private void initGeneratedRelationshipMaps () } } - protected Map getGeneratedFieldsMap () - { + + @Override + protected Map, List> getGeneratedFieldsMap() { return _generatedRelToInverseRelMap; } - protected Map getInverseFieldsMap () { return _relToInverseGeneratedRelMap; } + + + @Override + protected Map, List> getInverseFieldsMap() { + return _relToInverseGeneratedRelMap; + } + // isCMPField does not return true for relationships, so we use getTypeFor private boolean hasField (PersistenceDescriptor persistenceDescriptor, String fieldName) { - Class fieldType = null; + Class fieldType = null; try { @@ -180,6 +184,7 @@ abstract public EjbCMPEntityDescriptor getDescriptorForEjbName ( * @return the key class type, one of {@link #USER_DEFINED_KEY_CLASS}, * {@link #PRIMARY_KEY_FIELD}, or {@link #UNKNOWN_KEY_CLASS} */ + @Override public int getKeyClassTypeForEjbName (String name) { String keyClass = getKeyClassForEjbName(name); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/CodeGeneration.g b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/CodeGeneration.g index bafb724720f..5742c7735dd 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/CodeGeneration.g +++ b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/CodeGeneration.g @@ -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 @@ -23,10 +24,11 @@ header { package com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc; - - import java.util.*; + + import java.lang.System.Logger; import java.lang.reflect.Field; import java.lang.IllegalAccessException; + import java.util.*; import com.sun.jdo.api.persistence.support.JDOFatalUserException; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceCapable; @@ -36,7 +38,6 @@ header import org.glassfish.persistence.common.I18NHelper; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; - import com.sun.jdo.spi.persistence.utility.logging.Logger; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.TypeTable; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.Type; @@ -46,6 +47,8 @@ header import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.NumericWrapperClassType; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.NumberType; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.StringType; + + import static java.lang.System.Logger.Level.TRACE; } /** @@ -58,16 +61,16 @@ header * @version 0.1 */ class CodeGeneration extends TreeParser; - + options { importVocab = JQL; - ASTLabelType = "JQLAST"; //NOI18N + ASTLabelType = "JQLAST"; } { /** Name of the USE_IN property. */ - public static final String USE_IN_PROPERTY = + public static final String USE_IN_PROPERTY = "com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.USE_IN"; /** */ @@ -76,36 +79,44 @@ options /** * I18N support */ - protected final static ResourceBundle messages = - I18NHelper.loadBundle(CodeGeneration.class); + protected final static ResourceBundle messages = I18NHelper.loadBundle(CodeGeneration.class); + + /** The logger */ + private static final Logger LOG = System.getLogger(CodeGeneration.class.getName()); + + /** + * Defines the SQL wildcard character to be used in wildcard pattern + * (string methods startsWith and endsWith). + */ + protected static final String WILDCARD_PATTERN = "%"; /** * The persistence manager the query object is connected to. */ protected PersistenceManager pm; - + /** * type table */ protected TypeTable typetab; - + /** * query parameter table */ protected ParameterTable paramtab; - + /** * */ protected ErrorMsg errorMsg; - + /** * prefetchEnabled flag for RetrieveDesc. */ protected boolean prefetchEnabled; - + /** - * The RetrieveDesc for the candidate class. + * The RetrieveDesc for the candidate class. * Code gen for the CLASS_DEF AST will initilaized this variable. * Code gen for the filter expression will add the constraints. */ @@ -113,31 +124,22 @@ options /** * rd2TagMap maps RetrieveDesc to tags. A tag is either the variable name or - * the navigation path that used to create a new RetrieveDesc. This info is - * needed to identify whether two different RetrieveDescs denote the same + * the navigation path that used to create a new RetrieveDesc. This info is + * needed to identify whether two different RetrieveDescs denote the same * variable or relationship. */ protected Map rd2TagMap; - /** - * Set of RetrieveDescs. CodeGeneration uses this set to prevent multiple + /** + * Set of RetrieveDescs. CodeGeneration uses this set to prevent multiple * addConstraint calls for the RetrieveDescs denoting a variable. */ protected Set boundRetrieveDescs; - /** The logger */ - private static Logger logger = LogHelperQueryCompilerJDO.getLogger(); - - /** - * Defines the SQL wildcard character to be used in wildcard pattern - * (string methods startsWith and endsWith). - */ - protected static final String WILDCARD_PATTERN = "%"; //NOI18N - /** * */ - public void init(PersistenceManager pm, TypeTable typetab, + public void init(PersistenceManager pm, TypeTable typetab, ParameterTable paramtab, ErrorMsg errorMsg, boolean prefetchEnabled) { @@ -149,21 +151,21 @@ options this.rd2TagMap = new HashMap(); this.boundRetrieveDescs = new HashSet(); } - + /** * */ public void reportError(RecognitionException ex) { - errorMsg.fatal("CodeGeneration error", ex); //NOI18N + errorMsg.fatal("CodeGeneration error", ex); } /** * */ public void reportError(String s) { - errorMsg.fatal("CodeGeneration error: " + s); //NOI18N + errorMsg.fatal("CodeGeneration error: " + s); } - + /** * Returns the RetrieveDesc that represents the current query. */ @@ -177,13 +179,13 @@ options /** * Helper method for checkRetrieveDesc handling operators & and &&. */ - protected void checkAndOpRetrieveDesc(JQLAST op, JQLAST left, + protected void checkAndOpRetrieveDesc(JQLAST op, JQLAST left, JQLAST right, Map usedRD) throws RecognitionException { if ((right.getType() == CONTAINS) || (right.getType() == NOT_CONTAINS)) { // If right is a CONTAINS clause, start analysing the right expr. - // This ensures that the lft expression can reuse the RD defined + // This ensures that the lft expression can reuse the RD defined // for the variable from the contains clause checkRetrieveDesc(right, usedRD); checkRetrieveDesc(left, usedRD); @@ -191,11 +193,11 @@ options else { checkRetrieveDesc(left, usedRD); - checkRetrieveDesc(right, usedRD); + checkRetrieveDesc(right, usedRD); } - op.setRetrieveDesc(getCommonRetrieveDesc(left, right)); + op.setRetrieveDesc(getCommonRetrieveDesc(left, right)); } - + /** * Check the attached RetrieveDesc of the specified binary operation and its operands. */ @@ -232,11 +234,11 @@ options { // case 3b: left and right RetrieveDesc are NOT identical // check navigation: - rd = getCommonRetrieveDescHelper(leftRD, findNavigationSource(left), + rd = getCommonRetrieveDescHelper(leftRD, findNavigationSource(left), rightRD, findNavigationSource(right)); // use leftRD as default - if (rd == null) + if (rd == null) { rd = leftRD; } @@ -247,34 +249,34 @@ options /** Helper method for getCommonRetrieveDesc used to check navigation. */ protected RetrieveDesc getCommonRetrieveDescHelper( - RetrieveDesc leftRD, JQLAST leftNavSrc, + RetrieveDesc leftRD, JQLAST leftNavSrc, RetrieveDesc rightRD, JQLAST rightNavSrc) { RetrieveDesc rd = null; String leftPath = (String)rd2TagMap.get(leftRD); String rightPath = (String)rd2TagMap.get(rightRD); - RetrieveDesc leftNavSrcRD = + RetrieveDesc leftNavSrcRD = (leftNavSrc == null) ? null : leftNavSrc.getRetrieveDesc(); - String leftNavSrcPath = + String leftNavSrcPath = (leftNavSrcRD == null ) ? null: (String)rd2TagMap.get(leftNavSrcRD); - RetrieveDesc rightNavSrcRD = + RetrieveDesc rightNavSrcRD = (rightNavSrc == null) ? null : rightNavSrc.getRetrieveDesc(); - String rightNavSrcPath = + String rightNavSrcPath = (rightNavSrcRD == null) ? null : (String)rd2TagMap.get(rightNavSrcRD); if ((leftNavSrcPath != null) && leftNavSrcPath.equals(rightPath)) { - // case I: left operand is a navigation and + // case I: left operand is a navigation and // the navigation source is equal to the right operand rd = rightRD; } else if ((rightNavSrcPath != null) && rightNavSrcPath.equals(leftPath)) { - // case II: right operand is a navigation and + // case II: right operand is a navigation and // the navigation source is equal to the left operand rd = leftRD; } - else if ((leftNavSrcPath != null) && (rightNavSrcPath != null) && + else if ((leftNavSrcPath != null) && (rightNavSrcPath != null) && leftNavSrcPath.equals(rightNavSrcPath)) { // case III: both operands are navigations and have the same source @@ -287,17 +289,17 @@ options JQLAST rightConstraint = findNavigationSourceOfBoundVariable(rightNavSrc); if ((leftConstraint != null) && (rightConstraint != null)) { - rd = getCommonRetrieveDescHelper(leftRD, leftConstraint, + rd = getCommonRetrieveDescHelper(leftRD, leftConstraint, rightRD, rightConstraint); } else if ((leftConstraint == null) && (rightConstraint != null)) { - rd = getCommonRetrieveDescHelper(leftRD, leftNavSrc, + rd = getCommonRetrieveDescHelper(leftRD, leftNavSrc, rightRD, rightConstraint); } else if ((leftConstraint != null) && (rightConstraint == null)) { - rd = getCommonRetrieveDescHelper(leftRD, leftConstraint, + rd = getCommonRetrieveDescHelper(leftRD, leftConstraint, rightRD, rightNavSrc); } } @@ -305,14 +307,14 @@ options } /** - * Helper method to support getting the common RetrieveDesc for operands + * Helper method to support getting the common RetrieveDesc for operands * taking three arguments such as like with escape, substring, indexOf. */ protected RetrieveDesc getCommonRetrieveDesc(JQLAST arg1, JQLAST arg2, JQLAST arg3) { RetrieveDesc rd = null; if (arg3 == null) { - // Just call the regular method for binray ops, + // Just call the regular method for binray ops, // if the third argument is not specified. rd = getCommonRetrieveDesc(arg1, arg2); } @@ -321,10 +323,10 @@ options getCommonRetrieveDesc(arg2, arg3); // Now check the first and the second arg. rd = getCommonRetrieveDesc(arg1, arg2); - // Propagate the common RetrieveDesc to the third arg. + // Propagate the common RetrieveDesc to the third arg. // This is important, if arg two and three are literals. - // Then the first call checking arg2 and arg3 did not attach any - // RetrieveDesc. The second call checking arg1 and arg2 might have + // Then the first call checking arg2 and arg3 did not attach any + // RetrieveDesc. The second call checking arg1 and arg2 might have // propagated a rd from arg1 to arg2. So this propagateRetrieveDesc // call propagates this rd to arg3, too. propagateRetrieveDesc(arg3, rd); @@ -332,21 +334,21 @@ options return rd; } - /** - * Helper method to support getting the common RetrieveDesc for object + /** + * Helper method to support getting the common RetrieveDesc for object * comparison operators. */ protected RetrieveDesc getObjectComparisonRetrieveDesc(JQLAST left, JQLAST right) { RetrieveDesc rd = null; - if ((left.getType() == NAVIGATION) && + if ((left.getType() == NAVIGATION) && (right.getType() == VALUE) && (right.getValue() == null)) { // case obj.relship == null // take the RetrieveDesc from the navigation source rd = ((JQLAST)left.getFirstChild()).getRetrieveDesc(); } - else if ((left.getType() == VALUE) && (left.getValue() == null) && + else if ((left.getType() == VALUE) && (left.getValue() == null) && (right.getType() == NAVIGATION)) { // case null == obj.relship @@ -390,9 +392,9 @@ options return null; } - /** - * If the specifid node is a bound variable return the navigation source of - * it's collection. + /** + * If the specifid node is a bound variable return the navigation source of + * it's collection. */ protected JQLAST findNavigationSourceOfBoundVariable(JQLAST tree) { @@ -400,7 +402,7 @@ options return findNavigationSource((JQLAST)tree.getFirstChild()); return null; } - + /** * Attach the specified RetrieveDesc to all JQLAST node of the ast subtree, * that do not have a RetrieveDesc attached. @@ -411,8 +413,8 @@ options { ast.setRetrieveDesc(rd); } - for (JQLAST node = (JQLAST)ast.getFirstChild(); - node != null; + for (JQLAST node = (JQLAST)ast.getFirstChild(); + node != null; node = (JQLAST)node.getNextSibling()) { propagateRetrieveDesc(node, rd); @@ -424,7 +426,7 @@ options */ protected Object getZeroValue(Type type) { - return (type instanceof NumberType) ? + return (type instanceof NumberType) ? ((NumberType)type).getValue(new Integer(0)) : null; } @@ -434,26 +436,26 @@ options */ protected Object getMinusOneValue(Type type) { - return (type instanceof NumberType) ? + return (type instanceof NumberType) ? ((NumberType)type).getValue(new Integer(-1)) : null; } - + /** - * Returns -value. - * The method assumes that the passed argument is a numeric wrapper class object. - * If so it negates the wrapped numeric value and wraps the negated value into a + * Returns -value. + * The method assumes that the passed argument is a numeric wrapper class object. + * If so it negates the wrapped numeric value and wraps the negated value into a * numeric wrapper class object. */ protected Object negate(Object value, Type type) { - return (type instanceof NumberType) ? + return (type instanceof NumberType) ? ((NumberType)type).negate((Number)value) : null; } /** - * Returns the boolean operation of the equivalent relational expression + * Returns the boolean operation of the equivalent relational expression * with swapped arguments. * expr1 > expr2 <=> expr2 < expr1 */ @@ -485,18 +487,18 @@ options } /** - * Code generation for a comparison of the form field relop value, + * Code generation for a comparison of the form field relop value, * where field denotes a non relationship field - * This method checks for null values and generates OP_NULL / OP_NOTNULL constraints + * This method checks for null values and generates OP_NULL / OP_NOTNULL constraints * in the case of field relop null */ - protected void generateSimpleFieldValueComparison(RetrieveDesc rd, String name, + protected void generateSimpleFieldValueComparison(RetrieveDesc rd, String name, int operation, Object value) { if (value != null) { rd.addConstraint(name, operation, value); - } + } else if (operation == RetrieveDesc.OP_EQ) { rd.addConstraint(name, RetrieveDesc.OP_NULL, null); @@ -507,20 +509,20 @@ options } else { - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.generatesimplefieldvaluecomparison.invalidvalue")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.generatesimplefieldvaluecomparison.invalidvalue")); } } /** - * Code generation for a comparison of the form + * Code generation for a comparison of the form * dbvalue relop constant - * where dbvalue denotes an object in the database such as + * where dbvalue denotes an object in the database such as * - this * - the result of a relationship navigation * - variable access * and constant is a constant value at query compile time (e.g. a literal) */ - protected void generateDbValueConstantComparison(RetrieveDesc rd, ClassType objectType, + protected void generateDbValueConstantComparison(RetrieveDesc rd, ClassType objectType, int operation, Object value, Type valueType) { int booleanOp = getKeyFieldsComparisonBooleanOp(operation); @@ -541,19 +543,19 @@ options } /** - * Code generation for a comparison of the form + * Code generation for a comparison of the form * dbvalue relop dbvalue - * where dbvalue denotes an object in the database such as + * where dbvalue denotes an object in the database such as * - this * - the result of a relationship navigation * - variable access */ - protected void generateDbValueDbValueComparison(RetrieveDesc leftRD, ClassType leftType, int operation, + protected void generateDbValueDbValueComparison(RetrieveDesc leftRD, ClassType leftType, int operation, RetrieveDesc rightRD, ClassType rightType) { int booleanOp = getKeyFieldsComparisonBooleanOp(operation); - - // Note, this code assumes that both operands are of class types that have + + // Note, this code assumes that both operands are of class types that have // the same key fields. Thus take the list of key field names of the left side. List leftKeyFieldNames = leftType.getKeyFieldNames(); for (Iterator i = leftKeyFieldNames.iterator(); i.hasNext();) @@ -566,11 +568,11 @@ options } /** - * Code generation for a comparison of the form + * Code generation for a comparison of the form * parameter relop constantValue */ protected void generateParameterValueComparison(RetrieveDesc rd, - String paramName, + String paramName, int operation, Object value) { if (value != null) @@ -579,7 +581,7 @@ options rd.addConstraint(null, RetrieveDesc.OP_PARAMETER, paramtab.getParameterInfoForParamName(paramName)); rd.addConstraint(null, operation, null); - } + } else if (operation == RetrieveDesc.OP_EQ) { rd.addConstraint(null, RetrieveDesc.OP_PARAMETER, @@ -594,7 +596,7 @@ options } else { - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.generateparametervaluecomparison.invalidvalue")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.generateparametervaluecomparison.invalidvalue")); } } @@ -613,7 +615,7 @@ options return RetrieveDesc.OP_OR; } errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.codegeneration.getkeyfieldscomparisonbooleanop.invalidobj", //NOI18N + "jqlc.codegeneration.getkeyfieldscomparisonbooleanop.invalidobj", String.valueOf(operation))); return 0; } @@ -631,10 +633,10 @@ options PersistenceCapable pc = (PersistenceCapable)object; int index = fieldInfo.getFieldNumber(); StateManager stateManager = pc.jdoGetStateManager(); - + if (stateManager != null) { - // call stateManager.prepareGetField to allow the stateManager + // call stateManager.prepareGetField to allow the stateManager // to mediate the field access stateManager.prepareGetField(index); } @@ -647,18 +649,18 @@ options { value = fieldInfo.getField().get(object); } - catch (IllegalAccessException e) + catch (IllegalAccessException e) { throw new JDOFatalUserException( - I18NHelper.getMessage(messages, "jqlc.codegeneration.fieldaccess.illegal", //NOI18N - fieldName, (object==null ? "null" : object.toString())), e); //NOI18N + I18NHelper.getMessage(messages, "jqlc.codegeneration.fieldaccess.illegal", + fieldName, (object==null ? "null" : object.toString())), e); } } return value; } - + /** - * This method checks whether the result RetrieveDesc needs a DISTINCT clause or not. + * This method checks whether the result RetrieveDesc needs a DISTINCT clause or not. * @param query the query AST */ protected void handleDistinct(JQLAST query, boolean distinct) @@ -666,15 +668,15 @@ options // candidateRD is null in the case of false filter if (candidateRD == null) return; - + if (distinct) candidateRD.addResult(RetrieveDesc.OP_DISTINCT, FieldTypeEnumeration.NOT_ENUMERATED); } /** * This method returns true if the specified node is an AST that represensts a value. - * It returns false for CONTAINS/NOT_CONTAINS nodes and boolean operations that include - * only CONTAINS nodes + * It returns false for CONTAINS/NOT_CONTAINS nodes and boolean operations that include + * only CONTAINS nodes */ protected boolean pushesValueOnStack(JQLAST node) { @@ -703,11 +705,10 @@ options protected RetrieveDesc createRetrieveDesc(String pathExpr, ClassType classType) { RetrieveDesc rd = pm.getRetrieveDesc(classType.getJavaClass()); - if (logger.isLoggable(Logger.FINEST)) - { + if (LOG.isLoggable(TRACE)) { rd = new DebugRetrieveDesc(rd); - logger.finest("LOG_JQLCDumpRD", "create " + JQLAST.getRetrieveDescRepr(rd)); //NOI18N - } + LOG.log(TRACE, "createRetrieveDesc " + JQLAST.getRetrieveDescRepr(rd)); + } rd2TagMap.put(rd, pathExpr); rd.setNavigationalId(pathExpr); return rd; @@ -724,7 +725,7 @@ options { this.wrapped = wrapped; } - + public RetrieveDesc unwrap(RetrieveDesc rd) { if (rd instanceof DebugRetrieveDesc) @@ -732,30 +733,25 @@ options return rd; } - // methods from RetrieveDesc + // methods from RetrieveDesc public void addResult(String name, RetrieveDesc desc, boolean projection) { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + ".addResult(" + //NOI18N - name + ", " + JQLAST.getRetrieveDescRepr(desc) + ", " + //NOI18N - projection + ")"); //NOI18N - desc = unwrap(desc); - wrapped.addResult(name, desc, projection); + + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + ".addResult(" + + name + ", " + JQLAST.getRetrieveDescRepr(desc) + ", " + + projection + ")"); + wrapped.addResult(name, unwrap(desc), projection); } - + public void addResult(int opCode, int resultType) { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + ".addResult(" + //NOI18N - opCode + ", " + resultType + ")"); //NOI18N - wrapped.addResult(opCode, resultType); + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + ".addResult(" + opCode + ", " + resultType + ")"); + wrapped.addResult(opCode, resultType); } - + public void addConstraint(String name, int operation, Object value) { - String thirdArgRepr = null; + final String thirdArgRepr; if (value instanceof RetrieveDesc) { RetrieveDesc foreignConstraint = (RetrieveDesc)value; @@ -766,49 +762,38 @@ options { thirdArgRepr = (value == null) ? "null" : value.toString(); } - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + //NOI18N - name + ", " + operation + ", " + thirdArgRepr + ")"); //NOI18N + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + + name + ", " + operation + ", " + thirdArgRepr + ")"); wrapped.addConstraint(name, operation, value); } public void addConstraint(String name, RetrieveDesc foreignConstraint) { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + //NOI18N - name + ", " + JQLAST.getRetrieveDescRepr(foreignConstraint) + ")"); //NOI18N - foreignConstraint = unwrap(foreignConstraint); - wrapped.addConstraint(name, foreignConstraint); + LOG.log(TRACE, () -> + JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + + name + ", " + JQLAST.getRetrieveDescRepr(foreignConstraint) + ")"); + wrapped.addConstraint(name, unwrap(foreignConstraint)); } public void addConstraint(String name, int operator, RetrieveDesc foreignConstraint, String foreignFieldName) { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + //NOI18N - name + ", " + operator + ", " + JQLAST.getRetrieveDescRepr(foreignConstraint) + //NOI18N - ", " + foreignFieldName + ")"); //NOI18N - foreignConstraint = unwrap(foreignConstraint); - wrapped.addConstraint(name, operator, foreignConstraint, foreignFieldName); + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + ".addConstraint(" + + name + ", " + operator + ", " + JQLAST.getRetrieveDescRepr(foreignConstraint) + + ", " + foreignFieldName + ")"); + wrapped.addConstraint(name, operator, unwrap(foreignConstraint), foreignFieldName); } - + public void setNavigationalId(Object navigationalId) - { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + - ".setNavigationalId(" + navigationalId + ")"); //NOI18N - wrapped.setNavigationalId(navigationalId); + { + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + + ".setNavigationalId(" + navigationalId + ")"); + wrapped.setNavigationalId(navigationalId); } public void setPrefetchEnabled(boolean prefetchEnabled) { - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpRD", //NOI18N - JQLAST.getRetrieveDescRepr(this) + - ".setPrefetchEnabled(" + prefetchEnabled + ")"); //NOI18N + LOG.log(TRACE, () -> JQLAST.getRetrieveDescRepr(this) + + ".setPrefetchEnabled(" + prefetchEnabled + ")"); wrapped.setPrefetchEnabled(prefetchEnabled); } @@ -825,18 +810,19 @@ query : q:. { prepareRetrieveDescs(q); - if (logger.isLoggable(Logger.FINEST)) - logger.finest("LOG_JQLCDumpTree", q.getTreeRepr("RD annotated AST")); //NOI18N + if (LOG.isLoggable(TRACE)) { + LOG.log(TRACE, q.getTreeRepr("RD annotated AST")); + } doCodeGen(q); } ; doCodeGen -{ +{ boolean distinct = false; } : #( q:QUERY - candidateClass + candidateClass parameters variables ordering @@ -853,8 +839,8 @@ doCodeGen // ---------------------------------- candidateClass -{ - errorMsg.setContext("setCandidates"); //NOI18N +{ + errorMsg.setContext("setCandidates"); } : c:CLASS_DEF // Note, DISTINCT is added by handleDistinct called in the rule query @@ -864,8 +850,8 @@ candidateClass // ---------------------------------- parameters -{ - errorMsg.setContext("declareParameters"); //NOI18N +{ + errorMsg.setContext("declareParameters"); } : ( declareParameter )* ; @@ -878,9 +864,9 @@ declareParameter // rules: variable declaration // ---------------------------------- -variables -{ - errorMsg.setContext("declareVariables"); //NOI18N +variables +{ + errorMsg.setContext("declareVariables"); } : ( declareVariable )* ; @@ -894,8 +880,8 @@ declareVariable // ---------------------------------- ordering -{ - errorMsg.setContext("setOrdering"); //NOI18N +{ + errorMsg.setContext("setOrdering"); } : ( orderSpec )* ; @@ -904,7 +890,7 @@ orderSpec { int op = 0; } - : #( ORDERING_DEF + : #( ORDERING_DEF ( ASCENDING { op = RetrieveDesc.OP_ORDERBY; } | DESCENDING { op = RetrieveDesc.OP_ORDERBY_DESC; } ) @@ -920,7 +906,7 @@ orderingExpr [int op] | e:. { errorMsg.unsupported(e.getLine(), e.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.generic.unsupportedop", // NOI18N e.getText())); } @@ -931,11 +917,11 @@ orderingExpr [int op] // ---------------------------------- result returns [boolean distinct] -{ - errorMsg.setContext("setResult"); //NOI18N +{ + errorMsg.setContext("setResult"); distinct = false; } - : #( RESULT_DEF + : #( RESULT_DEF distinct = resultExpr[true] ) | { @@ -1017,8 +1003,8 @@ resultExpr [boolean outer] returns [boolean distinct] ; collectionExprResult returns [String fieldName] -{ - fieldName = null; +{ + fieldName = null; boolean tmp; } : #( FIELD_ACCESS tmp = resultExpr[false] name1:IDENT ) @@ -1033,14 +1019,14 @@ collectionExprResult returns [String fieldName] // rules: filer expression // // NOTE: the code generator traverses operands of binary operations in reverse order. -// The reason is that the RetrieveDesc processes the constriant stack in a LIFO way. -// This means, the code generator has to process the right operand first, +// The reason is that the RetrieveDesc processes the constriant stack in a LIFO way. +// This means, the code generator has to process the right operand first, // then the left operand and finally the operation. // ---------------------------------- filter -{ - errorMsg.setContext("setFilter"); //NOI18N +{ + errorMsg.setContext("setFilter"); } : #( FILTER_DEF expr:. ) { @@ -1048,7 +1034,7 @@ filter case VALUE: // constant filter Object value = expr.getValue(); - if (value instanceof Boolean) + if (value instanceof Boolean) { // Note, in the case of a true filter do not add // any constraints to the candidateRD @@ -1062,14 +1048,14 @@ filter else { errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.codegeneration.filter.nonbooleanvalue", //NOI18N + "jqlc.codegeneration.filter.nonbooleanvalue", String.valueOf(value))); } break; case FIELD_ACCESS: // The entire filter consists of a boolean field only. // Map this to 'booleanField <> FALSE'. Note, the runtime will - // create a JDBC parameter for the literal FALSE and call + // create a JDBC parameter for the literal FALSE and call // setBoolean to bind the value. RetrieveDesc rd = expr.getRetrieveDesc(); rd.addConstraint(null, RetrieveDesc.OP_VALUE, Boolean.FALSE); @@ -1083,7 +1069,7 @@ filter } ; -expression +expression : ( primary )=> primary | bitwiseExpr | conditionalExpr @@ -1106,82 +1092,82 @@ booleanOperationArgument } ; -bitwiseExpr +bitwiseExpr : #( op1:BAND left1:. right1:booleanOperationArgument ) - { + { booleanOperationArgument(left1); // do not generate boolean operation if one of the operands is variable constraint if (pushesValueOnStack(left1) && pushesValueOnStack(right1)) - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_AND, null); + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_AND, null); } | #( op2:BOR left2:. right2:booleanOperationArgument ) { booleanOperationArgument(left2); // do not generate boolean operation if one of the operands is variable constraint if (pushesValueOnStack(left2) && pushesValueOnStack(right2)) - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_OR, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_OR, null); } | #( op3:BXOR left3:. right3:booleanOperationArgument ) - { + { booleanOperationArgument(left3); errorMsg.unsupported(op3.getLine(), op3.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.generic.unsupportedop", // NOI18N op3.getText())); } ; -conditionalExpr +conditionalExpr : #( op1:AND left1:. right1:booleanOperationArgument ) - { + { booleanOperationArgument(left1); // do not generate boolean operation if one of the operands is variable constraint if (pushesValueOnStack(left1) && pushesValueOnStack(right1)) - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_AND, null); + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_AND, null); } | #( op2:OR left2:. right2:booleanOperationArgument ) - { + { booleanOperationArgument(left2); // do not generate boolean operation if one of the operands is variable constraint if (pushesValueOnStack(left2) && pushesValueOnStack(right2)) - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_OR, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_OR, null); } ; -relationalExpr +relationalExpr : ( fieldComparison )=> fieldComparison | ( objectComparison )=> objectComparison | ( collectionComparison )=> collectionComparison | ( parameterComparison )=> parameterComparison | #( op1:EQUAL left1:. expression ) - { + { expression(left1); - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_EQ, null); + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_EQ, null); } | #( op2:NOT_EQUAL left2:. expression ) - { + { expression(left2); - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_NE, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_NE, null); } | #( op3:LT left3:. expression ) - { + { expression(left3); - op3.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LT, null); + op3.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LT, null); } | #( op4:GT left4:. expression ) - { + { expression(left4); - op4.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_GT, null); + op4.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_GT, null); } | #( op5:LE left5:. expression ) - { + { expression(left5); - op5.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LE, null); + op5.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LE, null); } | #( op6:GE left6:. expression ) - { + { expression(left6); - op6.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_GE, null); + op6.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_GE, null); } ; @@ -1195,7 +1181,7 @@ fieldComparison ; fieldComparisonOperands [int operation] -{ +{ String leftName = null; String rightName = null; Object value = null; @@ -1203,30 +1189,30 @@ fieldComparisonOperands [int operation] : value = constantValue rightName = f1:fieldAccess { // case constant relop field - generateSimpleFieldValueComparison(f1.getRetrieveDesc(), rightName, + generateSimpleFieldValueComparison(f1.getRetrieveDesc(), rightName, getSwappedOp(operation), value); } | p1:PARAMETER rightName = f2:fieldAccess { // case parameter relop field // Support for fixed-width char pk columns - f2.getRetrieveDesc().addConstraint(rightName, RetrieveDesc.OP_FIELD, null); + f2.getRetrieveDesc().addConstraint(rightName, RetrieveDesc.OP_FIELD, null); f2.getRetrieveDesc().addConstraint(null, - RetrieveDesc.OP_PARAMETER, + RetrieveDesc.OP_PARAMETER, paramtab.getParameterInfoForParamName(p1.getText(), rightName)); f2.getRetrieveDesc().addConstraint(null, operation, null); } - | leftName = f3:fieldAccess - ( value = constantValue + | leftName = f3:fieldAccess + ( value = constantValue { // case field relop constant - generateSimpleFieldValueComparison(f3.getRetrieveDesc(), leftName, + generateSimpleFieldValueComparison(f3.getRetrieveDesc(), leftName, operation, value); } - | rightName = f4:fieldAccess + | rightName = f4:fieldAccess { // case field relop field - f3.getRetrieveDesc().addConstraint(leftName, operation, + f3.getRetrieveDesc().addConstraint(leftName, operation, f4.getRetrieveDesc(), rightName); } | p2:PARAMETER @@ -1234,7 +1220,7 @@ fieldComparisonOperands [int operation] // case field relop parameter // Support for fixed-width char pk columns f3.getRetrieveDesc().addConstraint(null, - RetrieveDesc.OP_PARAMETER, + RetrieveDesc.OP_PARAMETER, paramtab.getParameterInfoForParamName(p2.getText(), leftName)); f3.getRetrieveDesc().addConstraint(leftName, RetrieveDesc.OP_FIELD, null); f3.getRetrieveDesc().addConstraint(null, operation, null); @@ -1246,12 +1232,12 @@ objectComparison { Object value = null; } - : #( OBJECT_EQUAL objectComparisonOperands[RetrieveDesc.OP_EQ] ) + : #( OBJECT_EQUAL objectComparisonOperands[RetrieveDesc.OP_EQ] ) | #( OBJECT_NOT_EQUAL objectComparisonOperands[RetrieveDesc.OP_NE] ) ; objectComparisonOperands [int operation] -{ +{ Object value = null; } : value = v1:constantValue d1:dbValue @@ -1264,18 +1250,18 @@ objectComparisonOperands [int operation] // now handle navigation source expression(expr); // now generate IS NULL constraint - generateSimpleFieldValueComparison(expr.getRetrieveDesc(), ident.getText(), + generateSimpleFieldValueComparison(expr.getRetrieveDesc(), ident.getText(), getSwappedOp(operation), value); } else { if (d1.getType() == NAVIGATION) navigation(d1); - generateDbValueConstantComparison(d1.getRetrieveDesc(), (ClassType)d1.getJQLType(), + generateDbValueConstantComparison(d1.getRetrieveDesc(), (ClassType)d1.getJQLType(), getSwappedOp(operation), value, v1.getJQLType()); } } | d2:dbValue - ( value = v2:constantValue + ( value = v2:constantValue // case dbvalue relop constant { if ((value == null) && (d2.getType() == NAVIGATION)) @@ -1285,14 +1271,14 @@ objectComparisonOperands [int operation] // now handle navigation source expression(expr); // now generate IS NULL constraint - generateSimpleFieldValueComparison(expr.getRetrieveDesc(), ident.getText(), + generateSimpleFieldValueComparison(expr.getRetrieveDesc(), ident.getText(), operation, value); } else { if (d2.getType() == NAVIGATION) navigation(d2); - generateDbValueConstantComparison(d2.getRetrieveDesc(), - (ClassType)d2.getJQLType(), + generateDbValueConstantComparison(d2.getRetrieveDesc(), + (ClassType)d2.getJQLType(), operation, value, v2.getJQLType()); } } @@ -1301,10 +1287,10 @@ objectComparisonOperands [int operation] { if (d2.getType() == NAVIGATION) navigation(d2); if (d3.getType() == NAVIGATION) navigation(d3); - generateDbValueDbValueComparison(d2.getRetrieveDesc(), - (ClassType)d2.getJQLType(), - operation, - d3.getRetrieveDesc(), + generateDbValueDbValueComparison(d2.getRetrieveDesc(), + (ClassType)d2.getJQLType(), + operation, + d3.getRetrieveDesc(), (ClassType)d3.getJQLType()); } ) @@ -1339,9 +1325,9 @@ dbValue } : THIS | variableAccess - | #( NAVIGATION . IDENT ) - // do not use non-terminal navigation here, because navigation - // creates a RetrieveDesc for the relationship navigation and + | #( NAVIGATION . IDENT ) + // do not use non-terminal navigation here, because navigation + // creates a RetrieveDesc for the relationship navigation and // we must not create this in the case of relship == null ; @@ -1349,33 +1335,33 @@ collectionComparison : #( eq:COLLECTION_EQUAL . . ) { errorMsg.unsupported(eq.getLine(), eq.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.collectioncomparison.nonnull")); // NOI18N } | #( ne:COLLECTION_NOT_EQUAL . . ) { errorMsg.unsupported(ne.getLine(), ne.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.collectioncomparison.nonnull")); // NOI18N } ; -binaryArithmeticExpr +binaryArithmeticExpr : #( op1:PLUS left1:. right1:. ) { - // Optimize indexOf + : - // The SQL database returns an index starting with 1, so we need + // Optimize indexOf + : + // The SQL database returns an index starting with 1, so we need // to decrement the returned index. We can do the derement at compile // timeCombine, if the other operand is a constant int value. - if ((left1.getType() == INDEXOF) && - (right1.getType() == VALUE) && + if ((left1.getType() == INDEXOF) && + (right1.getType() == VALUE) && (right1.getValue() instanceof Integer)) { // case: indexOf() + intValue indexOf(left1, ((Integer)right1.getValue()).intValue()); } - else if ((right1.getType() == INDEXOF) && - (left1.getType() == VALUE) && + else if ((right1.getType() == INDEXOF) && + (left1.getType() == VALUE) && (left1.getValue() instanceof Integer)) { // case: intValue + indexOf() @@ -1385,25 +1371,25 @@ binaryArithmeticExpr { expression(right1); expression(left1); - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_ADD, null); + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_ADD, null); } } | #( op2:CONCAT left2:. expression ) { expression(left2); - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_CONCAT, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_CONCAT, null); } | #( op3:MINUS left3:. right3:. ) { - // Optimize indexOf + : - // The SQL database returns an index starting with 1, so we need + // Optimize indexOf + : + // The SQL database returns an index starting with 1, so we need // to decrement the returned index. We can do the derement at compile // timeCombine, if the other operand is a constant int value. - if ((left3.getType() == INDEXOF) && - (right3.getType() == VALUE) && + if ((left3.getType() == INDEXOF) && + (right3.getType() == VALUE) && (right3.getValue() instanceof Integer)) { - // case: indexOf - intValue + // case: indexOf - intValue // treated as indexOf + -intValue indexOf(left3, -((Integer)right3.getValue()).intValue()); } @@ -1411,18 +1397,18 @@ binaryArithmeticExpr { expression(right3); expression(left3); - op3.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); + op3.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); } } | #( op4:STAR left4:. expression ) { expression(left4); - op4.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_MUL, null); + op4.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_MUL, null); } | #( op5:DIV left5:. expression ) { expression(left5); - op5.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_DIV, null); + op5.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_DIV, null); } | #( op6:MOD left6:. expression ) { @@ -1431,9 +1417,9 @@ binaryArithmeticExpr } ; -unaryArithmeticExpr -{ - Object value = null; +unaryArithmeticExpr +{ + Object value = null; } : #( UNARY_PLUS expression ) // no action needed, just ignore the unary plus @@ -1445,46 +1431,46 @@ unaryArithmeticExpr op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, value); } | - expression - { + expression + { // map -value to 0 - value - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, getZeroValue(op2.getJQLType())); - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); } ) ) ; -complementExpr +complementExpr : #( op1:BNOT expression ) - { + { // map ~value to -1 - value (which is equivalent to (-value)-1) - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, getMinusOneValue(op1.getJQLType())); - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_SUB, null); } | #( op2:LNOT expr:. ) { if (expr.getType() == FIELD_ACCESS) { // The NOT operand is a boolean field. // Map this to 'booleanField = FALSE'. Note, the runtime will - // create a JDBC parameter for the literal FALSE and call + // create a JDBC parameter for the literal FALSE and call // setBoolean to bind the value. RetrieveDesc rd = op2.getRetrieveDesc(); - rd.addConstraint(null, RetrieveDesc.OP_VALUE, Boolean.FALSE); + rd.addConstraint(null, RetrieveDesc.OP_VALUE, Boolean.FALSE); expression(expr); rd.addConstraint(null, RetrieveDesc.OP_EQ, null); } else { expression(expr); - op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_NOT, null); + op2.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_NOT, null); } } ; -primary -{ - Object value; +primary +{ + Object value; String name; } : #( TYPECAST type expression ) @@ -1493,24 +1479,24 @@ primary { if (value == null) { - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.primary.null")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.codegeneration.primary.null")); } else if (value instanceof Boolean) { boolean booleanValue = ((Boolean)value).booleanValue(); RetrieveDesc rd = v.getRetrieveDesc(); - rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(0)); - rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(0)); - rd.addConstraint(null, (booleanValue?RetrieveDesc.OP_EQ:RetrieveDesc.OP_NE), null); + rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(0)); + rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(0)); + rd.addConstraint(null, (booleanValue?RetrieveDesc.OP_EQ:RetrieveDesc.OP_NE), null); } else { - v.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, value); + v.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, value); } } - | p:PARAMETER + | p:PARAMETER { - p.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_PARAMETER, + p.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_PARAMETER, paramtab.getParameterInfoForParamName(p.getText())); } | THIS @@ -1536,8 +1522,8 @@ primary ; constantValue returns [Object value] -{ - value = null; +{ + value = null; } : v:VALUE { @@ -1547,8 +1533,8 @@ constantValue returns [Object value] fieldAccess returns [String fieldName] -{ - fieldName = null; +{ + fieldName = null; } : #( FIELD_ACCESS expression name:IDENT ) { fieldName = name.getText(); } @@ -1569,11 +1555,11 @@ variableAccess } : #( var:VARIABLE ( name = col:collectionExpr )? ) { - + RetrieveDesc varRD = var.getRetrieveDesc(); if (!boundRetrieveDescs.contains(varRD)) { - if (col != null) + if (col != null) { if (col.getType() == NOT_IN) col.getRetrieveDesc().addConstraint(name, RetrieveDesc.OP_NOTIN, varRD); @@ -1594,8 +1580,8 @@ variableAccess ; collectionExpr returns [String fieldName] -{ - fieldName = null; +{ + fieldName = null; } : #( FIELD_ACCESS expression name1:IDENT ) { fieldName = name1.getText(); } @@ -1610,36 +1596,36 @@ startsWith Object value = null; JQLAST pattern = null; } - : #( op1:STARTS_WITH string:. + : #( op1:STARTS_WITH string:. { // I need to store a pointer to the second operand of startsWith here. // See second alternative below. pattern = (JQLAST)string.getNextSibling(); } - ( + ( ( constantValue )=> value = constantValue { if (string.getType() == FIELD_ACCESS) { // case 1 fieldAccess constantValue String fieldName = fieldAccess(string); - op1.getRetrieveDesc().addConstraint(fieldName, RetrieveDesc.OP_LIKE, + op1.getRetrieveDesc().addConstraint(fieldName, RetrieveDesc.OP_LIKE, ((String)value) + WILDCARD_PATTERN); } else { // case 2 expression constantValue - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, ((String)value) + WILDCARD_PATTERN); expression(string); op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LIKE, null); } } | { - // I have to access the tree matched by rule expression before - // the rule is entered. Variable pattern points to that tree and + // I have to access the tree matched by rule expression before + // the rule is entered. Variable pattern points to that tree and // needs to be initilaized before! - pattern.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + pattern.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, WILDCARD_PATTERN); } expression @@ -1657,21 +1643,21 @@ endsWith { Object value = null; } - : #( op1:ENDS_WITH string:. - ( + : #( op1:ENDS_WITH string:. + ( ( constantValue )=> value = constantValue { if (string.getType() == FIELD_ACCESS) { // case 1 fieldAccess constantValue String fieldName = fieldAccess(string); - op1.getRetrieveDesc().addConstraint(fieldName, RetrieveDesc.OP_LIKE, + op1.getRetrieveDesc().addConstraint(fieldName, RetrieveDesc.OP_LIKE, WILDCARD_PATTERN + ((String)value)); } else { // case 2 expression constantValue - op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, WILDCARD_PATTERN + ((String)value)); expression(string); op1.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_LIKE, null); @@ -1691,7 +1677,7 @@ endsWith ; isEmpty -{ +{ String name = null; } : #(op:IS_EMPTY name = collectionExpr) @@ -1701,10 +1687,10 @@ isEmpty ; like -{ +{ int opCode = RetrieveDesc.OP_LIKE; } - : #( op:LIKE string:. pattern:. opCode = escape ) + : #( op:LIKE string:. pattern:. opCode = escape ) { expression(pattern); expression(string); @@ -1713,7 +1699,7 @@ like ; escape returns [int opCode] -{ +{ // The default is no ESCAPE definition => OP_LIKE opCode = RetrieveDesc.OP_LIKE; } @@ -1727,50 +1713,50 @@ escape returns [int opCode] substring : // JDOQL: string.substring(begin, end) -> // RetrieveDesc: SUBSTRING(string, begin + 1, end - begin) - #( op:SUBSTRING string:. begin:. end:. ) + #( op:SUBSTRING string:. begin:. end:. ) { RetrieveDesc rd = op.getRetrieveDesc(); if ((begin.getType() == VALUE) && (end.getType() == VALUE)) { // Optimization: begin and end are constant values => - // calculate start and length of SQL SUBSTRING function + // calculate start and length of SQL SUBSTRING function // at compile time. // Note, Semantic ensures begin and end are int or Integer values. - int beginValue = (begin.getValue() != null) ? + int beginValue = (begin.getValue() != null) ? ((Integer)begin.getValue()).intValue() : 0; - int endValue = (end.getValue() != null) ? + int endValue = (end.getValue() != null) ? ((Integer)end.getValue()).intValue() : 0; - if (beginValue < 0) + if (beginValue < 0) { errorMsg.error(begin.getLine(), begin.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.substring.beginnegative", // NOI18N String.valueOf(beginValue))); } - else if (endValue < beginValue) + else if (endValue < beginValue) { errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, + I18NHelper.getMessage(messages, "jqlc.codegeneration.substring.beginlargerend", // NOI18N String.valueOf(beginValue), String.valueOf(endValue))); } // SQL length = end - begin - rd.addConstraint(null, RetrieveDesc.OP_VALUE, + rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(endValue-beginValue)); - // SQL start index = begin + 1 - rd.addConstraint(null, RetrieveDesc.OP_VALUE, + // SQL start index = begin + 1 + rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(beginValue+1)); } else { // At least one of begin or end is a non constant value => - // generate the arguments start and length of the SQL SUBSTRING + // generate the arguments start and length of the SQL SUBSTRING // function as binary plus/minus expressions. // The next 3 line denote the SQL length = end - begin expression(begin); expression(end); rd.addConstraint(null, RetrieveDesc.OP_SUB, null); - // The next 3 lines denote the SQL start index = begin + 1 + // The next 3 lines denote the SQL start index = begin + 1 rd.addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(1)); expression(begin); rd.addConstraint(null, RetrieveDesc.OP_ADD, null); @@ -1790,7 +1776,7 @@ indexOf [int incr] // RetrieveDesc: POSITION(string, pattern) - 1 // JDOQL: string.indexOf(pattern, begin) -> // RetrieveDesc: POSITION_START(string, pattern, begin + 1) - 1 - #( op:INDEXOF string:. pattern:. opCode = fromIndex ) + #( op:INDEXOF string:. pattern:. opCode = fromIndex ) { RetrieveDesc rd = op.getRetrieveDesc(); // the 3 lines denote the SQL function POSITION OR POSITION_START @@ -1816,21 +1802,21 @@ fromIndex returns [int opCode] : e:. { opCode = RetrieveDesc.OP_POSITION_START; - // Java indexOf method use indexes starting with 0, + // Java indexOf method use indexes starting with 0, // where SQL starts with 1, so we need to add 1 if (e.getType() == VALUE) { - // Optimization: calulate index at compile time, + // Optimization: calulate index at compile time, // if start is a constant value. // Note, Semantic ensures begin and end are int or Integer values. - int value = (e.getValue() != null) ? + int value = (e.getValue() != null) ? ((Integer)e.getValue()).intValue() : 0; - e.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + e.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(value + 1)); } else { - e.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, + e.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_VALUE, new Integer(1)); expression(e); e.getRetrieveDesc().addConstraint(null, RetrieveDesc.OP_ADD, null); @@ -1888,8 +1874,8 @@ prepareRetrieveDescs checkRetrieveDesc[usedRD] // candidate class ( #( PARAMETER_DEF . . ) )* ( #( VARIABLE_DEF . . ) )* - ( #( ORDERING_DEF - ( ASCENDING | DESCENDING ) + ( #( ORDERING_DEF + ( ASCENDING | DESCENDING ) ordering:checkRetrieveDesc[usedRD] { propagateRetrieveDesc(ordering, candidateRD); } ) @@ -1898,7 +1884,7 @@ prepareRetrieveDescs { propagateRetrieveDesc(result, candidateRD); } ) )? - #( FILTER_DEF + #( FILTER_DEF filter:checkRetrieveDesc[usedRD] { propagateRetrieveDesc(filter, candidateRD); } ) @@ -1910,7 +1896,7 @@ checkRetrieveDesc [Map usedRD] { // check persistence capable ClassType candidateClass = (ClassType)c.getJQLType(); - candidateRD = createRetrieveDesc("this", candidateClass); //NOI18N + candidateRD = createRetrieveDesc("this", candidateClass); candidateRD.setPrefetchEnabled(prefetchEnabled); } | #( cast:TYPECAST type expr1:checkRetrieveDesc[usedRD] ) @@ -1918,11 +1904,11 @@ checkRetrieveDesc [Map usedRD] cast.setRetrieveDesc(expr1.getRetrieveDesc()); } - // constantValue not necessary here, this is covered by the last rule + // constantValue not necessary here, this is covered by the last rule | t:THIS - { - t.setRetrieveDesc(candidateRD); + { + t.setRetrieveDesc(candidateRD); } | #(var:VARIABLE ( checkRetrieveDesc[usedRD] )? ) { @@ -1967,17 +1953,17 @@ checkRetrieveDesc [Map usedRD] { ie.setRetrieveDesc(expr9.getRetrieveDesc()); } - | #(like:LIKE string10:checkRetrieveDesc[usedRD] + | #(like:LIKE string10:checkRetrieveDesc[usedRD] pattern10:checkRetrieveDesc[usedRD] ( escape10:checkRetrieveDesc[usedRD] )? ) { like.setRetrieveDesc(getCommonRetrieveDesc(string10, pattern10, escape10)); } - | #(substr:SUBSTRING string11:checkRetrieveDesc[usedRD] + | #(substr:SUBSTRING string11:checkRetrieveDesc[usedRD] lower11:checkRetrieveDesc[usedRD] upper11:checkRetrieveDesc[usedRD] ) { substr.setRetrieveDesc(getCommonRetrieveDesc(string11, lower11, upper11)); } - | #(indexOf:INDEXOF string12:checkRetrieveDesc[usedRD] + | #(indexOf:INDEXOF string12:checkRetrieveDesc[usedRD] pattern12:checkRetrieveDesc[usedRD] ( start12:checkRetrieveDesc[usedRD] )? ) { indexOf.setRetrieveDesc(getCommonRetrieveDesc(string12, pattern12, start12)); @@ -1999,15 +1985,15 @@ checkRetrieveDesc [Map usedRD] | #( op1:BAND left1:. right1:. ) { checkAndOpRetrieveDesc(op1, left1, right1, usedRD); } - | #( op2:BOR left2:checkRetrieveDesc[new HashMap(usedRD)] + | #( op2:BOR left2:checkRetrieveDesc[new HashMap(usedRD)] right2:checkRetrieveDesc[new HashMap(usedRD)] ) { op2.setRetrieveDesc(getCommonRetrieveDesc(left2, right2)); } - | #( op3:BXOR left3:checkRetrieveDesc[new HashMap()] + | #( op3:BXOR left3:checkRetrieveDesc[new HashMap()] right3:checkRetrieveDesc[new HashMap()] ) { op3.setRetrieveDesc(getCommonRetrieveDesc(left3, right3)); } | #( op4:AND left4:. right4:. ) { checkAndOpRetrieveDesc(op4, left4, right4, usedRD); } - | #( op5:OR left5:checkRetrieveDesc[new HashMap(usedRD)] + | #( op5:OR left5:checkRetrieveDesc[new HashMap(usedRD)] right5:checkRetrieveDesc[new HashMap(usedRD)] ) { op5.setRetrieveDesc(getCommonRetrieveDesc(left5, right5)); } | #( op6:EQUAL left6:checkRetrieveDesc[usedRD] right6:checkRetrieveDesc[usedRD] ) @@ -2066,4 +2052,4 @@ checkRetrieveDesc [Map usedRD] | #( count:COUNT arg10:checkRetrieveDesc[usedRD] ) { count.setRetrieveDesc(arg10.getRetrieveDesc()); } | . - ; + ; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/JQL.g b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/JQL.g index def1b6e7be8..d73f3bf32cf 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/JQL.g +++ b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/JQL.g @@ -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 @@ header import antlr.NoViableAltException; import antlr.NoViableAltForCharException; import antlr.TokenStreamRecognitionException; - + import java.util.Locale; import java.util.ResourceBundle; import com.sun.jdo.api.persistence.support.JDOQueryException; @@ -52,43 +53,43 @@ options { k = 2; exportVocab = JQL; - charVocabulary = '\u0000'..'\uFFFE'; //NOI18N + charVocabulary = '\u0000'..'\uFFFE'; } tokens { - IMPORT = "import"; //NOI18N - THIS = "this"; //NOI18N - ASCENDING = "ascending"; //NOI18N - DESCENDING = "descending"; //NOI18N + IMPORT = "import"; + THIS = "this"; + ASCENDING = "ascending"; + DESCENDING = "descending"; // non-standard extensions - DISTINCT = "distinct"; //NOI18N - + DISTINCT = "distinct"; + // types - - BOOLEAN = "boolean"; //NOI18N - BYTE = "byte"; //NOI18N - CHAR = "char"; //NOI18N - SHORT = "short"; //NOI18N - INT = "int"; //NOI18N - FLOAT = "float"; //NOI18N - LONG = "long"; //NOI18N - DOUBLE = "double"; //NOI18N - + + BOOLEAN = "boolean"; + BYTE = "byte"; + CHAR = "char"; + SHORT = "short"; + INT = "int"; + FLOAT = "float"; + LONG = "long"; + DOUBLE = "double"; + // literals - - NULL = "null"; //NOI18N - TRUE = "true"; //NOI18N - FALSE = "false"; //NOI18N + + NULL = "null"; + TRUE = "true"; + FALSE = "false"; // aggregate functions - AVG = "avg"; //NOI18N - MAX = "max"; //NOI18N - MIN = "min"; //NOI18N - SUM = "sum"; //NOI18N - COUNT = "count"; //NOI18N - + AVG = "avg"; + MAX = "max"; + MIN = "min"; + SUM = "sum"; + COUNT = "count"; + } { @@ -97,12 +98,12 @@ tokens { */ private final static ResourceBundle messages = I18NHelper.loadBundle( JQLLexer.class); - + /** * */ protected ErrorMsg errorMsg; - + /** * The width of a tab stop. * This value is used to calculate the correct column in a line @@ -117,11 +118,11 @@ tokens { { this.errorMsg = errorMsg; } - + /** * */ - public void tab() + public void tab() { int column = getColumn(); int newColumn = (((column-1)/TABSIZE)+1)*TABSIZE+1; @@ -166,24 +167,24 @@ LPAREN : '(' ; RPAREN : ')' ; COMMA : ',' ; //DOT : '.' ; -EQUAL : "==" ; //NOI18N +EQUAL : "==" ; LNOT : '!' ; BNOT : '~' ; -NOT_EQUAL : "!=" ; //NOI18N +NOT_EQUAL : "!=" ; DIV : '/' ; PLUS : '+' ; MINUS : '-' ; STAR : '*' ; MOD : '%' ; -GE : ">=" ; //NOI18N -GT : ">" ; //NOI18N -LE : "<=" ; //NOI18N +GE : ">=" ; +GT : ">" ; +LE : "<=" ; LT : '<' ; BXOR : '^' ; BOR : '|' ; -OR : "||" ; //NOI18N +OR : "||" ; BAND : '&' ; -AND : "&&" ; //NOI18N +AND : "&&" ; SEMI : ';' ; // Whitespace -- ignored @@ -196,24 +197,24 @@ WS ; NEWLINE - : ( "\r\n" //NOI18N + : ( "\r\n" | '\r' | '\n' ) - { - newline(); - _ttype = Token.SKIP; + { + newline(); + _ttype = Token.SKIP; } ; // character literals CHAR_LITERAL - : '\'' ( ESC | ~'\'' ) '\'' + : '\'' ( ESC | ~'\'' ) '\'' ; // string literals STRING_LITERAL - : '"' ( ESC | ~'"')* '"' //NOI18N + : '"' ( ESC | ~'"')* '"' ; // escape sequence -- note that this is protected; it can only be called @@ -227,23 +228,23 @@ STRING_LITERAL protected ESC : '\\' - ( options { warnWhenFollowAmbig = false; } + ( options { warnWhenFollowAmbig = false; } : 'n' | 'r' | 't' | 'b' | 'f' - | '"' //NOI18N + | '"' | '\'' | '\\' - | ('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT + | ('u')+ HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT | ('0'..'3') ( options { warnWhenFollowAmbig = false; } : ('0'..'7') - ( + ( options { warnWhenFollowAmbig = false; } @@ -269,13 +270,13 @@ HEX_DIGIT // a numeric literal INT_LITERAL - { + { boolean isDecimal=false; - int tokenType = DOUBLE_LITERAL; + int tokenType = DOUBLE_LITERAL; } : '.' {_ttype = DOT;} (('0'..'9')+ {tokenType = DOUBLE_LITERAL;} - (EXPONENT)? + (EXPONENT)? (tokenType = FLOATINGPOINT_SUFFIX)? { _ttype = tokenType; })? | ( '0' {isDecimal = true;} // special case for just '0' @@ -296,11 +297,11 @@ INT_LITERAL | ('1'..'9') ('0'..'9')* {isDecimal=true;} // non-zero decimal ) ( ('l'|'L') { _ttype = LONG_LITERAL; } - + // only check to see if it's a float if looks like decimal so far | {isDecimal}? - {tokenType = DOUBLE_LITERAL;} - ( '.' ('0'..'9')* (EXPONENT)? + {tokenType = DOUBLE_LITERAL;} + ( '.' ('0'..'9')* (EXPONENT)? (tokenType = FLOATINGPOINT_SUFFIX)? | EXPONENT (tokenType = FLOATINGPOINT_SUFFIX)? | tokenType = FLOATINGPOINT_SUFFIX @@ -317,10 +318,10 @@ EXPONENT protected FLOATINGPOINT_SUFFIX returns [int tokenType] - : 'f' { tokenType = FLOAT_LITERAL; } - | 'F' { tokenType = FLOAT_LITERAL; } - | 'd' { tokenType = DOUBLE_LITERAL; } - | 'D' { tokenType = DOUBLE_LITERAL; } + : 'f' { tokenType = FLOAT_LITERAL; } + | 'F' { tokenType = FLOAT_LITERAL; } + | 'd' { tokenType = DOUBLE_LITERAL; } + | 'D' { tokenType = DOUBLE_LITERAL; } ; // an identifier. Note that testLiterals is set to true! This means @@ -328,21 +329,21 @@ FLOATINGPOINT_SUFFIX returns [int tokenType] // if it's a literal or really an identifer IDENT - options {paraphrase = "an identifier"; testLiterals=true;} //NOI18N + options {paraphrase = "an identifier"; testLiterals=true;} : ( 'a'..'z' | 'A'..'Z' | '_' | '$' | UNICODE_ESCAPE | c1:'\u0080'..'\uFFFE' - { + { if (!Character.isJavaIdentifierStart(c1)) { - errorMsg.error(getLine(), getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", //NOI18N + errorMsg.error(getLine(), getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", String.valueOf(c1))); } } - ) + ) ( 'a'..'z' | 'A'..'Z' | '_' @@ -350,10 +351,10 @@ IDENT | '0'..'9' | UNICODE_ESCAPE | c2:'\u0080'..'\uFFFE' - { + { if (!Character.isJavaIdentifierPart(c2)) { - errorMsg.error(getLine(), getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", //NOI18N + errorMsg.error(getLine(), getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", String.valueOf(c2))); } } @@ -368,11 +369,11 @@ UNICODE_ESCAPE String tmp = text.toString(); char c = (char)Integer.parseInt(tmp.substring(tmp.length() - 4, tmp.length()), 16); // problems using ANTLR feature $setText => use generated code - text.setLength(_begin); + text.setLength(_begin); text.append(new Character(c).toString()); } catch (NumberFormatException ex) { - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, "jqlc.parser.invalidunicodestr"), ex); //NOI18N + throw new JDOFatalInternalException(I18NHelper.getMessage(messages, "jqlc.parser.invalidunicodestr"), ex); } } ; @@ -426,7 +427,7 @@ tokens STARTS_WITH; ENDS_WITH; IS_EMPTY; - + // identifier types VARIABLE; PARAMETER; @@ -446,7 +447,7 @@ tokens ABS; SQRT; - // + // NOT_IN; } @@ -464,7 +465,7 @@ tokens * */ protected ErrorMsg errorMsg; - + /** * */ @@ -472,7 +473,7 @@ tokens { this.errorMsg = errorMsg; } - + /** * ANTLR method called when an error was detected. */ @@ -515,16 +516,16 @@ tokens MismatchedCharException mismatched = (MismatchedCharException)ex; if (mismatched.mismatchType == MismatchedCharException.CHAR) { - if (mismatched.foundChar == EOF_CHAR) + if (mismatched.foundChar == EOF_CHAR) { - errorMsg.error(mismatched.getLine(), mismatched.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); //NOI18N + errorMsg.error(mismatched.getLine(), mismatched.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); } - else + else { - errorMsg.error(mismatched.getLine(), mismatched.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.expectedfoundchar", //NOI18N - String.valueOf((char)mismatched.expecting), + errorMsg.error(mismatched.getLine(), mismatched.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.expectedfoundchar", + String.valueOf((char)mismatched.expecting), String.valueOf((char)mismatched.foundChar))); } return; @@ -535,15 +536,15 @@ tokens MismatchedTokenException mismatched = (MismatchedTokenException)ex; Token token = mismatched.token; if ((mismatched.mismatchType == MismatchedTokenException.TOKEN) && - (token != null)) + (token != null)) { if (token.getType() == Token.EOF_TYPE) { - errorMsg.error(token.getLine(), token.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); //NOI18N + errorMsg.error(token.getLine(), token.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); } else { - errorMsg.error(token.getLine(), token.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.syntaxerrorattoken", token.getText())); //NOI18N + errorMsg.error(token.getLine(), token.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.syntaxerrorattoken", token.getText())); } return; } @@ -553,15 +554,15 @@ tokens Token token = ((NoViableAltException)ex).token; if (token != null) { - if (token.getType() == Token.EOF_TYPE) + if (token.getType() == Token.EOF_TYPE) { errorMsg.error(token.getLine(), token.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); //NOI18N + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedEOF")); } - else + else { - errorMsg.error(token.getLine(), token.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedtoken", token.getText())); //NOI18N + errorMsg.error(token.getLine(), token.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedtoken", token.getText())); } return; } @@ -569,8 +570,8 @@ tokens else if (ex instanceof NoViableAltForCharException) { NoViableAltForCharException noViableAlt = (NoViableAltForCharException)ex; - errorMsg.error(noViableAlt.getLine(), noViableAlt.getColumn(), - I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", //NOI18N + errorMsg.error(noViableAlt.getLine(), noViableAlt.getColumn(), + I18NHelper.getMessage(messages, "jqlc.parser.unexpectedchar", String.valueOf(noViableAlt.foundChar))); } else if (ex instanceof TokenStreamRecognitionException) @@ -587,7 +588,7 @@ tokens line = ((RecognitionException)ex).getLine(); column = ((RecognitionException)ex).getColumn(); } - errorMsg.error(line, column, I18NHelper.getMessage(messages, "jqlc.parser.syntaxerror")); //NOI18N + errorMsg.error(line, column, I18NHelper.getMessage(messages, "jqlc.parser.syntaxerror")); } } @@ -596,14 +597,14 @@ tokens // ---------------------------------- parseImports -{ - errorMsg.setContext("declareImports"); //NOI18N +{ + errorMsg.setContext("declareImports"); } : ( declareImport ( SEMI! declareImport )* )? ( SEMI! )? EOF! ; declareImport - : i:IMPORT^ qualifiedName //NOI18N + : i:IMPORT^ qualifiedName { #i.setType(IMPORT_DEF); } @@ -614,15 +615,15 @@ declareImport // ---------------------------------- parseParameters -{ - errorMsg.setContext("declareParameters"); //NOI18N +{ + errorMsg.setContext("declareParameters"); } : ( declareParameter ( COMMA! declareParameter )* )? ( COMMA! )? EOF! ; declareParameter : type IDENT - { #declareParameter = #(#[PARAMETER_DEF,"parameterDef"], #declareParameter); } //NOI18N + { #declareParameter = #(#[PARAMETER_DEF,"parameterDef"], #declareParameter); } ; // ---------------------------------- @@ -630,15 +631,15 @@ declareParameter // ---------------------------------- parseVariables -{ - errorMsg.setContext("declareVariables"); //NOI18N +{ + errorMsg.setContext("declareVariables"); } : ( declareVariable ( SEMI! declareVariable )* )? ( SEMI! )? EOF! ; declareVariable : type IDENT - { #declareVariable = #(#[VARIABLE_DEF,"variableDef"], #declareVariable); } //NOI18N + { #declareVariable = #(#[VARIABLE_DEF,"variableDef"], #declareVariable); } ; // ---------------------------------- @@ -646,16 +647,16 @@ declareVariable // ---------------------------------- parseOrdering -{ - errorMsg.setContext("setOrdering"); //NOI18N +{ + errorMsg.setContext("setOrdering"); } : ( orderSpec ( COMMA! orderSpec )* )? ( COMMA! )? EOF! ; orderSpec! : e:expression d:direction - { #orderSpec = #(#[ORDERING_DEF,"orderingDef"], #d, #e); } //NOI18N - ; + { #orderSpec = #(#[ORDERING_DEF,"orderingDef"], #d, #e); } + ; direction : ASCENDING @@ -667,18 +668,18 @@ direction // ---------------------------------- parseResult -{ - errorMsg.setContext("setResult"); //NOI18N +{ + errorMsg.setContext("setResult"); } : ( ( DISTINCT^ )? ( a:aggregateExpr | e:expression ) )? EOF! - { + { // create RESULT_DEF node if there was a projection if (#a != null) { // skip a possible first distinct in case of an aggregate expr #parseResult = #(#[RESULT_DEF, "resultDef"], #a); } else if (#e != null) { - #parseResult = #(#[RESULT_DEF,"resultDef"], #parseResult); //NOI18N + #parseResult = #(#[RESULT_DEF,"resultDef"], #parseResult); } } ; @@ -688,7 +689,7 @@ aggregateExpr ; distinctExpr - : DISTINCT^ e:expression + : DISTINCT^ e:expression | expression ; @@ -697,11 +698,11 @@ distinctExpr // ---------------------------------- parseFilter! -{ - errorMsg.setContext("setFilter"); //NOI18N +{ + errorMsg.setContext("setFilter"); } : e:expression EOF! - { #parseFilter = #(#[FILTER_DEF,"filterDef"], #e); } //NOI18N + { #parseFilter = #(#[FILTER_DEF,"filterDef"], #e); } ; // This is a list of expressions. @@ -786,10 +787,10 @@ postfixExpression argList : LPAREN! ( expressionList - {#argList = #(#[ARG_LIST,"ARG_LIST"], #argList); } //NOI18N + {#argList = #(#[ARG_LIST,"ARG_LIST"], #argList); } | /* empty list */ - {#argList = #[ARG_LIST,"ARG_LIST"];} //NOI18N + {#argList = #[ARG_LIST,"ARG_LIST"];} ) RPAREN! ; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Optimizer.g b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Optimizer.g index d4458047230..c42cefeef93 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Optimizer.g +++ b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Optimizer.g @@ -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 @@ -23,9 +24,9 @@ header { package com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc; - + import java.util.*; - + import java.math.BigDecimal; import java.math.BigInteger; @@ -45,7 +46,7 @@ header * This class defines the optimizer pass of the JQL compiler. * It takes the typed AST as produced by the smenatic analysis and * converts it into a simpler but equivalent typed AST. - * + * * @author Michael Bouschen * @version 0.1 */ @@ -56,26 +57,26 @@ options importVocab = JQL; buildAST = true; defaultErrorHandler = false; - ASTLabelType = "JQLAST"; //NOI18N + ASTLabelType = "JQLAST"; } { /** * I18N support */ - protected final static ResourceBundle messages = + protected final static ResourceBundle messages = I18NHelper.loadBundle(Optimizer.class); - + /** - * type table + * type table */ protected TypeTable typetab; - + /** * query parameter table */ protected ParameterTable paramtab; - + /** * */ @@ -84,7 +85,7 @@ options /** * */ - public void init(TypeTable typetab, ParameterTable paramtab, + public void init(TypeTable typetab, ParameterTable paramtab, ErrorMsg errorMsg) { this.typetab = typetab; @@ -96,14 +97,14 @@ options * */ public void reportError(RecognitionException ex) { - errorMsg.fatal("Optimizer error", ex); //NOI18N + errorMsg.fatal("Optimizer error", ex); } /** * */ public void reportError(String s) { - errorMsg.fatal("Optimizer error: " + s); //NOI18N + errorMsg.fatal("Optimizer error: " + s); } /** @@ -123,33 +124,33 @@ options case 't': return '\t'; case 'b': return '\b'; case 'f': return '\f'; - case 'u': + case 'u': // unicode spec return (char)Integer.parseInt(text.substring(2, text.length()), 16); - case '0': + case '0': case '1': case '2': - case '3': + case '3': case '4': - case '5': + case '5': case '6': - case '7': - // octal spec + case '7': + // octal spec return (char)Integer.parseInt(text.substring(1, text.length()), 8); default : return second; } } return first; } - + /** - * Check an AND operation (BAND, AND) for constant operands + * Check an AND operation (BAND, AND) for constant operands * that could be optimized. * @param op the AND operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkAnd(JQLAST op, JQLAST left, JQLAST right) { @@ -167,12 +168,12 @@ options } /** - * Check an OR operation (BOR, OR) for constant operands + * Check an OR operation (BOR, OR) for constant operands * that could be optimized. * @param op the OR operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkOr(JQLAST op, JQLAST left, JQLAST right) { @@ -196,14 +197,14 @@ options * @param left the left operand * @param right the right operand * @param negate true for not equal operation, false otherwise - * @return optimized JQLAST + * @return optimized JQLAST */ - protected JQLAST checkEqualityOp(JQLAST op, JQLAST left, JQLAST right, + protected JQLAST checkEqualityOp(JQLAST op, JQLAST left, JQLAST right, boolean negate) { JQLAST ast = op; - // case + // case if ((left.getType() == VALUE) && (right.getType() == VALUE)) { ast = handleValueEqValue(op, left, right, negate); @@ -222,13 +223,13 @@ options } /** - * Check a object equality operation (OBJECT_EQUAL, OBJECT_NOT_EQUAL) + * Check a object equality operation (OBJECT_EQUAL, OBJECT_NOT_EQUAL) * for constant operands that could be optimized. * @param op the object equality operator * @param left the left operand * @param right the right operand * @param negate true for not equal operation, false otherwise - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkObjectEqualityOp(JQLAST op, JQLAST left, JQLAST right, boolean negate) @@ -243,29 +244,29 @@ options } /** - * Check a collection equality operation (COLLECTION_EQUAL, + * Check a collection equality operation (COLLECTION_EQUAL, * COLLECTION_NOT_EQUAL) for constant operands that could be optimized. * @param op the collection equality operator * @param left the left operand * @param right the right operand * @param negate true for not equal operation, false otherwise - * @return optimized JQLAST + * @return optimized JQLAST */ - protected JQLAST checkCollectionEqualityOp(JQLAST op, JQLAST left, + protected JQLAST checkCollectionEqualityOp(JQLAST op, JQLAST left, JQLAST right, boolean negate) { JQLAST ast = op; boolean isLeftConstant = (left.getType() == VALUE); boolean isRightConstant = (right.getType() == VALUE); - + if (isLeftConstant && isRightConstant) { ast = handleValueEqValue(op, left, right, negate); } - else if ((isLeftConstant && (left.getValue() == null) && isNonConstantCollection(right)) || - (isRightConstant && (right.getValue() == null) && isNonConstantCollection(left))) + else if ((isLeftConstant && (left.getValue() == null) && isNonConstantCollection(right)) || + (isRightConstant && (right.getValue() == null) && isNonConstantCollection(left))) { - // This optimization is datastore dependend. + // This optimization is datastore dependend. // In TP we know a collection returned by the datastore is never null. // null == -> false // == null -> false @@ -280,11 +281,11 @@ options } /** - * Check a logical not operation (LNOT) for a constant operand + * Check a logical not operation (LNOT) for a constant operand * that could be optimized. * @param op the logical not operator * @param arg the operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkLogicalNotOp(JQLAST op, JQLAST arg) { @@ -294,7 +295,7 @@ options { // !value may be calculated at compile time. Object valueObj = arg.getValue(); - boolean value = (valueObj instanceof Boolean) ? + boolean value = (valueObj instanceof Boolean) ? ((Boolean)valueObj).booleanValue() : false; arg.setType(VALUE); arg.setValue(new Boolean(!value)); @@ -314,7 +315,7 @@ options * @param op the plus operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkBinaryPlusOp(JQLAST op, JQLAST left, JQLAST right) { @@ -332,21 +333,21 @@ options else { Type type = op.getJQLType(); - + if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) - value = new Integer(((Number)leftValue).intValue() + + value = new Integer(((Number)leftValue).intValue() + ((Number)rightValue).intValue()); else if (type.equals(typetab.longType)) - value = new Long(((Number)leftValue).longValue() + + value = new Long(((Number)leftValue).longValue() + ((Number)rightValue).longValue()); else if (type.equals(typetab.floatType)) - value = new Float(((Number)leftValue).floatValue() + + value = new Float(((Number)leftValue).floatValue() + ((Number)rightValue).floatValue()); else if (type.equals(typetab.doubleType)) - value = new Double(((Number)leftValue).doubleValue() + + value = new Double(((Number)leftValue).doubleValue() + ((Number)rightValue).doubleValue()); else if (type.equals(typetab.bigDecimalType)) value = getBigDecimalValue(leftValue).add( @@ -354,9 +355,9 @@ options else if (type.equals(typetab.bigIntegerType)) value = getBigIntegerValue(leftValue).add( getBigIntegerValue(rightValue)); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkbinaryplusop.invalidtype", //NOI18N + "jqlc.optimizer.checkbinaryplusop.invalidtype", String.valueOf(type))); } ast.setType(VALUE); @@ -365,14 +366,14 @@ options } return ast; } - + /** * Check a string concatenation operation (CONCAT) for constant operands * that could be optimized. * @param op the concat operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkConcatOp(JQLAST op, JQLAST left, JQLAST right) { @@ -387,7 +388,7 @@ options value = rightValue; else if (rightValue == null) value = leftValue; - else + else value = leftValue.toString() + rightValue.toString(); ast.setType(VALUE); ast.setValue(value); @@ -402,7 +403,7 @@ options * @param op the minus operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkBinaryMinusOp(JQLAST op, JQLAST left, JQLAST right) { @@ -419,12 +420,12 @@ options { if (leftValue == null) leftValue = new Integer(0); - + Type type = op.getJQLType(); - + if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) value = new Integer(((Number)leftValue).intValue() - ((Number)rightValue).intValue()); @@ -432,10 +433,10 @@ options value = new Long(((Number)leftValue).longValue() - ((Number)rightValue).longValue()); else if (type.equals(typetab.floatType)) - value = new Float(((Number)leftValue).floatValue() - + value = new Float(((Number)leftValue).floatValue() - ((Number)rightValue).floatValue()); else if (type.equals(typetab.doubleType)) - value = new Double(((Number)leftValue).doubleValue() - + value = new Double(((Number)leftValue).doubleValue() - ((Number)rightValue).doubleValue()); else if (type.equals(typetab.bigDecimalType)) value = getBigDecimalValue(leftValue).subtract( @@ -443,9 +444,9 @@ options else if (type.equals(typetab.bigIntegerType)) value = getBigIntegerValue(leftValue).subtract( getBigIntegerValue(rightValue)); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkbinaryminusop.invalidtype", //NOI18N + "jqlc.optimizer.checkbinaryminusop.invalidtype", String.valueOf(type))); } ast.setType(VALUE); @@ -454,14 +455,14 @@ options } return ast; } - + /** * Check a binary multiplication operation (STAR) for constant operands * that could be optimized. * @param op the multiplication operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkMultiplicationOp(JQLAST op, JQLAST left, JQLAST right) { @@ -477,10 +478,10 @@ options if (rightValue == null) rightValue = new Integer(0); Type type = op.getJQLType(); - + if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) value = new Integer(((Number)leftValue).intValue() * ((Number)rightValue).intValue()); @@ -488,10 +489,10 @@ options value = new Long(((Number)leftValue).longValue() * ((Number)rightValue).longValue()); else if (type.equals(typetab.floatType)) - value = new Float(((Number)leftValue).floatValue() * + value = new Float(((Number)leftValue).floatValue() * ((Number)rightValue).floatValue()); else if (type.equals(typetab.doubleType)) - value = new Double(((Number)leftValue).doubleValue() * + value = new Double(((Number)leftValue).doubleValue() * ((Number)rightValue).doubleValue()); else if (type.equals(typetab.bigDecimalType)) value = getBigDecimalValue(leftValue).multiply( @@ -499,9 +500,9 @@ options else if (type.equals(typetab.bigIntegerType)) value = getBigIntegerValue(leftValue).multiply( getBigIntegerValue(rightValue)); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkmultiplicationop.invalidtype", //NOI18N + "jqlc.optimizer.checkmultiplicationop.invalidtype", String.valueOf(type))); ast.setType(VALUE); @@ -510,14 +511,14 @@ options } return ast; } - + /** * Check a binary division operation (DIV) for constant operands * that could be optimized. * @param op the division operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkDivisionOp(JQLAST op, JQLAST left, JQLAST right) { @@ -535,10 +536,10 @@ options rightValue = new Integer(0); Type type = op.getJQLType(); - + if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) value = new Integer(((Number)leftValue).intValue() / ((Number)rightValue).intValue()); @@ -546,10 +547,10 @@ options value = new Long(((Number)leftValue).longValue() / ((Number)rightValue).longValue()); else if (type.equals(typetab.floatType)) - value = new Float(((Number)leftValue).floatValue() / + value = new Float(((Number)leftValue).floatValue() / ((Number)rightValue).floatValue()); else if (type.equals(typetab.doubleType)) - value = new Double(((Number)leftValue).doubleValue() / + value = new Double(((Number)leftValue).doubleValue() / ((Number)rightValue).doubleValue()); else if (type.equals(typetab.bigDecimalType)) value = getBigDecimalValue(leftValue).divide( @@ -557,9 +558,9 @@ options else if (type.equals(typetab.bigIntegerType)) value = getBigIntegerValue(leftValue).divide( getBigIntegerValue(rightValue)); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkdivisionop.invalidtype", //NOI18N + "jqlc.optimizer.checkdivisionop.invalidtype", String.valueOf(type))); ast.setType(VALUE); @@ -568,14 +569,14 @@ options } return ast; } - + /** * Check a binary modular operation (MOD) for constant operands * that could be optimized. * @param op the mod operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkModOp(JQLAST op, JQLAST left, JQLAST right) { @@ -593,10 +594,10 @@ options rightValue = new Integer(0); Type type = op.getJQLType(); - + if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) value = new Integer(((Number)leftValue).intValue() % ((Number)rightValue).intValue()); @@ -604,10 +605,10 @@ options value = new Long(((Number)leftValue).longValue() % ((Number)rightValue).longValue()); else if (type.equals(typetab.floatType)) - value = new Float(((Number)leftValue).floatValue() % + value = new Float(((Number)leftValue).floatValue() % ((Number)rightValue).floatValue()); else if (type.equals(typetab.doubleType)) - value = new Double(((Number)leftValue).doubleValue() % + value = new Double(((Number)leftValue).doubleValue() % ((Number)rightValue).doubleValue()); else if (type.equals(typetab.bigDecimalType)) { @@ -622,9 +623,9 @@ options else if (type.equals(typetab.bigIntegerType)) value = getBigIntegerValue(leftValue).remainder( getBigIntegerValue(rightValue)); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkmodop.invalidtype", //NOI18N + "jqlc.optimizer.checkmodop.invalidtype", String.valueOf(type))); ast.setType(VALUE); @@ -639,25 +640,25 @@ options * that could be optimized. * @param op the unary minus operator * @param arg the operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkUnaryMinusOp(JQLAST op, JQLAST arg) { JQLAST ast = op; - + if (arg.getType() == VALUE) { Object value = arg.getValue(); Type type = op.getJQLType(); Object negate = null; - + if (type instanceof NumberType) negate = ((NumberType)type).negate((Number)value); - else + else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.checkunaryminusop.invalidtype", //NOI18N + "jqlc.optimizer.checkunaryminusop.invalidtype", String.valueOf(type))); - + ast.setType(VALUE); ast.setValue(negate); ast.setFirstChild(null); @@ -671,19 +672,19 @@ options * @param op the cast operator * @param castType the cast type * @param expr the non constant operand - * @return optimized JQLAST + * @return optimized JQLAST */ protected JQLAST checkCastOp(JQLAST op, JQLAST castType, JQLAST expr) { JQLAST ast = op; - + if (expr.getType() == VALUE) { Object value = expr.getValue(); Type type = op.getJQLType(); if (type instanceof NumericWrapperClassType) type = ((NumericWrapperClassType)type).getPrimitiveType(); - + if (type.equals(typetab.intType)) value = new Integer(((Number)value).intValue()); else if (type.equals(typetab.longType)) @@ -702,7 +703,7 @@ options value = new Short((short)((Number)value).intValue()); else if (type.equals(typetab.charType)) value = new Character((char)((Number)value).intValue()); - + // If non of the above type applies, leave the value as it is // convert the TYPECAST op into a VALUE @@ -714,7 +715,7 @@ options } /** - * Converts the specified value into a BigDecimal value. + * Converts the specified value into a BigDecimal value. * @param value value to be converted * @return BigDecimal representation */ @@ -725,14 +726,14 @@ options ret = (BigDecimal)typetab.bigDecimalType.getValue((Number)value); else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.getbigdecimalvalue.notnumber", //NOI18N + "jqlc.optimizer.getbigdecimalvalue.notnumber", String.valueOf(value))); return ret; } /** - * Converts the specified value into a BigInteger value. + * Converts the specified value into a BigInteger value. * @param value value to be converted * @return BigInteger representation */ @@ -744,29 +745,29 @@ options ret = (BigInteger)typetab.bigIntegerType.getValue((Number)value); else errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.optimizer.getbigintegervalue.notnumber", //NOI18N + "jqlc.optimizer.getbigintegervalue.notnumber", String.valueOf(value))); return ret; } - + /** - * This method is called in the case of an equality operation having two - * constant operands. It calculates the result of this constant operation + * This method is called in the case of an equality operation having two + * constant operands. It calculates the result of this constant operation * and returns a JQLAST node representing a constant boolean value. * @param op the equality operator * @param left the left operand * @param right the right operand * @param negate true for not equal operation, false otherwise - * @return optimized JQLAST + * @return optimized JQLAST */ - protected JQLAST handleValueEqValue(JQLAST op, JQLAST left, JQLAST right, + protected JQLAST handleValueEqValue(JQLAST op, JQLAST left, JQLAST right, boolean negate) { Object leftValue = left.getValue(); Object rightValue = right.getValue(); boolean value = false; - + if ((leftValue == null) && (rightValue == null)) { // both values are null -> true @@ -782,7 +783,7 @@ options // one value is null, the other is not null -> false value = false; } - if (negate) + if (negate) { value = !value; } @@ -793,21 +794,21 @@ options } /** - * This method is called in the case of an equality operation having - * a boolean constant operand and a non constant operand. - * It returns the non constant operand either as it is or inverted, + * This method is called in the case of an equality operation having + * a boolean constant operand and a non constant operand. + * It returns the non constant operand either as it is or inverted, * depending on the equality operation. * @param op the equality operator * @param value the contant boolean value * @param expr the non constant operand * @param negate true for not equal operation, false otherwise - * @return optimized JQLAST + * @return optimized JQLAST */ - private JQLAST handleBooleanValueEqExpr(JQLAST op, Object value, + private JQLAST handleBooleanValueEqExpr(JQLAST op, Object value, JQLAST expr, boolean negate) { JQLAST ast; - boolean skip = (value instanceof Boolean) ? + boolean skip = (value instanceof Boolean) ? ((Boolean)value).booleanValue() : false; if (negate) skip = !skip; @@ -817,7 +818,7 @@ options // expr != false -> expr ast = expr; } - else + else { // if expr is a equality op or a not op the invert operation may be "inlined": // (expr1 == expr2) != true -> expr1 != expr2 @@ -831,12 +832,12 @@ options { case EQUAL: expr.setType(NOT_EQUAL); - expr.setText("!="); //NOI18N + expr.setText("!="); ast = expr; break; case NOT_EQUAL: expr.setType(EQUAL); - expr.setText("=="); //NOI18N + expr.setText("=="); ast = expr; break; case LNOT: @@ -844,7 +845,7 @@ options break; default: op.setType(LNOT); - op.setText("!"); //NOI18N + op.setText("!"); op.setFirstChild(expr); ast = op; } @@ -854,14 +855,14 @@ options } /** - * This method is called in the case of an AND operation having at least - * one constant operand. If the constant operand evaluates to true it + * This method is called in the case of an AND operation having at least + * one constant operand. If the constant operand evaluates to true it * returns the other operand. If it evaluates to false it returns an AST * representing the constant boolean value false. * @param op the AND operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ private JQLAST handleValueAndExpr(JQLAST op, Object value, JQLAST expr) { @@ -879,7 +880,7 @@ options // false AND expr -> false // expr AND false -> false op.setType(VALUE); - op.setText("false"); //NOI18N + op.setText("false"); op.setValue(new Boolean(false)); op.setFirstChild(null); ast = op; @@ -888,14 +889,14 @@ options } /** - * This method is called in the case of an OR operation having at least - * one constant operand. If the constant operand evaluates to false it + * This method is called in the case of an OR operation having at least + * one constant operand. If the constant operand evaluates to false it * returns the other operand. If it evaluates to true it returns an AST * representing the constant boolean value true. * @param op the AND operator * @param left the left operand * @param right the right operand - * @return optimized JQLAST + * @return optimized JQLAST */ private JQLAST handleValueOrExpr(JQLAST op, Object value, JQLAST expr) { @@ -906,7 +907,7 @@ options // true OR expr -> true // expr OR true -> true op.setType(VALUE); - op.setText("true"); //NOI18N + op.setText("true"); op.setValue(new Boolean(true)); op.setFirstChild(null); ast = op; @@ -926,12 +927,12 @@ options */ protected boolean isBooleanValueAST(JQLAST ast) { - return (ast.getType() == VALUE) && + return (ast.getType() == VALUE) && (typetab.booleanType.equals(ast.getJQLType())); } /** - * Returns true if the specified AST represents a datastore value. + * Returns true if the specified AST represents a datastore value. */ protected boolean isNonConstantCollection(JQLAST ast) { @@ -949,7 +950,7 @@ options } /** - * Implements DeMorgans rule: + * Implements DeMorgans rule: *
* NOT (a AND b) -> NOT a OR NOT b *
@@ -957,8 +958,8 @@ options *
* NOT (NOT a) -> a *
- * The method assumes that the tree passed as an argument does not include - * the initial NOT. Note, this method checks for contains clauses, because + * The method assumes that the tree passed as an argument does not include + * the initial NOT. Note, this method checks for contains clauses, because * they require special treatement. */ protected JQLAST deMorgan(JQLAST tree) @@ -966,7 +967,7 @@ options JQLAST result = null; JQLAST left = null; JQLAST right = null; - switch (tree.getType()) + switch (tree.getType()) { case AND: case BAND: @@ -1007,12 +1008,12 @@ options // wrap arg into not operator result = buildAST(new JQLAST(LNOT, "!", typetab.booleanType), tree); break; - } + } return result; } /** - * This overloaded deMorgan method implements special treatment of variable + * This overloaded deMorgan method implements special treatment of variable * access expressions in the case of !contains. The method keeps an expression * accessing the specified variable as it is, but it inverts an expression NOT * accessing the variable following regular DeMorgan rules. @@ -1020,7 +1021,7 @@ options protected JQLAST deMorgan(JQLAST tree, String var) { JQLAST result = tree; - switch (tree.getType()) + switch (tree.getType()) { case AND: case BAND: @@ -1045,8 +1046,8 @@ options return result; } - /** - * Checks the specified tree being a CONATAINS clause. If yes it returns + /** + * Checks the specified tree being a CONATAINS clause. If yes it returns * the variable used in the contains clause. Otherwise it returns null. */ protected String getVariableFromContainsClause(JQLAST tree) @@ -1060,11 +1061,11 @@ options return null; } } - + /** - * Checks whether the specified tree accesses the variable with the - * specified name. Accessing means either this node or of of the subnodes - * has the type VARIABLE. + * Checks whether the specified tree accesses the variable with the + * specified name. Accessing means either this node or of of the subnodes + * has the type VARIABLE. * NOTE, the method is intended to be used in the ! contains case only! * If it find a variable access node of the form *
@@ -1081,7 +1082,7 @@ options boolean found = false; JQLAST child = (JQLAST)tree.getFirstChild(); - if ((tree.getType() == VARIABLE) && (tree.getText().equals(var)) && + if ((tree.getType() == VARIABLE) && (tree.getText().equals(var)) && (child != null)) { found = true; @@ -1099,7 +1100,7 @@ options return found; } - /** + /** * Inverts the specified node: AND -> OR, == -> !=, etc. */ protected void invertNode(JQLAST node) @@ -1185,8 +1186,8 @@ query // ---------------------------------- candidateClass -{ - errorMsg.setContext("setCandidates"); //NOI18N +{ + errorMsg.setContext("setCandidates"); } : CLASS_DEF ; @@ -1196,8 +1197,8 @@ candidateClass // ---------------------------------- parameters -{ - errorMsg.setContext("declareParameters"); //NOI18N +{ + errorMsg.setContext("declareParameters"); } : ( declareParameter )* ; @@ -1210,9 +1211,9 @@ declareParameter // rules: variable declaration // ---------------------------------- -variables -{ - errorMsg.setContext("declareVariables"); //NOI18N +variables +{ + errorMsg.setContext("declareVariables"); } : ( declareVariable )* ; @@ -1225,9 +1226,9 @@ declareVariable // rules: ordering specification // ---------------------------------- -ordering -{ - errorMsg.setContext("setOrdering"); //NOI18N +ordering +{ + errorMsg.setContext("setOrdering"); } : ( orderSpec )* ; @@ -1241,8 +1242,8 @@ orderSpec // ---------------------------------- result -{ - errorMsg.setContext("setResult"); //NOI18N +{ + errorMsg.setContext("setResult"); } : #( r:RESULT_DEF resultExpr ) | // empty rule @@ -1263,13 +1264,13 @@ resultExpr // ---------------------------------- filter -{ - errorMsg.setContext("setFilter"); //NOI18N +{ + errorMsg.setContext("setFilter"); } : #( FILTER_DEF expression ) ; -expression +expression : primary | bitwiseExpr | conditionalExpr @@ -1279,7 +1280,7 @@ expression | complementExpr ; -bitwiseExpr +bitwiseExpr : #( op1:BAND left1:expression right1:expression ) { #bitwiseExpr = checkAnd(#op1, #left1, #right1); @@ -1291,7 +1292,7 @@ bitwiseExpr | #( op3:BXOR left3:expression right3:expression ) ; -conditionalExpr +conditionalExpr : #( op1:AND left1:expression right1:expression ) { #conditionalExpr = checkAnd(#op1, #left1, #right1); @@ -1311,7 +1312,7 @@ relationalExpr { #relationalExpr = checkEqualityOp(#op2, #left2, #right2, true); } - | #( op3:OBJECT_EQUAL left3:expression right3:expression ) + | #( op3:OBJECT_EQUAL left3:expression right3:expression ) { #relationalExpr = checkObjectEqualityOp(#op3, #left3, #right3, false); } @@ -1333,7 +1334,7 @@ relationalExpr | #( GE expression expression ) ; -binaryArithmeticExpr +binaryArithmeticExpr : #( op1:PLUS left1:expression right1:expression ) { #binaryArithmeticExpr = checkBinaryPlusOp(#op1, #left1, #right1); @@ -1360,7 +1361,7 @@ binaryArithmeticExpr } ; -unaryArithmeticExpr +unaryArithmeticExpr : #( UNARY_PLUS expression ) | ( unaryMinusLiteralExpr )=> unaryMinusLiteralExpr | #( op2:UNARY_MINUS arg2:expression ) @@ -1382,7 +1383,7 @@ unaryMinusLiteralExpr } ; -complementExpr +complementExpr : #( op1:BNOT arg1:expression ) | #( op2:LNOT arg2:expression ) { @@ -1390,7 +1391,7 @@ complementExpr } ; -primary +primary : castExpr | literal | VALUE @@ -1421,8 +1422,8 @@ castExpr ; literal -{ - Object value = null; +{ + Object value = null; } : value = l:literalHelper { @@ -1432,8 +1433,8 @@ literal ; literalHelper returns [Object value] -{ - value = null; +{ + value = null; } : TRUE { value = new Boolean(true); } @@ -1448,13 +1449,13 @@ literalHelper returns [Object value] catch (NumberFormatException ex) { errorMsg.error(i.getLine(), i.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.optimizer.literal.invalid", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.optimizer.literal.invalid", i.getJQLType().getName(), i.getText())); } } | l:LONG_LITERAL - { + { String txt = l.getText(); char last = txt.charAt(txt.length() - 1); if ((last == 'l') || (last == 'L')) @@ -1468,13 +1469,13 @@ literalHelper returns [Object value] catch (NumberFormatException ex) { errorMsg.error(l.getLine(), l.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.optimizer.literal.invalid", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.optimizer.literal.invalid", l.getJQLType().getName(), l.getText())); } } | f:FLOAT_LITERAL - { + { String txt = f.getText(); char last = txt.charAt(txt.length() - 1); if ((last == 'f') || (last == 'F')) @@ -1488,13 +1489,13 @@ literalHelper returns [Object value] catch (NumberFormatException ex) { errorMsg.error(f.getLine(), f.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.optimizer.literal.invalid", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.optimizer.literal.invalid", f.getJQLType().getName(), f.getText())); } } | d:DOUBLE_LITERAL - { + { String txt = d.getText(); char last = txt.charAt(txt.length() - 1); if ((last == 'd') || (last == 'd')) @@ -1508,8 +1509,8 @@ literalHelper returns [Object value] catch (NumberFormatException ex) { errorMsg.error(d.getLine(), d.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.optimizer.literal.invalid", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.optimizer.literal.invalid", d.getJQLType().getName(), d.getText())); } } @@ -1523,17 +1524,17 @@ literalHelper returns [Object value] parameter : p:PARAMETER - { + { if (paramtab.inline(#p.getText())) { #p.setType(VALUE); - #p.setValue(paramtab.getValueByName(#p.getText())); + #p.setValue(paramtab.getValueByName(#p.getText())); } } ; staticFieldAccess -{ - Object value = null; +{ + Object value = null; } : #( s:STATIC_FIELD_ACCESS t:TYPENAME i:IDENT) { @@ -1548,11 +1549,11 @@ staticFieldAccess #s.setValue(value); #s.setFirstChild(null); } - catch (IllegalAccessException e) + catch (IllegalAccessException e) { throw new JDOFatalUserException( - I18NHelper.getMessage(messages, - "jqlc.optimizer.staticfieldaccess.illegal", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.optimizer.staticfieldaccess.illegal", i.getText(), classType.getName()), e); } } @@ -1563,12 +1564,12 @@ fieldAccess { if (#o.getType() == VALUE) { - // If the object of the field access is a constant value, - // evaluate the field access at compile time and + // If the object of the field access is a constant value, + // evaluate the field access at compile time and // treat the expression as constant value. Object object = #o.getValue(); ClassType classType = (ClassType)#o.getJQLType(); - Object value = CodeGeneration.getFieldValue(classType, object, + Object value = CodeGeneration.getFieldValue(classType, object, #name.getText()); #f.setType(VALUE); #f.setValue(value); @@ -1582,12 +1583,12 @@ navigation { if (#o.getType() == VALUE) { - // If the object of the navigation is a constant value, - // evaluate the field access at compile time and + // If the object of the navigation is a constant value, + // evaluate the field access at compile time and // treat the expression as constant value. Object object = #o.getValue(); ClassType classType = (ClassType)#o.getJQLType(); - Object value = CodeGeneration.getFieldValue(classType, object, + Object value = CodeGeneration.getFieldValue(classType, object, #name.getText()); #n.setType(VALUE); #n.setValue(value); @@ -1601,11 +1602,11 @@ variableAccess ; startsWith - : #( STARTS_WITH expression expression ) + : #( STARTS_WITH expression expression ) ; endsWith - : #( ENDS_WITH expression expression ) + : #( ENDS_WITH expression expression ) ; isEmpty @@ -1613,8 +1614,8 @@ isEmpty { if (#e.getType() == VALUE) { - // If the expression that specifies the collection is a constant value, - // evaluate the isEmpty call at compile time and treat the expression + // If the expression that specifies the collection is a constant value, + // evaluate the isEmpty call at compile time and treat the expression // as constant value. Object object = #e.getValue(); Object value = null; @@ -1628,7 +1629,7 @@ isEmpty } else { - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.optimizer.isempty.requirecollection")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.optimizer.isempty.requirecollection")); } #op.setType(VALUE); #op.setValue(value); @@ -1638,15 +1639,15 @@ isEmpty ; like - : #( LIKE expression expression ( expression )? ) + : #( LIKE expression expression ( expression )? ) ; substring - : #( SUBSTRING expression expression expression ) + : #( SUBSTRING expression expression expression ) ; indexOf - : #( INDEXOF expression expression ( expression )? ) + : #( INDEXOF expression expression ( expression )? ) ; length diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Semantic.g b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Semantic.g index 591553fa190..1ff1cdabc4a 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Semantic.g +++ b/appserver/persistence/cmp/support-sqlstore/src/main/antlr/Semantic.g @@ -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 @@ -23,11 +24,11 @@ header { package com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc; - + import java.util.Locale; import java.util.ResourceBundle; import java.util.Collection; - + import org.glassfish.persistence.common.I18NHelper; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.TypeTable; @@ -36,7 +37,7 @@ header import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.FieldInfo; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.NumericType; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.NumericWrapperClassType; - + import com.sun.jdo.spi.persistence.support.sqlstore.query.util.scope.SymbolTable; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.scope.Definition; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.scope.TypeName; @@ -62,51 +63,51 @@ options importVocab = JQL; buildAST = true; defaultErrorHandler = false; - ASTLabelType = "JQLAST"; //NOI18N + ASTLabelType = "JQLAST"; } { /** * I18N support */ - protected final static ResourceBundle messages = + protected final static ResourceBundle messages = I18NHelper.loadBundle(Semantic.class); - + /** * symbol table handling names of fields, variables and parameters */ protected SymbolTable symtab; - + /** * symbol table handling type names (candidate class and imported names) */ protected SymbolTable typeNames; /** - * type table + * type table */ protected TypeTable typetab; - + /** * query parameter table */ protected ParameterTable paramtab; - + /** * variable table */ protected VariableTable vartab; - + /** * */ protected ErrorMsg errorMsg; - + /** * Result class for this query. This class is set by setClass. */ - protected ClassType candidateClass; - + protected ClassType candidateClass; + /** * */ @@ -124,28 +125,28 @@ options * */ public void reportError(RecognitionException ex) { - errorMsg.fatal("Error: " + ex); //NOI18N + errorMsg.fatal("Error: " + ex); } /** * */ public void reportError(String s) { - errorMsg.fatal("Error: " + s); //NOI18N + errorMsg.fatal("Error: " + s); } - + /** * Combines partial ASTs into one query AST. */ - public JQLAST createQueryAST(JQLAST candidateClass, - JQLAST importsAST, - JQLAST paramsAST, - JQLAST varsAST, + public JQLAST createQueryAST(JQLAST candidateClass, + JQLAST importsAST, + JQLAST paramsAST, + JQLAST varsAST, JQLAST orderingAST, JQLAST resultAST, JQLAST filterAST) { - JQLAST query = new JQLAST(QUERY, "query", null); //NOI18N + JQLAST query = new JQLAST(QUERY, "query", null); if (candidateClass != null) query.addChild(candidateClass); if (importsAST != null) @@ -162,7 +163,7 @@ options query.addChild(filterAST); return query; } - + /** * Creates the CLASS_DEF AST that represents the setClass value. */ @@ -172,10 +173,10 @@ options if (type == null) { errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.semantic.checkcandidateclass.unknowntype", //NOI18N + "jqlc.semantic.checkcandidateclass.unknowntype", String.valueOf(candidateClass))); } - return new JQLAST(CLASS_DEF, "classDef", type); //NOI18N + return new JQLAST(CLASS_DEF, "classDef", type); } /** @@ -192,7 +193,7 @@ options if (!exprType.isOrderable()) { errorMsg.error(expr.getLine(), expr.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analyseorderingexpression.notorderable", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.analyseorderingexpression.notorderable", exprType.getName())); expr.setJQLType(typetab.errorType); } @@ -223,8 +224,8 @@ options } break; default: - errorMsg.error(expr.getLine(), expr.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.checkvalidorderingexpr.invalidordering", //NOI18N + errorMsg.error(expr.getLine(), expr.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.checkvalidorderingexpr.invalidordering", expr.getText())); } } @@ -265,9 +266,9 @@ options case SUM: if (!typetab.isNumberType(expr.getJQLType()) || typetab.isCharType(expr.getJQLType())) { - errorMsg.error(expr.getLine(), expr.getColumn(), + errorMsg.error(expr.getLine(), expr.getColumn(), I18NHelper.getMessage(messages, - "jqlc.semantic.checkvalidresultexpr.invalidavgsumexpr", //NOI18N + "jqlc.semantic.checkvalidresultexpr.invalidavgsumexpr", expr.getJQLType().getName(), expr.getText())); } checkValidResultExpr((JQLAST)expr.getFirstChild()); @@ -275,19 +276,19 @@ options case MAX: case MIN: if (!expr.getJQLType().isOrderable()) { - errorMsg.error(expr.getLine(), expr.getColumn(), + errorMsg.error(expr.getLine(), expr.getColumn(), I18NHelper.getMessage(messages, - "jqlc.semantic.checkvalidresultexpr.invalidminmaxexpr", //NOI18N + "jqlc.semantic.checkvalidresultexpr.invalidminmaxexpr", expr.getJQLType().getName(), expr.getText())); } checkValidResultExpr((JQLAST)expr.getFirstChild()); break; case COUNT: checkValidResultExpr((JQLAST)expr.getFirstChild()); - break; + break; default: - errorMsg.error(expr.getLine(), expr.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.checkvalidresultexpr.invalidresult", //NOI18N + errorMsg.error(expr.getLine(), expr.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.checkvalidresultexpr.invalidresult", expr.getText())); } } @@ -328,20 +329,20 @@ options StringBuffer buf = new StringBuffer(); genPathExpression(resultReturnAST, buf); String resultReturnPathExpr = buf.toString(); - + for (AST sibling = ordering; sibling != null && sibling.getType() == ORDERING_DEF; sibling = sibling.getNextSibling()) { - + // share buf buf.setLength(0); genPathExpression(sibling.getFirstChild().getNextSibling(), buf); String orderingItemExpr = buf.toString(); if (!orderingItemExpr.equals(resultReturnPathExpr)) { - errorMsg.error(ordering.getLine(), ordering.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.checkresultordering.invalidorderingfordistinctresultfield", //NOI18N - resultReturnPathExpr, orderingItemExpr)); + errorMsg.error(ordering.getLine(), ordering.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.checkresultordering.invalidorderingfordistinctresultfield", + resultReturnPathExpr, orderingItemExpr)); } } } else if (resultReturnAST.getType() == NAVIGATION || @@ -349,11 +350,11 @@ options StringBuffer buf = new StringBuffer(); genPathExpression(resultReturnAST, buf); String resultReturnPathExpr = buf.toString(); - + for (AST sibling = ordering; sibling != null && sibling.getType() == ORDERING_DEF; sibling = sibling.getNextSibling()) { - + // share buf buf.setLength(0); genPathExpression(sibling.getFirstChild().getNextSibling().getFirstChild(), buf); @@ -361,10 +362,10 @@ options if (!orderingRootExpr.equals(resultReturnPathExpr)) { buf.setLength(0); genPathExpression(sibling.getFirstChild().getNextSibling(), buf); - errorMsg.error(ordering.getLine(), ordering.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.checkresultordering.invalidorderingfordistinctresult", //NOI18N - resultReturnPathExpr, buf.toString())); + errorMsg.error(ordering.getLine(), ordering.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.checkresultordering.invalidorderingfordistinctresult", + resultReturnPathExpr, buf.toString())); } } } @@ -397,11 +398,11 @@ options } } - + /** * This method analyses a dot expression of the form expr.ident or * expr.ident(params) where expr itself can again be a dot expression. - * It checks whether the dot expression is + * It checks whether the dot expression is * - part of a qualified class name specification * - field access, * - a method call @@ -429,7 +430,7 @@ options if (fieldInfo == null) { errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknownfield", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknownfield", ident.getText(), exprType.getName())); dot.setJQLType(typetab.errorType); ident.setJQLType(typetab.errorType); @@ -461,8 +462,8 @@ options { return analyseMathCall(dot, expr, ident, args); } - errorMsg.error(dot.getLine(), dot.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + errorMsg.error(dot.getLine(), dot.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); dot.setJQLType(typetab.errorType); return dot; } @@ -470,7 +471,7 @@ options else { errorMsg.error(expr.getLine(), expr.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analysedotexpr.classexprexpected", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.analysedotexpr.classexprexpected", ident.getText(), exprType.getName())); dot.setJQLType(typetab.errorType); return dot; @@ -478,9 +479,9 @@ options } /** - * + * */ - protected JQLAST analyseFieldAccess(JQLAST access, JQLAST objectExpr, JQLAST ident, + protected JQLAST analyseFieldAccess(JQLAST access, JQLAST objectExpr, JQLAST ident, ClassType classType, FieldInfo fieldInfo) { String name = ident.getText(); @@ -489,9 +490,9 @@ options { if (!fieldInfo.isPersistent()) { - errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysefieldaccess.nonperistentfield", name, classType.getName())); //NOI18N + errorMsg.error(ident.getLine(), ident.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.analysefieldaccess.nonperistentfield", name, classType.getName())); } if (typetab.isPersistenceCapableType(fieldType)) { @@ -506,9 +507,9 @@ options { if (!fieldInfo.isPublic()) { - errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysefieldaccess.nonpublicfield", name, classType.getName())); //NOI18N + errorMsg.error(ident.getLine(), ident.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.analysefieldaccess.nonpublicfield", name, classType.getName())); } access.setType(FIELD_ACCESS); } @@ -521,24 +522,24 @@ options } /** - * + * */ - protected JQLAST analyseStaticFieldAccess(JQLAST access, JQLAST typename, JQLAST ident, + protected JQLAST analyseStaticFieldAccess(JQLAST access, JQLAST typename, JQLAST ident, ClassType classType, FieldInfo fieldInfo) { String name = ident.getText(); Type fieldType = fieldInfo.getType(); if (!fieldInfo.isStatic()) { - errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analysestaticfieldaccess.staticreference", //NOI18N + errorMsg.error(ident.getLine(), ident.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.analysestaticfieldaccess.staticreference", ident.getText(), classType.getName())); } if (!fieldInfo.isPublic()) { - errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysestaticfieldaccess.nonpublicfield", name, classType.getName())); //NOI18N + errorMsg.error(ident.getLine(), ident.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.analysestaticfieldaccess.nonpublicfield", name, classType.getName())); } access.setType(STATIC_FIELD_ACCESS); access.setText(typename.getText() + '.' + name); @@ -550,12 +551,12 @@ options } /** - * This method analyses and identifier defined in the current scope: + * This method analyses and identifier defined in the current scope: * - a field, variable or parameter defined in the symbol table * - a type define in a separate symbol table for type names * @param ident the identifier AST * @param def the entry in the symbol table of the type names tables - * @return AST node representing a defined identifier + * @return AST node representing a defined identifier */ protected JQLAST analyseDefinedIdentifier(JQLAST ident, Definition def) { @@ -565,8 +566,8 @@ options ident.setType(VARIABLE); } else if (def instanceof Parameter) - { - ident.setType(PARAMETER); + { + ident.setType(PARAMETER); } else if (def instanceof Field) { @@ -576,13 +577,13 @@ options if (fieldInfo.isStatic()) { JQLAST typeNameAST = new JQLAST(TYPENAME, candidateClass.getName(), candidateClass); - ident = analyseStaticFieldAccess(fieldAccessAST, typeNameAST, + ident = analyseStaticFieldAccess(fieldAccessAST, typeNameAST, identAST, candidateClass, fieldInfo); } else { - JQLAST thisAST = new JQLAST(THIS, "this", candidateClass); //NOI18N - ident = analyseFieldAccess(fieldAccessAST, thisAST, + JQLAST thisAST = new JQLAST(THIS, "this", candidateClass); + ident = analyseFieldAccess(fieldAccessAST, thisAST, identAST, candidateClass, fieldInfo); } } @@ -595,22 +596,22 @@ options { type = typetab.errorType; errorMsg.fatal(I18NHelper.getMessage(messages, - "jqlc.semantic.analysedefinedidentifier.illegalident", //NOI18N + "jqlc.semantic.analysedefinedidentifier.illegalident", String.valueOf(def))); } ident.setJQLType(type); return ident; } - + /** - * Analyses a call for an object that implements Collection. + * Analyses a call for an object that implements Collection. * Currently, contains is the only valid Collection method in a query filter. */ protected JQLAST analyseCollectionCall(JQLAST dot, JQLAST collection, JQLAST method, JQLAST args) { String methodName = method.getText(); JQLAST firstArg = (JQLAST)args.getFirstChild(); - if (methodName.equals("contains")) //NOI18N + if (methodName.equals("contains")) { checkContainsArgs(collection, method, firstArg); dot.setType(CONTAINS); @@ -619,7 +620,7 @@ options collection.setNextSibling(firstArg); return dot; } - else if (methodName.equals("isEmpty")) //NOI18N + else if (methodName.equals("isEmpty")) { // isEmpty does not take parameters checkNoArgs(method, firstArg); @@ -629,9 +630,9 @@ options collection.setNextSibling(null); return dot; } - - errorMsg.error(dot.getLine(), dot.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + + errorMsg.error(dot.getLine(), dot.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); dot.setJQLType(typetab.errorType); return dot; } @@ -644,7 +645,7 @@ options { String methodName = method.getText(); JQLAST firstArg = (JQLAST)args.getFirstChild(); - if (methodName.equals("startsWith")) //NOI18N + if (methodName.equals("startsWith")) { dot.setType(STARTS_WITH); checkOneStringArg(method, firstArg); @@ -652,7 +653,7 @@ options dot.setFirstChild(string); string.setNextSibling(firstArg); } - else if (methodName.equals("endsWith")) //NOI18N + else if (methodName.equals("endsWith")) { dot.setType(ENDS_WITH); checkOneStringArg(method, firstArg); @@ -660,7 +661,7 @@ options dot.setFirstChild(string); string.setNextSibling(firstArg); } - else if (methodName.equals("like")) //NOI18N + else if (methodName.equals("like")) { checkLikeArgs(method, firstArg); dot.setType(LIKE); @@ -668,7 +669,7 @@ options dot.setFirstChild(string); string.setNextSibling(firstArg); } - else if (methodName.equals("substring")) //NOI18N + else if (methodName.equals("substring")) { checkTwoIntArgs(method, firstArg); dot.setType(SUBSTRING); @@ -676,7 +677,7 @@ options dot.setFirstChild(string); string.setNextSibling(firstArg); } - else if (methodName.equals("indexOf")) //NOI18N + else if (methodName.equals("indexOf")) { checkIndexOfArgs(method, firstArg); dot.setType(INDEXOF); @@ -684,7 +685,7 @@ options dot.setFirstChild(string); string.setNextSibling(firstArg); } - else if (methodName.equals("length")) //NOI18N + else if (methodName.equals("length")) { // length does not take parameters checkNoArgs(method, firstArg); @@ -695,8 +696,8 @@ options } else { - errorMsg.error(dot.getLine(), dot.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + errorMsg.error(dot.getLine(), dot.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); dot.setJQLType(typetab.errorType); } return dot; @@ -709,14 +710,14 @@ options { String methodName = method.getText(); JQLAST firstArg = (JQLAST)args.getFirstChild(); - if (methodName.equals("abs")) //NOI18N + if (methodName.equals("abs")) { checkAbsArgs(method, firstArg); dot.setType(ABS); dot.setJQLType(firstArg.getJQLType()); dot.setFirstChild(firstArg); } - else if (methodName.equals("sqrt")) //NOI18N + else if (methodName.equals("sqrt")) { checkSqrtArgs(method, firstArg); dot.setType(SQRT); @@ -725,45 +726,45 @@ options } else { - errorMsg.error(dot.getLine(), dot.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + errorMsg.error(dot.getLine(), dot.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); dot.setJQLType(typetab.errorType); } return dot; } /** - * This method checks the specified node (args) representing an empty + * This method checks the specified node (args) representing an empty * argument list. */ protected void checkNoArgs(JQLAST method, JQLAST firstArg) { - if (firstArg != null) + if (firstArg != null) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } } /** - * This method checks the specified node (args) representing an argument - * list which consists of a single argument of type String. + * This method checks the specified node (args) representing an argument + * list which consists of a single argument of type String. */ protected void checkOneStringArg(JQLAST method, JQLAST firstArg) { if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling() != null) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -771,15 +772,15 @@ options if (!argType.equals(typetab.stringType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", argType.getName(), typetab.stringType.getName())); } } } /** - * This method checks the specified node (args) representing a valid contains + * This method checks the specified node (args) representing a valid contains * argument list: one argument denoting a variable. */ protected void checkContainsArgs(JQLAST collection, JQLAST method, JQLAST firstArg) @@ -787,38 +788,38 @@ options if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling() != null) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getType() != VARIABLE) { errorMsg.unsupported(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysecollectioncall.nonvariable")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.analysecollectioncall.nonvariable")); } else { FieldInfo collectionFieldInfo = getCollectionField(collection); if (collectionFieldInfo == null) { - errorMsg.unsupported(collection.getLine(), collection.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysecollectioncall.unsupportedcollectionexpr", //NOI18N + errorMsg.unsupported(collection.getLine(), collection.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.analysecollectioncall.unsupportedcollectionexpr", collection.getText())); } else if (!collectionFieldInfo.isRelationship()) { // check compatibilty of collection element type and type of variable errorMsg.error(collection.getLine(), collection.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysecollectioncall.relationshipexpected", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.analysecollectioncall.relationshipexpected", collectionFieldInfo.getName())); } Type variableType = firstArg.getJQLType(); @@ -826,15 +827,15 @@ options if (!elementType.isCompatibleWith(variableType)) { errorMsg.error(collection.getLine(), collection.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysecollectioncall.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.analysecollectioncall.typemismatch", elementType.getName(), variableType.getName())); } } } /** - * This method checks the specified node (args) representing a valid like + * This method checks the specified node (args) representing a valid like * argument list: a string argument plus an optional char argument. */ protected void checkLikeArgs(JQLAST method, JQLAST firstArg) @@ -842,16 +843,16 @@ options if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } - else if ((firstArg.getNextSibling() != null) && + else if ((firstArg.getNextSibling() != null) && (firstArg.getNextSibling().getNextSibling() != null)) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling().getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -860,8 +861,8 @@ options if (!firstArgType.equals(typetab.stringType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", firstArgType.getName(), typetab.stringType.getName())); } // check type of second arg (if available) @@ -872,8 +873,8 @@ options if (!typetab.isCharType(secondArgType)) { errorMsg.error(secondArg.getLine(), secondArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", secondArgType.getName(), typetab.charType.getName())); } } @@ -881,7 +882,7 @@ options } /** - * This method checks the specified node (args) representing an argument + * This method checks the specified node (args) representing an argument * list which consists of two integer arguments. */ protected void checkTwoIntArgs(JQLAST method, JQLAST firstArg) @@ -890,23 +891,23 @@ options { // no args specified errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling() == null) { // one arg specified errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling().getNextSibling() != null) { // more than two args specified JQLAST nextArg = (JQLAST)firstArg.getNextSibling().getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -916,8 +917,8 @@ options if (!typetab.isIntType(firstArgType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", firstArgType.getName(), typetab.intType.getName())); } // check type of second arg @@ -926,15 +927,15 @@ options if (!typetab.isIntType(secondArgType)) { errorMsg.error(secondArg.getLine(), secondArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", secondArgType.getName(), typetab.intType.getName())); } } } /** - * This method checks the specified node (args) representing a valid indexOf + * This method checks the specified node (args) representing a valid indexOf * argument list: a string argument plus an optional char argument. */ protected void checkIndexOfArgs(JQLAST method, JQLAST firstArg) @@ -942,16 +943,16 @@ options if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } - else if ((firstArg.getNextSibling() != null) && + else if ((firstArg.getNextSibling() != null) && (firstArg.getNextSibling().getNextSibling() != null)) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling().getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -960,8 +961,8 @@ options if (!firstArgType.equals(typetab.stringType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", firstArgType.getName(), typetab.stringType.getName())); } // check type of second arg (if available) @@ -972,8 +973,8 @@ options if (!typetab.isIntType(secondArgType)) { errorMsg.error(secondArg.getLine(), secondArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", secondArgType.getName(), typetab.intType.getName())); } } @@ -989,15 +990,15 @@ options if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling() != null) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -1005,8 +1006,8 @@ options if (!typetab.isNumberType(argType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", argType.getName(), "number type")); } } @@ -1021,15 +1022,15 @@ options if (firstArg == null) { errorMsg.error(method.getLine(), method.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else if (firstArg.getNextSibling() != null) { JQLAST nextArg = (JQLAST)firstArg.getNextSibling(); errorMsg.error(nextArg.getLine(), nextArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.numbermismatch")); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.numbermismatch")); } else { @@ -1037,8 +1038,8 @@ options if (!typetab.isDoubleType(argType)) { errorMsg.error(firstArg.getLine(), firstArg.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.arguments.typemismatch", //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.arguments.typemismatch", argType.getName(), "double or Double")); } } @@ -1060,14 +1061,14 @@ options String fieldName = child.getNextSibling().getText(); return classType.getFieldInfo(fieldName); } - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.semantic.getcollectionfield.missingchildren")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.semantic.getcollectionfield.missingchildren")); break; case TYPECAST: if ((child != null) && (child.getNextSibling() != null)) { return getCollectionField((JQLAST)child.getNextSibling()); } - errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.semantic.getcollectionfield.missingchildren")); //NOI18N + errorMsg.fatal(I18NHelper.getMessage(messages, "jqlc.semantic.getcollectionfield.missingchildren")); break; } return null; @@ -1076,7 +1077,7 @@ options /** * Analyses a bitwise/logical operation (&, |, ^) * @param op the bitwise/logical operator - * @param leftAST left operand + * @param leftAST left operand * @param rightAST right operand * @return Type */ @@ -1084,11 +1085,11 @@ options { Type left = leftAST.getJQLType(); Type right = rightAST.getJQLType(); - + // handle error type if (left.equals(typetab.errorType) || right.equals(typetab.errorType)) return typetab.errorType; - + switch(op.getType()) { case BAND: @@ -1097,8 +1098,8 @@ options return typetab.booleanType; else if (typetab.isIntegralType(left) || typetab.isIntegralType(right)) { - errorMsg.unsupported(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analysebitwiseexpr.integerbitwiseop", //NOI18N + errorMsg.unsupported(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.analysebitwiseexpr.integerbitwiseop", op.getText())); return typetab.errorType; } @@ -1106,15 +1107,15 @@ options case BXOR: if (typetab.isBooleanType(left) && typetab.isBooleanType(right)) { - errorMsg.unsupported(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.analysebitwiseexpr.exclusiveorop")); //NOI18N + errorMsg.unsupported(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, + "jqlc.semantic.analysebitwiseexpr.exclusiveorop")); return typetab.errorType; } else if (typetab.isIntegralType(left) || typetab.isIntegralType(right)) { - errorMsg.unsupported(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analysebitwiseexpr.integerbitwiseop", //NOI18N + errorMsg.unsupported(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.analysebitwiseexpr.integerbitwiseop", op.getText())); return typetab.errorType; } @@ -1122,16 +1123,16 @@ options } // if this code is reached a bitwise operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } - + /** * Analyses a boolean conditional operation (&&, ||) * @param op the conditional operator - * @param leftAST left operand + * @param leftAST left operand * @param rightAST right operand * @return Type */ @@ -1152,10 +1153,10 @@ options return typetab.booleanType; break; } - + // if this code is reached a conditional operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } @@ -1163,9 +1164,9 @@ options /** * Analyses a relational operation (<, <=, >, >=, ==, !=) * @param op the relational operator - * @param leftAST left operand + * @param leftAST left operand * @param rightAST right operand - * @return Type + * @return Type */ protected Type analyseRelationalExpr(JQLAST op, JQLAST leftAST, JQLAST rightAST) { @@ -1187,14 +1188,14 @@ options if (!left.isOrderable()) { errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analyserelationalexpr.notorderable", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.analyserelationalexpr.notorderable", left.getName(), op.getText())); return typetab.errorType; } if (!right.isOrderable()) { errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.analyserelationalexpr.notorderable", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.analyserelationalexpr.notorderable", right.getName(), op.getText())); return typetab.errorType; } @@ -1204,13 +1205,13 @@ options if ((leftAST.getType() == CONTAINS) || (rightAST.getType() == CONTAINS)) { errorMsg.unsupported(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.unsupportedconstraintop", op.getText())); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.unsupportedconstraintop", op.getText())); return typetab.errorType; } break; } - + // check for numeric types, numeric wrapper class types and math class types if (typetab.isNumberType(left) && typetab.isNumberType(right)) return typetab.booleanType; @@ -1221,18 +1222,18 @@ options if (left.isCompatibleWith(right) || right.isCompatibleWith(left)) return typetab.booleanType; - + // if this code is reached a conditional operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } - + /** - * Analyses a + * Analyses a * @param op the operator - * @param leftAST left operand + * @param leftAST left operand * @param rightAST right operand * @return Type */ @@ -1252,22 +1253,22 @@ options return left; if (right.isCompatibleWith(typetab.bigDecimalType)) return right; - + // handle java.math.BigInteger if (left.isCompatibleWith(typetab.bigIntegerType)) { - // if right is floating point return BigDecimal, + // if right is floating point return BigDecimal, // otherwise return BigInteger - return typetab.isFloatingPointType(right) ? + return typetab.isFloatingPointType(right) ? typetab.bigDecimalType : left; } if (right.isCompatibleWith(typetab.bigIntegerType)) { - // if left is floating point return BigDecimal, + // if left is floating point return BigDecimal, // otherwise return BigInteger - return typetab.isFloatingPointType(left) ? + return typetab.isFloatingPointType(left) ? typetab.bigDecimalType : right; - } + } boolean wrapper = false; if (left instanceof NumericWrapperClassType) @@ -1280,13 +1281,13 @@ options right = ((NumericWrapperClassType)right).getPrimitiveType(); wrapper = true; } - + // handle numeric types with arbitrary arithmetic operator if ((left instanceof NumericType) && (right instanceof NumericType)) { Type promotedType = typetab.binaryNumericPromotion(left, right); if (wrapper && (promotedType instanceof NumericType)) - { + { promotedType = ((NumericType)promotedType).getWrapper(); } return promotedType; @@ -1296,8 +1297,8 @@ options { // handle + for strings // MBO: note, this if matches char + char (which it should'nt), - // but this case is already handled above - if ((left.equals(typetab.stringType) || left.equals(typetab.charType)) && + // but this case is already handled above + if ((left.equals(typetab.stringType) || left.equals(typetab.charType)) && (right.equals(typetab.stringType) || right.equals(typetab.charType))) { return typetab.stringType; @@ -1305,17 +1306,17 @@ options } // if this code is reached a conditional operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } /** - * Analyses a + * Analyses a * @param op the operator * @param argAST right operand - * @return Type + * @return Type */ protected Type analyseUnaryArithmeticExpr(JQLAST op, JQLAST argAST) { @@ -1324,7 +1325,7 @@ options // handle error type if (arg.equals(typetab.errorType)) return typetab.errorType; - + // handle java.math.BigDecimal and java.math.BigInteger if (arg.isCompatibleWith(typetab.bigDecimalType)) return arg; @@ -1349,18 +1350,18 @@ options } return promotedType; } - + // if this code is reached a conditional operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } /** - * Analyses a + * Analyses a * @param op the operator * @param argAST right operand - * @return Type + * @return Type */ protected Type analyseComplementExpr(JQLAST op, JQLAST argAST) { @@ -1384,22 +1385,22 @@ options if (argAST.getType() == CONTAINS) { errorMsg.unsupported(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, - "jqlc.semantic.generic.unsupportedconstraintop", op.getText())); //NOI18N + I18NHelper.getMessage(messages, + "jqlc.semantic.generic.unsupportedconstraintop", op.getText())); return typetab.errorType; } return arg; } break; } - + // if this code is reached a conditional operator was used with invalid arguments - errorMsg.error(op.getLine(), op.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", //NOI18N + errorMsg.error(op.getLine(), op.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.arguments.invalid", op.getText())); return typetab.errorType; } - + /** * */ @@ -1416,7 +1417,7 @@ options if (ast == null) return; switch (ast.getType()) { - case VARIABLE: + case VARIABLE: tab.markUsed(ast, dependentVariable); break; case CONTAINS: @@ -1451,8 +1452,8 @@ options query : #( QUERY - { - symtab.enterScope(); + { + symtab.enterScope(); typeNames.enterScope(); } candidateClass @@ -1466,12 +1467,12 @@ query o:ordering r:result filter - { + { typeNames.leaveScope(); // leaves variable and parameter name scope symtab.leaveScope(); // leaves global scope - symtab.leaveScope(); + symtab.leaveScope(); } ) { @@ -1484,8 +1485,8 @@ query // ---------------------------------- candidateClass -{ - errorMsg.setContext("setClass"); //NOI18N +{ + errorMsg.setContext("setClass"); } : c:CLASS_DEF { @@ -1495,7 +1496,7 @@ candidateClass if (!candidateClass.isPersistenceCapable()) { errorMsg.unsupported(#c.getLine(), #c.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.candidateclass.nonpc", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.candidateclass.nonpc", className)); } @@ -1519,8 +1520,8 @@ candidateClass // ---------------------------------- imports! -{ - errorMsg.setContext("declareImports"); //NOI18N +{ + errorMsg.setContext("declareImports"); } : ( declareImport )* ; @@ -1533,7 +1534,7 @@ declareImport if (type == null) { errorMsg.error(#i.getLine(), #i.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknowntype", name)); //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknowntype", name)); } // get base name @@ -1544,7 +1545,7 @@ declareImport if (old != null) { errorMsg.error(#i.getLine(), #i.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", identName, old.getName())); } } @@ -1555,8 +1556,8 @@ declareImport // ---------------------------------- parameters -{ - errorMsg.setContext("declareParameters"); //NOI18N +{ + errorMsg.setContext("declareParameters"); } : ( declareParameter )* ; @@ -1570,11 +1571,11 @@ declareParameter if (old != null) { errorMsg.error(#i.getLine(), #i.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", name, old.getName())); } #i.setJQLType(type); - paramtab.add(name, type); + paramtab.add(name, type); } ; @@ -1582,9 +1583,9 @@ declareParameter // rules: variable declaration // ---------------------------------- -variables -{ - errorMsg.setContext("declareVariables"); //NOI18N +variables +{ + errorMsg.setContext("declareVariables"); } : ( declareVariable )* ; @@ -1598,7 +1599,7 @@ declareVariable if (old != null) { errorMsg.error(#i.getLine(), #i.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.alreadydeclared", name, old.getName())); } vartab.add(name); @@ -1610,9 +1611,9 @@ declareVariable // rules: ordering specification // ---------------------------------- -ordering -{ - errorMsg.setContext("setOrdering"); //NOI18N +ordering +{ + errorMsg.setContext("setOrdering"); } : ( orderSpec )* ; @@ -1630,8 +1631,8 @@ orderSpec // ---------------------------------- result -{ - errorMsg.setContext("setResult"); //NOI18N +{ + errorMsg.setContext("setResult"); } : #( r:RESULT_DEF e:resultExpr ) { @@ -1675,12 +1676,12 @@ resultExpr // ---------------------------------- filter -{ - errorMsg.setContext("setFilter"); //NOI18N +{ + errorMsg.setContext("setFilter"); } // There is always a filter defined and it is the last node of the query tree. // Otherwise all the remaining subtrees after the CLASS_DEF subtree are empty - // which results in a ClassCastException antlr.ASTNullType when analysis + // which results in a ClassCastException antlr.ASTNullType when analysis // the (non existsent) subtrees : #( FILTER_DEF e:expression ) { @@ -1689,7 +1690,7 @@ filter { // filter expression must have the type boolean or java.lang.Boolean errorMsg.error(#e.getLine(), #e.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.filter.booleanexpected", exprType)); //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.filter.booleanexpected", exprType)); } checkConstraints(#e, vartab); vartab.checkConstraints(); @@ -1704,7 +1705,7 @@ expression { #e.setJQLType(typetab.errorType); errorMsg.error(#e.getLine(), #e.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.expression.undefined", repr)); //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.expression.undefined", repr)); } } ; @@ -1849,7 +1850,7 @@ complementExpr ; primary [boolean insideDotExpr] returns [String repr] -{ repr = null; } +{ repr = null; } : #( c:TYPECAST t:type e:expression ) { Type type = #t.getJQLType(); @@ -1857,7 +1858,7 @@ primary [boolean insideDotExpr] returns [String repr] if (!(type.isCompatibleWith(exprType) || exprType.isCompatibleWith(type))) { errorMsg.error(#c.getLine(), #c.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.primary.invalidcast", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.primary.invalidcast", exprType.getName(), type.getName())); type = typetab.errorType; } @@ -1869,13 +1870,13 @@ primary [boolean insideDotExpr] returns [String repr] | repr = dotExpr | repr = identifier [insideDotExpr] ; - + dotExpr returns [String repr] { repr = null; } - : #( dot:DOT - repr = expr:exprNoCheck[true] ident:IDENT ( args:argList )? + : #( dot:DOT + repr = expr:exprNoCheck[true] ident:IDENT ( args:argList )? ) { Type type = null; @@ -1902,8 +1903,8 @@ dotExpr returns [String repr] // found valid class name and arguments specified => // looks like constructor call repr = null; - errorMsg.error(dot.getLine(), dot.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + errorMsg.error(dot.getLine(), dot.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); } #dot.setJQLType(type); #dot.setText(#expr.getText() + '.' + #ident.getText()); @@ -1932,8 +1933,8 @@ identifier [boolean insideDotExpr] returns [String repr] if (#args != null) { #ident.setJQLType(typetab.errorType); - errorMsg.error(#ident.getLine(), #ident.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); //NOI18N + errorMsg.error(#ident.getLine(), #ident.getColumn(), + I18NHelper.getMessage(messages, "jqlc.semantic.generic.invalidmethodcall")); } else if (def != null) { @@ -1946,7 +1947,7 @@ identifier [boolean insideDotExpr] returns [String repr] { #ident = analyseDefinedIdentifier(#ident, typedef); } - else + else { repr = #ident.getText(); } @@ -1955,7 +1956,7 @@ identifier [boolean insideDotExpr] returns [String repr] { #ident.setJQLType(typetab.errorType); errorMsg.error(ident.getLine(), ident.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.identifier.undefined", //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.identifier.undefined", ident.getText())); } } @@ -2003,8 +2004,8 @@ type else { errorMsg.error(#qn.getLine(), #qn.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.type.notype", //NOI18N - name, def.getName())); + I18NHelper.getMessage(messages, "jqlc.semantic.type.notype", + name, def.getName())); } } else @@ -2012,13 +2013,13 @@ type type = typetab.checkType(name); if ((type == null) && (name.indexOf('.') == -1)) { - // ckeck java.lang class without package name - type = typetab.checkType("java.lang." + name); //NOI18N + // ckeck java.lang class without package name + type = typetab.checkType("java.lang." + name); } if (type == null) { errorMsg.error(#qn.getLine(), #qn.getColumn(), - I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknowntype", name)); //NOI18N + I18NHelper.getMessage(messages, "jqlc.semantic.generic.unknowntype", name)); } } // change AST to a single node that represents the full class name diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ActionDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ActionDesc.java index f6de2534ef8..c49457d62cc 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ActionDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ActionDesc.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 */ -/* - * ActionDesc.java - * - * Create on March 3, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore; @@ -336,6 +331,6 @@ public interface ActionDesc { /** */ - public Class getPersistenceCapableClass(); + public Class getPersistenceCapableClass(); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/Bundle.properties b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/Bundle.properties index ed4de1d22bc..67edcc3cad6 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/Bundle.properties +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/Bundle.properties @@ -329,7 +329,6 @@ core.constraint.stackempty=JDO76309: The constraint stack is empty -- not enough core.constraint.unknownfield=JDO76310: The field {0} specified in the retrieve descriptor is not a member of the class {1}. core.constraint.valdisallowed=JDO76311: The value parameter was specified, but it is disallowed with the operation {0}. core.constraint.valrequired=JDO76312: The value parameter is missing, but the operation {0} requires a value. -sqlstore.resultdesc.errorgettingvalefromresulset=JDO76313: Error while getting value from resultset at index {0} as resultType {1}. columnSqlType {2}. Exception: {3} sqlstore.resultdesc.foreignfieldprojection=JDO76314: Queries for {0} should not have projections on a relationship field. sqlstore.resultdesc.unknownfieldtype=JDO76317: Encountered unknown field type {0}. sqlstore.retrievedesc.toomanyprojections=JDO76318: Cannot set more than one projection for a RetrieveDesc. @@ -513,7 +512,6 @@ sqlstore.database.dbvendor.gettableliststart=<-> DBVendorType.getTableListStart( sqlstore.database.dbvendor.isAnsiTrim=<-> DBVendorType.isAnsiTrim(): {0}. sqlstore.database.dbvendor.isInlineNumeric=<-> DBVendorType.isInlineNumeric(): {0}. sqlstore.database.dbvendor.isNativeOuterJoin=<-> DBVendorType.isNativeOuterJoin(): {0}. -sqlstore.database.dbvendor.isParameterCast=<-> DBVendorType.isParameterCast(): {0}. sqlstore.database.dbvendor.isdistinctupdatelocksupported=<-> DBVendorType.isDistinctSupportedWithUpdateLock(): {0}. sqlstore.database.dbvendor.islockcolumnlistsupported=<-> DBVendorType.isLockColumnListSupported(): {0}. sqlstore.database.dbvendor.isupdatelocksupported=<-> DBVendorType.isUpdateLockSupported(): {0}. @@ -522,18 +520,6 @@ sqlstore.database.dbvendor.overrideproperties.with=<-> DBVendorType.overrideProp sqlstore.database.dbvendor.overrideproperties=<-> DBVendorType.overrideProperties() - NONE. sqlstore.database.dbvendor.supportslikeescape=<-> DBVendorType.supportsLikeEscape(): {0}. sqlstore.database.dbvendor.vendorname=<-> DBVendorType(), vendorName: [{0}] vendorType: {1}. -# -# -# -sqlstore.transactionimpl.call.info={0} Tran[ {1} ].{2}: {3} for {4}. -sqlstore.transactionimpl.call={0} Tran[ {1} ].{2}:status = {3}, txType: {4} for {5}. -sqlstore.transactionimpl.closeconnection=--- TransactionImpl.closeConnection() {0} for {1}. -sqlstore.transactionimpl.general={0}. -sqlstore.transactionimpl.getconnection=--- TransactionImpl.getConnection(): {0} TX optimistic: {1} referenceCount = {2} for {3}. -sqlstore.transactionimpl.releaseconnection=--- TransactionImpl.releaseConnection(): TX optimistic: {0} Inside Commit: {1} referenceCount: {2} for {3}. -sqlstore.transactionimpl.rollbackconnection=--- TransactionImpl.rollbackConnection(): {0} for {1}. -sqlstore.transactionimpl.status={0} Tran[ {1} ].setStatus: {2} => {3} for {4}. - ############################################################################### # All the source files under subdir ejb. @@ -615,5 +601,4 @@ core.generic.notinstanceof=The object of class {0} is not an instance of {1}. # to use different messages > ############################################################################### core.configuration.cantloadclass=Failed to load the class {0}. -sqlstore.exception.log=Exception. jdo.lifecycle.deleted.accessField=Cannot access field of a deleted instance. diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ConfigCache.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ConfigCache.java index e0f9203848f..7a041dfd7fc 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ConfigCache.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ConfigCache.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,7 +32,7 @@ public interface ConfigCache { * @param pcClass The input pcClass. * @return PersistenceConfig for given pcClass. */ - PersistenceConfig getPersistenceConfig(Class pcClass); + PersistenceConfig getPersistenceConfig(Class pcClass); /** * Gets the Class instance corresponding to given oidType. @@ -39,7 +40,7 @@ public interface ConfigCache { * @param oidType The input oidType. * @return The Class instance corresponding to given oidType. */ - Class getClassByOidClass(Class oidType); + Class getClassByOidClass(Class oidType); /** * Sets VersionConsistencyCache field. diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ExtentCollection.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ExtentCollection.java index 9d6615bfd33..c8d689922df 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ExtentCollection.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ExtentCollection.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 */ -/* - * ExtentCollection.java - * - * Created on April 6, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore; import com.sun.jdo.api.persistence.model.Model; @@ -37,8 +32,7 @@ * @author Michael Bouschen * @version 0.1 */ -public class ExtentCollection - implements Collection { +public class ExtentCollection implements Collection { /** * The PersistenceManager getExtent is called from */ @@ -47,7 +41,7 @@ public class ExtentCollection /** * This extent collection reperesents the extent of persistenceCapableClass. */ - protected Class persistenceCapableClass; + protected Class persistenceCapableClass; /** * I18N message handler @@ -60,37 +54,41 @@ public class ExtentCollection * @param persistenceCapableClass Class of instances * @param subclasses whether to include instances of subclasses */ - public ExtentCollection(PersistenceManager pm, Class persistenceCapableClass, boolean subclasses) { + public ExtentCollection(PersistenceManager pm, Class persistenceCapableClass, boolean subclasses) { this.pm = pm; this.persistenceCapableClass = persistenceCapableClass; // check persistenceCapableClass parameter being null - if (persistenceCapableClass == null) + if (persistenceCapableClass == null) { throw new JDOUserException( I18NHelper.getMessage(messages, "jdo.extentcollection.constructor.invalidclass", "null"));// NOI18N + } // check persistence-capable if (Model.RUNTIME.getMappingClass(persistenceCapableClass.getName(), - persistenceCapableClass.getClassLoader()) == null) + persistenceCapableClass.getClassLoader()) == null) { throw new JDOUserException( I18NHelper.getMessage(messages, "jdo.extentcollection.constructor.nonpc", // NOI18N persistenceCapableClass.getName())); + } // subclasses == true is not yet supported - if (subclasses) + if (subclasses) { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.constructor.subclasses"));// NOI18N + } } /** * */ - public Class getPersistenceCapableClass() { + public Class getPersistenceCapableClass() { return persistenceCapableClass; } /** * */ + @Override public int size() { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "size"));// NOI18N @@ -99,6 +97,7 @@ public int size() { /** * */ + @Override public boolean isEmpty() { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "isEmpty"));// NOI18N @@ -107,6 +106,7 @@ public boolean isEmpty() { /** * */ + @Override public boolean contains(Object o) { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "contains"));// NOI18N @@ -115,14 +115,16 @@ public boolean contains(Object o) { /** * */ - public Iterator iterator() { + @Override + public Iterator iterator() { RetrieveDesc rd = pm.getRetrieveDesc(persistenceCapableClass); - return ((Collection)pm.retrieve(rd)).iterator(); + return ((Collection) pm.retrieve(rd)).iterator(); } /** * */ + @Override public Object[] toArray() { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "toArray"));// NOI18N @@ -131,6 +133,7 @@ public Object[] toArray() { /** * */ + @Override public Object[] toArray(Object a[]) { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "toArray"));// NOI18N @@ -139,6 +142,7 @@ public Object[] toArray(Object a[]) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ + @Override public boolean add(Object o) { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N @@ -148,6 +152,7 @@ public boolean add(Object o) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ + @Override public boolean remove(Object o) { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N @@ -157,7 +162,8 @@ public boolean remove(Object o) { /** * */ - public boolean containsAll(Collection c) { + @Override + public boolean containsAll(Collection c) { throw new JDOUnsupportedOptionException( I18NHelper.getMessage(messages, "jdo.extentcollection.methodnotsupported", "containsAll"));// NOI18N } @@ -165,7 +171,8 @@ public boolean containsAll(Collection c) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ - public boolean addAll(Collection c) { + @Override + public boolean addAll(Collection c) { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N persistenceCapableClass.getName())); @@ -174,7 +181,8 @@ public boolean addAll(Collection c) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ - public boolean removeAll(Collection c) { + @Override + public boolean removeAll(Collection c) { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N persistenceCapableClass.getName())); @@ -183,7 +191,8 @@ public boolean removeAll(Collection c) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ - public boolean retainAll(Collection c) { + @Override + public boolean retainAll(Collection c) { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N persistenceCapableClass.getName())); @@ -192,6 +201,7 @@ public boolean retainAll(Collection c) { /** * Extent collection is unmodifiable => throw UnsupportedOperationException */ + @Override public void clear() { throw new UnsupportedOperationException( I18NHelper.getMessage(messages, "jdo.extentcollection.illegalmodification", // NOI18N @@ -201,9 +211,11 @@ public void clear() { /** * Two extent collections are equal, iff the names of their persistence capable class are equal */ + @Override public boolean equals(Object o) { - if (o == this) + if (o == this) { return true; + } if (o instanceof ExtentCollection) { String otherClassName = ((ExtentCollection) o).persistenceCapableClass.getName(); return persistenceCapableClass.getName().equals(otherClassName); @@ -214,6 +226,7 @@ public boolean equals(Object o) { /** * The hashCode is mapped to the hashCode of the name of the extent collection's persistence capable class */ + @Override public int hashCode() { return persistenceCapableClass.getName().hashCode(); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperPersistenceManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperPersistenceManager.java deleted file mode 100644 index 1702f12d6e3..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperPersistenceManager.java +++ /dev/null @@ -1,47 +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.spi.persistence.support.sqlstore; - -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -/** - * - * @author Craig Russell - * @version 1.0 - */ -public class LogHelperPersistenceManager { - - /** The component name for this component - */ - protected static final String componentName = "persistencemanager"; //NOI18N - - /** The class loader for this component - */ - protected static final ClassLoader loader = LogHelperPersistenceManager.class.getClassLoader(); - - /** The bundle name for this component - */ - protected static final String bundleName = "com.sun.jdo.spi.persistence.support.sqlstore.Bundle"; //NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - -} diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperSQLStore.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperSQLStore.java index 5eb7d292cbb..e1483946380 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperSQLStore.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperSQLStore.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,23 +17,22 @@ package com.sun.jdo.spi.persistence.support.sqlstore; -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.util.ResourceBundle; + +import org.glassfish.persistence.common.I18NHelper; /** - * * @author Craig Russell - * @version 1.0 */ -public class LogHelperSQLStore { +public final class LogHelperSQLStore { /** The component name for this component */ - protected static final String componentName = "sqlstore"; //NOI18N + protected static final String componentName = "sqlstore"; /** The component name for SQL logger */ - protected static final String sqlComponentName = componentName + ".sql"; //NOI18N + protected static final String sqlComponentName = componentName + ".sql"; /** The class loader for this component */ @@ -40,16 +40,8 @@ public class LogHelperSQLStore { /** The bundle name for this component */ - protected static final String bundleName = "com.sun.jdo.spi.persistence.support.sqlstore.Bundle"; //NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - - public static Logger getSqlLogger() { - return LogHelper.getLogger (sqlComponentName, bundleName, loader); - } + private static final String BUNDLE = "com.sun.jdo.spi.persistence.support.sqlstore.Bundle"; + public static final ResourceBundle RESOURCE_BUNDLE = I18NHelper.loadBundle(BUNDLE, + LogHelperSQLStore.class.getClassLoader()); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperStateManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperStateManager.java deleted file mode 100644 index 9ae43bf56b3..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperStateManager.java +++ /dev/null @@ -1,47 +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.spi.persistence.support.sqlstore; - -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -/** - * - * @author Craig Russell - * @version 1.0 - */ -public class LogHelperStateManager { - - /** The component name for this component - */ - protected static final String componentName = "statemanager"; //NOI18N - - /** The class loader for this component - */ - protected static final ClassLoader loader = LogHelperStateManager.class.getClassLoader(); - - /** The bundle name for this component - */ - protected static final String bundleName = "com.sun.jdo.spi.persistence.support.sqlstore.Bundle"; //NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - -} diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperTransaction.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperTransaction.java deleted file mode 100644 index cd3b6885f9f..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/LogHelperTransaction.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.spi.persistence.support.sqlstore; - -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -/** - * - * @author Craig Russell - * @version 1.0 - */ -public class LogHelperTransaction { - - /** The component name for this component - */ - protected static final String componentName = "transaction"; //NOI18N - - /** The class loader for this component - */ - protected static final ClassLoader loader = LogHelperTransaction.class.getClassLoader(); - - /** The bundle name for this component - */ - //Resolve : Should we share bundles between various logers in this directory ? - protected static final String bundleName = "com.sun.jdo.spi.persistence.support.sqlstore.Bundle"; //NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - -} diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceConfig.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceConfig.java index a93eb095197..24bbd057619 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceConfig.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceConfig.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,21 +15,17 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * PersistenceConfig.java - * - * Created on March 3, 2000 - * - */ package com.sun.jdo.spi.persistence.support.sqlstore; +import java.lang.reflect.Constructor; + /** */ public interface PersistenceConfig { - Class getPersistenceCapableClass(); + Class getPersistenceCapableClass(); - Class getOidClass(); + Class getOidClass(); java.lang.reflect.Field[] getKeyFields(); @@ -38,5 +35,5 @@ public interface PersistenceConfig boolean hasLocalNonDFGFields(); - java.lang.reflect.Constructor getConstructor(); + Constructor getConstructor(); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceManager.java index f97858b582d..7e1a3ca0e13 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceManager.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceManager.java @@ -1,25 +1,20 @@ /* + * 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 - * terms of the Eclipse Public License v. 2.0, which is available at + * terms of the Eclipse 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, + * Eclipse License v. 2.0 are satisfied: GNU General 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 */ -/* - * PersistenceManager.java - * - * Create on March 3, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore; import com.sun.jdo.spi.persistence.support.sqlstore.impl.PersistenceManagerWrapper; @@ -29,23 +24,23 @@ public interface PersistenceManager extends com.sun.jdo.api.persistence.support.PersistenceManager { - public PersistenceManagerWrapper getCurrentWrapper(); + PersistenceManagerWrapper getCurrentWrapper(); - public Object newInstance(StateManager sm); + Object newInstance(StateManager sm); - public void setStateManager(Object pc, StateManager sm); + void setStateManager(Object pc, StateManager sm); - public void setFlags(Object pc, byte flags); + void setFlags(Object pc, byte flags); - public byte getFlags(Object pc); + byte getFlags(Object pc); - public StateManager getStateManager(Object pc); + StateManager getStateManager(Object pc); - public void setField(Object pc, int fieldNumber, Object value); + void setField(Object pc, int fieldNumber, Object value); - public Object getField(Object pc, int fieldNumber); + Object getField(Object pc, int fieldNumber); - public void clearFields(Object pc); + void clearFields(Object pc); /** * Executes the given retrieve descriptor. The result @@ -61,7 +56,7 @@ public interface PersistenceManager * @return A collection of (persistent) objects unless * an aggregate query was specified. */ - public Object retrieve(RetrieveDesc action, ValueFetcher parameters); + Object retrieve(RetrieveDesc action, ValueFetcher parameters); /** * Executes the given retrieve descriptor. The result @@ -76,45 +71,45 @@ public interface PersistenceManager * @return A collection of (persistent) objects unless * an aggregate query was specified. */ - public Object retrieve(RetrieveDesc action); + Object retrieve(RetrieveDesc action); /** * Return a RetrieveDesc given a Class object. */ - public RetrieveDesc getRetrieveDesc(Class classType); + RetrieveDesc getRetrieveDesc(Class classType); /** * Return a RetrieveDesc for a foreign field (relationship) given the * Class object for the parent class. */ - public RetrieveDesc getRetrieveDesc(String fieldName, Class classType); + RetrieveDesc getRetrieveDesc(String fieldName, Class classType); /** * Called by Transaction commit() or rollback() * cleans up transactional cache * @param status jakarta.transaction.Status */ - public void afterCompletion(int status); + void afterCompletion(int status); /** * Called by Transaction commit() * Loops through transactional cache and calls PersistentStore.updatePersistent() * on each instance */ - public void beforeCompletion(); + void beforeCompletion(); /** * Called by Query in pessimistic transaction * to flush changes to the database */ - public void internalFlush(); + void internalFlush(); /** * Called by StateManager to register new instance. This method will throw * an JDOUserException if throwDuplicateException is true and the object being * registered already exists in the pm cache. */ - public void registerInstance(StateManager sm, Object oid, + void registerInstance(StateManager sm, Object oid, boolean throwDuplicateException, boolean forceRegister); /** @@ -122,53 +117,53 @@ public void registerInstance(StateManager sm, Object oid, * it was removed from the global (weak) cache as the result of the replace * operation. */ - public void registerInstance(StateManager sm, Object oid); + void registerInstance(StateManager sm, Object oid); /** * Deregister an instance. */ - public void deregisterInstance(Object oid); + void deregisterInstance(Object oid); /** * Deregister an instance with this object Id, only if it holds the same instance. */ - public void deregisterInstance(Object oid, StateManager sm); + void deregisterInstance(Object oid, StateManager sm); /** * For Transaction to notify PersistenceManager that * status is changed */ - public void notifyStatusChange(boolean isActive); + void notifyStatusChange(boolean isActive); /** * For Transaction to notify PersistenceManager that * optimistic flag is changed */ - public void notifyOptimistic(boolean optimistic); + void notifyOptimistic(boolean optimistic); /** * Returns true if associated transaction is optimistic */ - public boolean isOptimisticTransaction(); + boolean isOptimisticTransaction(); /** * For Transaction to notify PersistenceManager that * optimistic flag is changed */ - public void notifyNontransactionalRead(boolean nontransactionalRead); + void notifyNontransactionalRead(boolean nontransactionalRead); /** * Returns true if nontransactionalRead flag is set to true. */ - public boolean isNontransactionalRead(); + boolean isNontransactionalRead(); /** * Returns true if associated transaction is active */ - public boolean isActiveTransaction(); + boolean isActiveTransaction(); /** - * Called by newSCOInstance from the public interface or internally + * Called by newSCOInstance from the interface or internally * by the runtime * Will not result in marking field as dirty * @@ -178,10 +173,10 @@ public void registerInstance(StateManager sm, Object oid, * @param fieldName the field to notify upon changes * @return the object of the class type */ - public Object newSCOInstanceInternal (Class type, Object owner, String fieldName); + Object newSCOInstanceInternal (Class type, Object owner, String fieldName); /** - * Called by newCollectionInstance from the public interface + * Called by newCollectionInstance from the interface * or internally by the runtime * Will not result in marking field as dirty * @@ -193,67 +188,67 @@ public void registerInstance(StateManager sm, Object oid, * @param initialSize initial size of the Collection * @return the object of the class type */ - Object newCollectionInstanceInternal (Class type, Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialSize); + Object newCollectionInstanceInternal (Class type, Object owner, String fieldName, + Class elementType, boolean allowNulls, int initialSize); /** * Serialize field updates */ - public void acquireFieldUpdateLock(); + void acquireFieldUpdateLock(); /** * Allow other threads to update fields */ - public void releaseFieldUpdateLock(); + void releaseFieldUpdateLock(); /** * Acquires a share lock from the persistence manager. This method will * put the calling thread to sleep if another thread is holding the exclusive lock. */ - public void acquireShareLock(); + void acquireShareLock(); /** * Releases the share lock and notify any thread waiting to get an exclusive lock. * Note that every releaseShareLock() call needs to be preceeded by an acquireShareLock() call. */ - public void releaseShareLock(); + void releaseShareLock(); /** * Acquires an exclusive lock from the persistence manager. By acquiring an * exclusive lock, a thread is guaranteed to have exclusive right to the persistence * runtime meaning no other threads can perform any operation in the runtime. */ - public void acquireExclusiveLock(); + void acquireExclusiveLock(); /** * Release the exclusive lock and notify any thread waiting to get an exclusive or * share lock. Note that every releaseShareLock() call needs to be preceeded by * an acquireExclusiveLock() call. */ - public void releaseExclusiveLock(); + void releaseExclusiveLock(); /** * Force to close the persistence manager. Called by * TransactionImpl.afterCompletion in case of the CMT transaction * and the status value passed to the method cannot be resolved. */ - public void forceClose(); + void forceClose(); /** * Returns StateManager instance for this Object Id. * @param oid the ObjectId to look up. * @param pcClass the expected Class type of the new PC instance. */ - public StateManager findOrCreateStateManager(Object oid, Class pcClass); + StateManager findOrCreateStateManager(Object oid, Class pcClass); /** * Lock cache for getObjectById and result processing synchronization. */ - public void acquireCacheLock(); + void acquireCacheLock(); /** Release cache lock. */ - public void releaseCacheLock(); + void releaseCacheLock(); /** * Looks up the given instance in the Version Consistency cache and @@ -263,6 +258,6 @@ Object newCollectionInstanceInternal (Class type, Object owner, String fieldName * @return true if the sm was found and populated, false * otherwise. */ - public boolean initializeFromVersionConsistencyCache(StateManager sm); + boolean initializeFromVersionConsistencyCache(StateManager sm); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceStore.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceStore.java index 1ebd4fbe7c2..a2b7fd67978 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceStore.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/PersistenceStore.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 */ -/* - * PersistenceStore.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore; @@ -35,25 +29,25 @@ public interface PersistenceStore { /** */ - public void execute(PersistenceManager pm, Collection actions); + void execute(PersistenceManager pm, Collection actions); /** */ - public void executeBatch(PersistenceManager pm, UpdateObjectDesc request, boolean forceFlush); + void executeBatch(PersistenceManager pm, UpdateObjectDesc request, boolean forceFlush); /** */ - public Object retrieve(PersistenceManager pm, + Object retrieve(PersistenceManager pm, RetrieveDesc action, ValueFetcher parameters); /** */ - public Class getClassByOidClass(Class oidType); + Class getClassByOidClass(Class oidType); /** */ - public StateManager getStateManager(Class classType); + StateManager getStateManager(Class classType); /** * Returns a new retrieve descriptor for an external (user) query. @@ -61,7 +55,7 @@ public Object retrieve(PersistenceManager pm, * @param classType Type of the persistence capable class to be queried. * @return A new retrieve descriptor for an external (user) query. */ - public RetrieveDesc getRetrieveDesc(Class classType); + RetrieveDesc getRetrieveDesc(Class classType); /** * Returns a new retrieve descriptor for an external (user) query. @@ -72,22 +66,21 @@ public Object retrieve(PersistenceManager pm, * @param classType Persistence capable class including fieldName. * @return A new retrieve descriptor for an external (user) query. */ - public RetrieveDesc getRetrieveDesc(String fieldName, Class classType); + RetrieveDesc getRetrieveDesc(String fieldName, Class classType); /** */ - public UpdateObjectDesc getUpdateObjectDesc(Class classType); + UpdateObjectDesc getUpdateObjectDesc(Class classType); /** */ - public PersistenceConfig getPersistenceConfig( - Class classType); + PersistenceConfig getPersistenceConfig(Class classType); /** * Returns ConfigCache associated with this store. * * @return ConfigCache associated with this store. */ - public ConfigCache getConfigCache(); + ConfigCache getConfigCache(); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SCOCollection.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SCOCollection.java index 013ca2f5889..e14f21bc1e3 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SCOCollection.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SCOCollection.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,20 +15,14 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * SCOCollection.java - * - * created April 3, 2000 - * - * @author Marina Vatkina - * @version 1.0 - */ - package com.sun.jdo.spi.persistence.support.sqlstore; import java.util.Collection; -public interface SCOCollection extends java.util.Collection, SCO -{ +/* + * @author Marina Vatkina 2000 + */ +public interface SCOCollection extends java.util.Collection, SCO { + /** * Resets removed and added lists after flush */ @@ -50,7 +45,7 @@ public interface SCOCollection extends java.util.Collection, SCO * collection c will be added to the underlying collection * before the deferred updates are applied. */ - void applyDeferredUpdates(Collection c); + void applyDeferredUpdates(Collection c); /** * Adds object to the Collection without recording @@ -62,7 +57,7 @@ public interface SCOCollection extends java.util.Collection, SCO * Adds objects of the given Collection to this Collection without recording * the event. Used internaly to initially populate the Collection */ - void addAllInternal(Collection c); + void addAllInternal(Collection c); /** * Adds an object to the list without recording changes. @@ -73,7 +68,7 @@ public interface SCOCollection extends java.util.Collection, SCO * Removes objects of the given Collection from this Collection without recording * the event. Used internaly to remove a collection of elements from this collection. */ - void removeAllInternal(Collection c); + void removeAllInternal(Collection c); /** * Clears Collection without recording @@ -93,14 +88,14 @@ public interface SCOCollection extends java.util.Collection, SCO * * @return Collection of the added elements as java.util.Collection */ - Collection getAdded(); + Collection getAdded(); /** * Returns the Collection of removed elements * * @return Collection of the removed elements as java.util.Collection */ - Collection getRemoved(); + Collection getRemoved(); /** * Sets a new owner for the SCO instance that is not owned @@ -113,6 +108,6 @@ public interface SCOCollection extends java.util.Collection, SCO * @throws com.sun.jdo.api.persistence.support.JDOUserException if the * instance is owned by another owner. */ - void setOwner(Object owner, String fieldName, Class elementType); + void setOwner(Object owner, String fieldName, Class elementType); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStateManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStateManager.java index fe2b4cc9983..d73cfee803c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStateManager.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStateManager.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 */ -/* - * SQLStateManager.java - * - * Created on March 3, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore; import com.sun.jdo.api.persistence.support.JDOException; @@ -42,8 +37,8 @@ import com.sun.jdo.spi.persistence.utility.NullSemaphore; import com.sun.jdo.spi.persistence.utility.Semaphore; import com.sun.jdo.spi.persistence.utility.SemaphoreImpl; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -58,6 +53,10 @@ import org.glassfish.persistence.common.I18NHelper; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; + /** * @@ -73,7 +72,7 @@ public class SQLStateManager implements Cloneable, StateManager, TestStateManage private BitSet fieldMasks; /** Array of Object. */ - public ArrayList hiddenValues; + public ArrayList hiddenValues; private ClassDesc persistenceConfig; @@ -126,7 +125,7 @@ public class SQLStateManager implements Cloneable, StateManager, TestStateManage private UpdateObjectDescImpl updateDesc; /** Contains state managers depending on this object. */ - private HashSet updatedForeignReferences; + private HashSet updatedForeignReferences; /** Counts the foreign state managers this state manager depends on. */ private int referenceCount; @@ -135,22 +134,20 @@ public class SQLStateManager implements Cloneable, StateManager, TestStateManage private final Semaphore lock; /** The logger. */ - private static Logger logger = LogHelperStateManager.getLogger(); + private static final Logger LOG = System.getLogger(SQLStateManager.class.getName(), RESOURCE_BUNDLE); /** I18N message handler. */ - private final static ResourceBundle messages = I18NHelper.loadBundle( - SQLStateManager.class); + private final static ResourceBundle messages = I18NHelper.loadBundle(SQLStateManager.class); /** Name of the USE_BATCH property. */ - public static final String USE_BATCH_PROPERTY = - "com.sun.jdo.spi.persistence.support.sqlstore.USE_BATCH"; // NOI18N + public static final String USE_BATCH_PROPERTY = "com.sun.jdo.spi.persistence.support.sqlstore.USE_BATCH"; /** * Property to swich on/off batching. Note, the default is true, meaning we * try to do batching if the property is not specified. */ private static final boolean USE_BATCH = Boolean.valueOf( - System.getProperty(USE_BATCH_PROPERTY, "true")).booleanValue(); // NOI18N + System.getProperty(USE_BATCH_PROPERTY, "true")).booleanValue(); /** * Construct a new SQLStateManager so that it locks or does not lock as @@ -161,12 +158,13 @@ public SQLStateManager(PersistenceStore store, ClassDesc persistenceConfig) { this.persistenceConfig = persistenceConfig; if (EJBHelper.isManaged()) { - this.lock = new NullSemaphore("SQLStateManager"); // NOI18N + this.lock = new NullSemaphore("SQLStateManager"); } else { - this.lock = new SemaphoreImpl("SQLStateManager"); // NOI18N + this.lock = new SemaphoreImpl("SQLStateManager"); } } + @Override public synchronized void initialize(boolean persistentInDB) { boolean xactActive = persistenceManager.isActiveTransaction(); boolean optimistic = persistenceManager.isOptimisticTransaction(); @@ -206,9 +204,9 @@ public synchronized void initialize(boolean persistentInDB) { registerInstance(false, null, oldstate); } - private void registerInstance(boolean throwDuplicateException, - ArrayList newlyRegisteredSMs, LifeCycleState oldstate) { + private void registerInstance(boolean throwDuplicateException, List newlyRegisteredSMs, + LifeCycleState oldstate) { if ((stateFlags & ST_REGISTERED) == 0 || // not registered or (oldstate != state && // state changed from clean to dirty or transactional type. (oldstate == null || oldstate.isDirty() != state.isDirty() || @@ -217,16 +215,19 @@ private void registerInstance(boolean throwDuplicateException, persistenceManager.registerInstance(this, getObjectId(), throwDuplicateException, false); stateFlags |= ST_REGISTERED; if (newlyRegisteredSMs != null) { - if (!newlyRegisteredSMs.contains(this)) + if (!newlyRegisteredSMs.contains(this)) { newlyRegisteredSMs.add(this); + } } } } + @Override public void setPersistenceManager(com.sun.jdo.api.persistence.support.PersistenceManager pm) { this.persistenceManager = (PersistenceManager) pm; } + @Override public void setPersistent(Object pc) { this.persistentObject = pc; } @@ -235,10 +236,12 @@ public PersistenceStore getStore() { return store; } + @Override public Object getPersistent() { return persistentObject; } + @Override public PersistenceConfig getPersistenceConfig() { return persistenceConfig; } @@ -299,6 +302,7 @@ private void newFieldMasks() { this.fieldMasks = new BitSet(MAX_MASKS * persistenceConfig.maxFields); } + @Override public void setPresenceMaskBit(int index) { if (fieldMasks == null) { newFieldMasks(); @@ -325,6 +329,7 @@ private void setSetMaskBit(int index) { } } + @Override public boolean getPresenceMaskBit(int index) { if (fieldMasks == null) { newFieldMasks(); @@ -351,11 +356,12 @@ public boolean getSetMaskBit(int index) { } } + @Override public Object getHiddenValue(int index) { // This method expects index to be negative for hidden fields. if (index >= 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.poshiddenindex", "" + index)); // NOI18N + "core.statemanager.poshiddenindex", "" + index)); } int realIndex = -(index + 1); @@ -367,17 +373,18 @@ public Object getHiddenValue(int index) { return null; } + @Override public void setHiddenValue(int index, Object value) { // This method expects index to be negative for hidden fields. if (index >= 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.poshiddenindex", "" + index)); // NOI18N + "core.statemanager.poshiddenindex", "" + index)); } int realIndex = -(index + 1); if (hiddenValues == null) { - hiddenValues = new ArrayList(); + hiddenValues = new ArrayList<>(); } for (int i = hiddenValues.size(); i <= realIndex; i++) { @@ -387,29 +394,25 @@ public void setHiddenValue(int index, Object value) { hiddenValues.set(realIndex, value); } + @Override public synchronized void replaceObjectField(String fieldName, Object o) { - boolean debug = logger.isLoggable(); - - if (debug) { - Object[] items = new Object[] {fieldName, o.getClass().getName()}; - logger.fine("sqlstore.sqlstatemanager.replaceobjectfield", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.replaceobjectfield", fieldName, o.getClass().getName()); FieldDesc fieldDesc = persistenceConfig.getField(fieldName); Object oldo = prepareSetField(fieldDesc, o); if ((oldo instanceof SCO) && oldo != o) { - if (debug) - logger.fine("sqlstore.sqlstatemanager.replaceobjectfield.unsetsco"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.replaceobjectfield.unsetsco"); ((SCO) oldo).unsetOwner(); } } + @Override public synchronized void makeDirty(String fieldName) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.makedirty", fieldName); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makedirty", fieldName); } FieldDesc fieldDesc = persistenceConfig.getField(fieldName); @@ -426,16 +429,16 @@ public synchronized void makeDirty(String fieldName) { if ((newo instanceof SCO) && oldo != newo) { if (oldo instanceof SCOCollection) { if (debug) { - logger.fine("sqlstore.sqlstatemanager.makedirty.fixscocollection"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makedirty.fixscocollection"); } ((SCOCollection) oldo).clearInternal(); - ((SCOCollection) oldo).addAllInternal((Collection) newo); + ((SCOCollection) oldo).addAllInternal((Collection) newo); } else if (oldo instanceof SCODate) { if (debug) { - logger.fine("sqlstore.sqlstatemanager.makedirty.fixscodate"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makedirty.fixscodate"); } long l = ((java.util.Date) newo).getTime(); @@ -463,25 +466,27 @@ else if (oldo instanceof SCODate) { fieldDesc.setValue(this, oldo); // disconnect temp SCO instance - if (newo instanceof SCO) + if (newo instanceof SCO) { ((SCO) newo).unsetOwner(); + } } } /** * This method is central to record changes to SCOCollections. */ + @Override public void applyUpdates(String fieldName, SCOCollection c) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.applyupdates", fieldName); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.applyupdates", fieldName); } FieldDesc fieldDesc = persistenceConfig.getField(fieldName); if (fieldDesc instanceof ForeignFieldDesc) { - ArrayList removed = new ArrayList(c.getRemoved()); - ArrayList added = new ArrayList(c.getAdded()); + ArrayList removed = new ArrayList<>(c.getRemoved()); + ArrayList added = new ArrayList<>(c.getAdded()); // We reset the collection to clear the added and removed list before calling // processCollectionUpdates() which can throw an exception. @@ -491,15 +496,16 @@ public void applyUpdates(String fieldName, SCOCollection c) { // else it is an ERROR? if (debug) { - logger.fine("sqlstore.sqlstatemanager.applyupdates.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.applyupdates.exit"); } } + @Override public void makePresent(String fieldName, Object value) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.makepresent", fieldName); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makepresent", fieldName); } FieldDesc fieldDesc = persistenceConfig.getField(fieldName); @@ -507,22 +513,24 @@ public void makePresent(String fieldName, Object value) { setPresenceMaskBit(fieldDesc.absoluteID); } + @Override public void setObjectId(Object objectId) { // RESOLVE: do we allow to replace existing? this.objectId = objectId; } + @Override public Object getObjectId() { // Note: PM.getObjectId() makes copy of the actual object id. if (objectId == null) { - Class oidClass = persistenceConfig.getOidClass(); + Class oidClass = persistenceConfig.getOidClass(); Object oid = null; try { - oid = oidClass.newInstance(); + oid = oidClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantnewoid", oidClass.getName()), e); // NOI18N + "core.statemanager.cantnewoid", oidClass.getName()), e); } Field keyFields[] = persistenceConfig.getKeyFields(); @@ -538,7 +546,7 @@ public Object getObjectId() { } catch (IllegalAccessException e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantsetkeyfield", keyField.getName()), e); // NOI18N + "core.statemanager.cantsetkeyfield", keyField.getName()), e); } } objectId = oid; @@ -559,12 +567,13 @@ private void makeAutoPersistent(Object pc) { * This method is called by PersistenceManager.makePersistent(). * Thread synchronization is done in the persistence manager. */ + @Override public void makePersistent(PersistenceManager pm, Object pc) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.makepersistence", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makepersistence", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -608,9 +617,9 @@ public void makePersistent(PersistenceManager pm, Object pc) { // Make sure all the fields have been marked dirty. Object obj = null; - ArrayList fields = persistenceConfig.fields; + List fields = persistenceConfig.fields; for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); // In case of makePersistent, we skip all secondary tracked fields // and use the primary to propagate changes. In addition, we take @@ -625,10 +634,10 @@ public void makePersistent(PersistenceManager pm, Object pc) { if (f instanceof ForeignFieldDesc) { ForeignFieldDesc ff = (ForeignFieldDesc) f; - ArrayList trackedFields = null; + List trackedFields = null; if (debug) { - logger.fine("sqlstore.sqlstatemanager.processforeign", ff.getName()); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.processforeign", ff.getName()); } if ((ff.sqlProperties & FieldDesc.PROP_PRIMARY_TRACKED_FIELD) > 0) { @@ -636,7 +645,7 @@ public void makePersistent(PersistenceManager pm, Object pc) { Object theValue = obj; for (int j = 0; j < trackedFields.size(); j++) { - FieldDesc tf = (FieldDesc) trackedFields.get(j); + FieldDesc tf = trackedFields.get(j); Object value = tf.getValue(this); if ((theValue != null) && (value != null) && (theValue != value)) { @@ -648,7 +657,7 @@ public void makePersistent(PersistenceManager pm, Object pc) { } this.release(); throw new JDOUserException(I18NHelper.getMessage(messages, - "core.statemanager.conflictingvalues", ff.getName(), tf.getName())); // NOI18N + "core.statemanager.conflictingvalues", ff.getName(), tf.getName())); } else if ((theValue == null) && (value != null)) { theValue = value; } @@ -662,9 +671,9 @@ public void makePersistent(PersistenceManager pm, Object pc) { if (obj != null) { if (obj instanceof Collection) { - if (((Collection) obj).size() > 0) { - ArrayList removed = null; - ArrayList added = new ArrayList((Collection) obj); + if (((Collection) obj).size() > 0) { + ArrayList removed = null; + ArrayList added = new ArrayList<>((Collection) obj); processCollectionUpdates(ff, removed, added, null, true, false); } } else { @@ -688,11 +697,11 @@ public void makePersistent(PersistenceManager pm, Object pc) { } else { // We ignore primitive fields that also tracks relationship field if ((f.sqlProperties & FieldDesc.PROP_TRACK_RELATIONSHIP_FIELD) > 0) { - ArrayList trackedFields = f.getTrackedFields(); + List trackedFields = f.getTrackedFields(); boolean found = false; for (int j = trackedFields.size() - 1; j >= 0; j--) { - FieldDesc tf = (FieldDesc) trackedFields.get(j); + FieldDesc tf = trackedFields.get(j); if (tf instanceof ForeignFieldDesc) { if (tf.getValue(this) != null) { @@ -719,7 +728,7 @@ public void makePersistent(PersistenceManager pm, Object pc) { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.makedirtyfield", f.getName()); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.makedirtyfield", f.getName()); } setSetMaskBit(f.absoluteID); @@ -735,12 +744,10 @@ public void makePersistent(PersistenceManager pm, Object pc) { * nullifying the relationship fields, the instance transitions to * deleted state. */ + @Override public void deletePersistent() { - if (logger.isLoggable()) { - logger.fine("sqlstore.sqlstatemanager.deletepersistence", // NOI18N - persistenceConfig.getPersistenceCapableClass().getName()); - - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.deletepersistence", + persistenceConfig.getPersistenceCapableClass().getName()); // Why try try? The difference is in whether you try and then // acquire/get, or acquire/get and then try. @@ -780,12 +787,12 @@ public void deletePersistent() { * fields marked for cascade delete. */ private void deleteRelationships() { - ArrayList foreignFields = persistenceConfig.foreignFields; + List foreignFields = persistenceConfig.foreignFields; int size = foreignFields.size(); stateFlags |= ST_DELETE_INPROGRESS; for (int i = 0; i < size; i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); + ForeignFieldDesc ff = foreignFields.get(i); ForeignFieldDesc irf = ff.getInverseRelationshipField(); // Skip this field if it is secondary. @@ -801,10 +808,10 @@ private void deleteRelationships() { prepareUpdateField(ff, null); if (ff.cardinalityUPB > 1) { - Collection c = (Collection) ff.getValue(this); + Collection c = (Collection) ff.getValue(this); if (c != null) { - ArrayList removed = new ArrayList(c); + ArrayList removed = new ArrayList<>(c); // For managed relationship or cascade delete, we need to call // processCollectionUpdates() to set up the dependency. In case of @@ -819,7 +826,7 @@ private void deleteRelationships() { } if (ff.deleteAction == ForeignFieldDesc.ACT_CASCADE) { - Iterator iter = removed.iterator(); + Iterator iter = removed.iterator(); while (iter.hasNext()) { Object obj = iter.next(); @@ -880,37 +887,38 @@ private void deleteRelationships() { * * @param next Next state manager in the transaction cache. */ + @Override public void updatePersistent(StateManager next) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if ((stateFlags & ST_UPDATE_DISABLED) > 0) { if (debug) { Object[] items = new Object[] {persistenceConfig.getPersistenceCapableClass().getName(), persistentObject}; - logger.fine("sqlstore.sqlstatemanager.updatepersistent.skipped", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updatepersistent.skipped", items); } return; } try { if (debug) { - logger.fine("sqlstore.sqlstatemanager.updatepersistent", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updatepersistent", persistenceConfig.getPersistenceCapableClass().getName()); } - ArrayList actions = new ArrayList(); + ArrayList actions = new ArrayList<>(); // Get a list of actions to perform. getUpdateActions(actions); if (actions.size() == 1 && useBatch()) { // Batch update only if actions consists of a single action - UpdateObjectDesc updateDesc = (UpdateObjectDesc)actions.get(0); + UpdateObjectDesc updateDesc = actions.get(0); boolean immediateFlush = requiresImmediateFlush((SQLStateManager)next); if (debug && immediateFlush) { Object[] items = new Object[] {getPersistent(), (next != null) ? next.getPersistent() : null}; - logger.fine("sqlstore.sqlstatemanager.updatepersistent.immediateflush", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updatepersistent.immediateflush", items); } store.executeBatch(persistenceManager, updateDesc, immediateFlush); @@ -921,15 +929,14 @@ public void updatePersistent(StateManager next) { incrementVersion(actions); if (debug) { - logger.fine("sqlstore.sqlstatemanager.updatepersistent.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updatepersistent.exit"); } } catch (JDOException e) { e.addFailedObject(persistentObject); throw e; } catch (Exception e) { - logger.throwing("sqlstore.SQLStateManager", "updatePersistent", e); // NOI18N throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.unknownexception"), e); // NOI18N + "core.generic.unknownexception"), e); } } @@ -939,10 +946,10 @@ public void updatePersistent(StateManager next) { * * @param actions List of updated state managers. */ - static private void incrementVersion(List actions) { + static private void incrementVersion(List actions) { - for (Iterator iter = actions.iterator(); iter.hasNext(); ) { - ((UpdateObjectDescImpl) iter.next()).incrementVersion(); + for (Iterator iter = actions.iterator(); iter.hasNext(); ) { + iter.next().incrementVersion(); } } @@ -961,6 +968,7 @@ public void incrementVersion() { /** * @inheritDoc StateManager#hasVersionConsistency */ + @Override public boolean hasVersionConsistency() { return persistenceConfig.hasVersionConsistency(); } @@ -968,6 +976,7 @@ public boolean hasVersionConsistency() { /** * @inheritDoc StateManager#verifyPersistent */ + @Override public boolean verifyPersistent() { assert persistenceConfig.hasVersionConsistency(); boolean verified = true; @@ -1033,6 +1042,7 @@ private boolean useBatch() { /** * @inheritDoc StateManager#setVerificationFailed */ + @Override public void setVerificationFailed() { if (hasVersionConsistency()) { stateFlags |= ST_VALIDATION_FAILED; @@ -1042,6 +1052,7 @@ public void setVerificationFailed() { /** * @inheritDoc StateManager#getFailed */ + @Override public boolean isVerificationFailed() { return (stateFlags & ST_VALIDATION_FAILED) > 0; } @@ -1057,26 +1068,31 @@ public boolean isVerificationFailed() { private boolean requiresImmediateFlush(SQLStateManager next) { // There is no next SM => // flush this sm immediately - if (next == null) + if (next == null) { return true; + } // The next StateManager has a different pc class => // flush this sm immediately - if (persistenceConfig != next.persistenceConfig) + if (persistenceConfig != next.persistenceConfig) { return true; + } // The next StateManager represents a different update operation // INSERT/UPDATE/DELETE => flush this sm immediately - if (state.getUpdateAction() != next.state.getUpdateAction()) + if (state.getUpdateAction() != next.state.getUpdateAction()) { return true; + } // If the next's flush is disabled, flush this sm - if ((next.stateFlags & ST_UPDATE_DISABLED) > 0) + if ((next.stateFlags & ST_UPDATE_DISABLED) > 0) { return true; + } // If next sm does not use batch update flush this sm - if (!next.useBatch()) + if (!next.useBatch()) { return true; + } // For updates, we need to check if the next sm updates the // same fields. If not, flush this sm @@ -1102,11 +1118,12 @@ private boolean compareUpdatedFields(SQLStateManager next) { return updFields.equals(nextUpdFields); } + @Override public void refreshPersistent() { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.refreshpersistent", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.refreshpersistent", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -1119,7 +1136,7 @@ public void refreshPersistent() { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.refreshpersistent.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.refreshpersistent.exit"); } } @@ -1131,11 +1148,12 @@ public void refreshPersistent() { * PersistenceManager.getObjectById(Object, boolean)} with validate * flag set to true */ + @Override public void reload() { - boolean debug = logger.isLoggable(Logger.FINER); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.finer("sqlstore.sqlstatemanager.unconditionalreload", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.unconditionalreload", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -1151,7 +1169,7 @@ public void reload() { releaseLock(); if (debug) { - logger.finer("sqlstore.sqlstatemanager.unconditionalreload.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.unconditionalreload.exit"); } } } @@ -1162,12 +1180,12 @@ public void reload() { * @param additionalField Field to be loaded. */ private void reload(FieldDesc additionalField) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { String fieldName = (additionalField != null) ? additionalField.getName() : null; - logger.fine("sqlstore.sqlstatemanager.reload", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.reload", persistenceConfig.getPersistenceCapableClass().getName(), fieldName); } @@ -1202,7 +1220,7 @@ private void reload(FieldDesc additionalField) { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.reload.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.reload.exit"); } } @@ -1235,11 +1253,12 @@ private boolean retrieveFromVersionConsistencyCache(FieldDesc additionalField) { * Collections. Such process has the side-effect of causing more * objects to be registered with the transaction cache. */ + @Override public void prepareToUpdatePhaseI() { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph1", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph1", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -1253,24 +1272,24 @@ public void prepareToUpdatePhaseI() { // Initialize UpdateDesc. getUpdateDesc(); - ArrayList newlyRegisteredSMs = new ArrayList(); - ArrayList foreignFields = persistenceConfig.foreignFields; + List newlyRegisteredSMs = new ArrayList<>(); + List foreignFields = persistenceConfig.foreignFields; int size = foreignFields.size(); for (int i = 0; i < size; i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); + ForeignFieldDesc ff = foreignFields.get(i); if ((ff.sqlProperties & FieldDesc.PROP_SECONDARY_TRACKED_FIELD) > 0) { continue; } if ((ff.cardinalityUPB > 1) && (getSetMaskBit(ff.absoluteID) == true)) { - Collection v = (Collection) ff.getValue(this); + Collection v = (Collection) ff.getValue(this); if ((v != null) && (!(v instanceof SCO) || (((SCO) v).getOwner() == null)) && (v.size() > 0)) { - ArrayList removed = null; - ArrayList added = new ArrayList(v); + ArrayList removed = null; + ArrayList added = new ArrayList<>(v); processCollectionUpdates(ff, removed, added, newlyRegisteredSMs, true, false); } @@ -1280,13 +1299,13 @@ public void prepareToUpdatePhaseI() { // The newRegisteredSMs should contain a list of all the state managers that // are registered as the result of processCollectionUpdates. for (int i = 0; i < newlyRegisteredSMs.size(); i++) { - SQLStateManager sm = (SQLStateManager) newlyRegisteredSMs.get(i); + SQLStateManager sm = newlyRegisteredSMs.get(i); sm.prepareToUpdatePhaseI(); } if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph1.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph1.exit"); } } @@ -1297,11 +1316,12 @@ public void prepareToUpdatePhaseI() { * @param phase3sms List containing autopersistent instances that are no longer reachable * from a persistent instance. */ - public void prepareToUpdatePhaseII(HashSet phase3sms) { - boolean debug = logger.isLoggable(); + @Override + public void prepareToUpdatePhaseII(HashSet phase3sms) { + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph2", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph2", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -1324,13 +1344,13 @@ public void prepareToUpdatePhaseII(HashSet phase3sms) { return; } - ArrayList foreignFields = persistenceConfig.foreignFields; + List foreignFields = persistenceConfig.foreignFields; int size = foreignFields.size(); // Walk the object graph starting from this instance and transition all // autopersistent instances to persistent and remove it from phase3sms. for (int i = 0; i < size; i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); + ForeignFieldDesc ff = foreignFields.get(i); if (ff.cardinalityUPB <= 1) { if (getPresenceMaskBit(ff.absoluteID)) { @@ -1341,10 +1361,10 @@ public void prepareToUpdatePhaseII(HashSet phase3sms) { } } } else { - Collection c = getCollectionValue(ff); + Collection c = getCollectionValue(ff); if (c != null) { - Iterator iter = c.iterator(); + Iterator iter = c.iterator(); while (iter.hasNext()) { Object v = iter.next(); @@ -1356,7 +1376,7 @@ public void prepareToUpdatePhaseII(HashSet phase3sms) { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph2.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph2.exit"); } } @@ -1364,11 +1384,12 @@ public void prepareToUpdatePhaseII(HashSet phase3sms) { * This is the third phase of commit processing. It sets up the delete dependencies among * all the autopersistent instances that have been flushed to the database. */ + @Override public void prepareToUpdatePhaseIII() { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph3", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph3", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -1384,13 +1405,13 @@ public void prepareToUpdatePhaseIII() { return; } - ArrayList foreignFields = persistenceConfig.foreignFields; + List foreignFields = persistenceConfig.foreignFields; int size = foreignFields.size(); // Sets up dependencies between this instance and all its relationship fields // that are autopersistent. for (int i = 0; i < size; i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); + ForeignFieldDesc ff = foreignFields.get(i); if (ff.cardinalityUPB <= 1) { if (getPresenceMaskBit(ff.absoluteID)) { @@ -1401,12 +1422,12 @@ public void prepareToUpdatePhaseIII() { } } } else { - Collection c = getCollectionValue(ff); + Collection c = getCollectionValue(ff); if (c != null) { if (c.size() > 0) { - ArrayList removed = new ArrayList(c); - ArrayList added = null; + ArrayList removed = new ArrayList<>(c); + ArrayList added = null; processCollectionUpdates(ff, removed, added, null, false, false); } @@ -1415,7 +1436,7 @@ public void prepareToUpdatePhaseIII() { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.preparetoupdateph3.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.preparetoupdateph3.exit"); } } @@ -1431,7 +1452,7 @@ public void prepareToUpdatePhaseIII() { * @param pc Instance becoming persistent and removed from phase3sms. * @param phase3sms List containing so far unreachable autopersistent instances. */ - private void transitionPersistent(Object pc, HashSet phase3sms) { + private void transitionPersistent(Object pc, HashSet phase3sms) { SQLStateManager sm = (SQLStateManager) persistenceManager.getStateManager(pc); // Need to check if the associated state manager is null, if @@ -1457,10 +1478,10 @@ private void transitionPersistent(Object pc, HashSet phase3sms) { * ff. For deferred SCOCollections, only the * objects added in the current transaction are returned. */ - private Collection getCollectionValue(ForeignFieldDesc ff) { - Collection c = null; + private Collection getCollectionValue(ForeignFieldDesc ff) { + Collection c = null; if (ff.cardinalityUPB > 1) { - c = (Collection) ff.getValue(this); + c = (Collection) ff.getValue(this); if (c != null && c instanceof SCOCollection) { SCOCollection sco = (SCOCollection) c; if (sco.isDeferred()) { @@ -1471,7 +1492,7 @@ private Collection getCollectionValue(ForeignFieldDesc ff) { return c; } - private void getUpdateActions(ArrayList actions) { + private void getUpdateActions(ArrayList actions) { if ((stateFlags & ST_VISITED) > 0) { return; } @@ -1495,10 +1516,10 @@ private void getUpdateActions(ArrayList actions) { stateFlags |= ST_VISITED; if (updatedForeignReferences != null) { - Iterator iter = updatedForeignReferences.iterator(); + Iterator iter = updatedForeignReferences.iterator(); while (iter.hasNext()) { - SQLStateManager sm = ((UpdatedForeignReference) iter.next()).getStateManager(); + SQLStateManager sm = iter.next().getStateManager(); if (sm.referenceCount == 1) { sm.getUpdateActions(actions); @@ -1509,6 +1530,7 @@ private void getUpdateActions(ArrayList actions) { } } + @Override public void release() { if (null != persistenceManager) { @@ -1530,12 +1552,12 @@ public void release() { } private void reset(boolean retainValues, boolean wasNew, boolean keepState) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { Object[] items = new Object[] {Boolean.valueOf(retainValues), Boolean.valueOf(wasNew), Boolean.valueOf(keepState)}; - logger.fine("sqlstore.sqlstatemanager.reset", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.reset", items); } @@ -1570,9 +1592,9 @@ private void reset(boolean retainValues, boolean wasNew, boolean keepState) { // is persistentNontransactional if (retainValues || (state instanceof PersistentNonTransactional)) { FieldDesc f = null; - ArrayList fields = persistenceConfig.fields; + List fields = persistenceConfig.fields; for (int i = 0; i < fields.size(); i++) { - f = (FieldDesc) fields.get(i); + f = fields.get(i); Object v = f.getValue(this); // For new objects mark null references as not set if the field is @@ -1580,8 +1602,9 @@ private void reset(boolean retainValues, boolean wasNew, boolean keepState) { // transaction because a relationship may exist in the database. if (wasNew && (f instanceof ForeignFieldDesc) && (v == null) && (((ForeignFieldDesc) f).getInverseRelationshipField() == null)) { - if (debug) - logger.fine("sqlstore.sqlstatemanager.unsetmask", f.getName()); // NOI18N + if (debug) { + LOG.log(DEBUG, "sqlstore.sqlstatemanager.unsetmask", f.getName()); + } unsetMaskBit(f.absoluteID, PRESENCE_MASK); } @@ -1589,13 +1612,14 @@ private void reset(boolean retainValues, boolean wasNew, boolean keepState) { // with SCO instances: if ((v instanceof Collection) && !(v instanceof SCOCollection) && !keepState) { - if (debug) - logger.fine("sqlstore.sqlstatemanager.resettingcollection"); // NOI18N + if (debug) { + LOG.log(DEBUG, "sqlstore.sqlstatemanager.resettingcollection"); + } - replaceCollection((ForeignFieldDesc) f, (Collection) v); + replaceCollection((ForeignFieldDesc) f, (Collection) v); if (debug) { - logger.fine("sqlstore.sqlstatemanager.newtype", (f.getValue(this)).getClass()); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.newtype", (f.getValue(this)).getClass()); } } else if (v instanceof SCOCollection) { ((SCOCollection) v).reset(); @@ -1604,13 +1628,14 @@ private void reset(boolean retainValues, boolean wasNew, boolean keepState) { // TO FIX!!!: this already replaces Date with SCO Date else if ((v instanceof java.util.Date) && !(v instanceof SCODate) && !keepState) { - if (debug) - logger.fine("sqlstore.sqlstatemanager.resettingdate"); // NOI18N + if (debug) { + LOG.log(DEBUG, "sqlstore.sqlstatemanager.resettingdate"); + } v = f.convertValue(v, this); f.setValue(this, v); if (debug) { - logger.fine("sqlstore.sqlstatemanager.newtype", (f.getValue(this)).getClass()); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.newtype", (f.getValue(this)).getClass()); } } } @@ -1641,10 +1666,12 @@ else if ((v instanceof java.util.Date) && !(v instanceof SCODate) /** * @return true if persistentObject has been flushed to db */ + @Override public boolean isProcessed() { return (referenceCount == 0); } + @Override public void flushed() { // reset the current state to the point where we can accept more updates. state = state.transitionFlushed(); @@ -1667,12 +1694,14 @@ public void flushed() { } } + @Override public void commit(boolean retainValues) { boolean wasNew = (state.isNew() && !state.isDeleted()); state = state.transitionCommit(retainValues); reset(retainValues, wasNew, false); } + @Override public void rollback(boolean retainValues) { boolean wasNew = (state.isNew() && !state.isDeleted()); boolean needsRestore = state.needsRestoreOnRollback(retainValues); @@ -1694,7 +1723,7 @@ public void rollback(boolean retainValues) { } private void markKeyFieldsPresent() { - ArrayList keyFields = persistenceConfig.getPrimaryTable().getKey().getFields(); + List keyFields = persistenceConfig.getPrimaryTable().getKey().getFields(); for (int i = 0; i < keyFields.size(); i++) { LocalFieldDesc fd = (LocalFieldDesc) keyFields.get(i); @@ -1705,6 +1734,7 @@ private void markKeyFieldsPresent() { } } + @Override public void prepareGetField(int fieldID) { FieldDesc fieldDesc = persistenceConfig.getField(fieldID); @@ -1725,10 +1755,10 @@ private void prepareGetField(FieldDesc fieldDesc) { * @param fieldDesc Field descriptor for the field to be loaded. */ private void prepareGetField(FieldDesc fieldDesc, boolean internal, boolean acquireShareLock) { - boolean debug = logger.isLoggable(Logger.FINEST); + boolean debug = LOG.isLoggable(TRACE); if (debug) { - logger.finest("sqlstore.sqlstatemanager.preparegetfield", fieldDesc.getName()); // NOI18N + LOG.log(TRACE, "sqlstore.sqlstatemanager.preparegetfield", fieldDesc.getName()); } if (acquireShareLock) { @@ -1760,9 +1790,8 @@ private void prepareGetField(FieldDesc fieldDesc, boolean internal, boolean acqu } catch (JDOException e) { throw e; } catch (Exception e) { - logger.log(Logger.FINE,"sqlstore.exception.log", e); throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.getfieldfailed"), e); // NOI18N + "core.statemanager.getfieldfailed"), e); } finally { if (acquireShareLock) { persistenceManager.releaseShareLock(); @@ -1770,7 +1799,7 @@ private void prepareGetField(FieldDesc fieldDesc, boolean internal, boolean acqu releaseLock(); if (debug) { - logger.finest("sqlstore.sqlstatemanager.preparegetfield.exit"); // NOI18N + LOG.log(TRACE, "sqlstore.sqlstatemanager.preparegetfield.exit"); } } } @@ -1787,15 +1816,15 @@ private void prepareGetField(FieldDesc fieldDesc, boolean internal, boolean acqu private void realizeField(FieldDesc fieldDesc) { assert fieldDesc != null; - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.realizefield", fieldDesc.getName()); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.realizefield", fieldDesc.getName()); } if (!persistenceConfig.isNavigable()) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.notnavigable", // NOI18N + "core.statemanager.notnavigable", fieldDesc.getName(), persistentObject.getClass().getName())); } @@ -1823,7 +1852,7 @@ private void realizeField(FieldDesc fieldDesc) { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.realizefield.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.realizefield.exit"); } } @@ -1848,16 +1877,16 @@ private boolean realizeForeignField(ForeignFieldDesc foreignField) { assert foreignField != null; boolean isPresent = false; - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.realizeforeignfield", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.realizeforeignfield", foreignField.getName()); } // Check and see if all the values we need are present. for (int i = 0; i < foreignField.localFields.size(); i++) { - LocalFieldDesc lf = (LocalFieldDesc) foreignField.localFields.get(i); + LocalFieldDesc lf = foreignField.localFields.get(i); isPresent = getPresenceMaskBit(lf.absoluteID); if (!isPresent) { @@ -1873,7 +1902,7 @@ private boolean realizeForeignField(ForeignFieldDesc foreignField) { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.realizeforeignfield.exit", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.realizeforeignfield.exit", Boolean.valueOf(isPresent)); } @@ -1908,7 +1937,7 @@ private void populateForeignField(ForeignFieldDesc foreignField) { if (!foundInstance) { // Query lookup, returns a collection. - Collection result = retrieveForeign(foreignField); + Collection result = retrieveForeign(foreignField); attachQueryResult(foreignField, result); } @@ -1925,7 +1954,7 @@ private void populateForeignField(ForeignFieldDesc foreignField) { * foreignField. */ private void attachQueryResult(ForeignFieldDesc foreignField, - Collection queryResult) { + Collection queryResult) { assert foreignField != null; // Attach the object(s) we got back to our managed object. @@ -1942,9 +1971,9 @@ private void attachQueryResult(ForeignFieldDesc foreignField, } else { if (queryResult.size() > 1) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.persistencestore.toomanyobjforcard1", // NOI18N + "core.persistencestore.toomanyobjforcard1", persistenceConfig.getName(), - foreignField.getName(), "" + queryResult.size())); // NOI18N + foreignField.getName(), "" + queryResult.size())); } Object v = queryResult.iterator().next(); foreignField.setValue(this, v); @@ -1973,14 +2002,14 @@ private void attachQueryResult(ForeignFieldDesc foreignField, * is not set or the passed relationship field is null. * @see #retrieve */ - private Collection retrieveForeign(ForeignFieldDesc foreignField) { + private Collection retrieveForeign(ForeignFieldDesc foreignField) { assert foreignField != null; - Collection result = null; - boolean debug = logger.isLoggable(); + Collection result = null; + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.retrieveforeign", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.retrieveforeign", foreignField.getName()); } @@ -1988,7 +2017,7 @@ private Collection retrieveForeign(ForeignFieldDesc foreignField) { boolean isValidForeignKey = true; for (int i = 0; i < foreignField.localFields.size(); i++) { - FieldDesc flf = (FieldDesc) foreignField.localFields.get(i); + FieldDesc flf = foreignField.localFields.get(i); if (!getPresenceMaskBit(i)) { // throw exception @@ -2013,12 +2042,12 @@ private Collection retrieveForeign(ForeignFieldDesc foreignField) { // Getting a new generated RD or a cached one. RetrieveDesc fdesc = persistenceConfig.getRetrieveDescForFKQuery(foreignField, store); - result = (Collection) store.retrieve( + result = (Collection) store.retrieve( persistenceManager, fdesc, new QueryValueFetcher(values)); } if (debug) { - logger.fine("sqlstore.sqlstatemanager.retrieveforeign.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.retrieveforeign.exit"); } return result; @@ -2037,11 +2066,11 @@ private Collection retrieveForeign(ForeignFieldDesc foreignField) { * @see #retrieveForeign */ private void retrieve(FieldDesc additionalField) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { String fieldName = (additionalField != null) ? additionalField.getName() : null; - logger.fine("sqlstore.sqlstatemanager.retrieve", fieldName); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.retrieve", fieldName); } LocalFieldDesc[] keyFields = persistenceConfig.getKeyFieldDescs(); @@ -2050,24 +2079,24 @@ private void retrieve(FieldDesc additionalField) { // Getting a new generated RD or a cached one. RetrieveDesc rd = persistenceConfig.getRetrieveDescForPKQuery(additionalField, store); - Collection result = (Collection) store. + Collection result = (Collection) store. retrieve(persistenceManager, rd, new QueryValueFetcher(values)); if (result.size() > 1) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.toomanyrows", // NOI18N + "core.statemanager.toomanyrows", persistenceConfig.getPersistenceCapableClass().getName())); } else if (result.size() < 1 || result.iterator().next() != persistentObject) { // If there are no instances fetched, or the fetched instances is not the one // we asked for, it means that it is not found and we throw an exception throw new JDOObjectNotFoundException(I18NHelper.getMessage(messages, - "core.statemanager.objectnotfound"), // NOI18N + "core.statemanager.objectnotfound"), new Object[]{persistentObject}); } if (debug) { - logger.fine("sqlstore.sqlstatemanager.retrieve.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.retrieve.exit"); } } @@ -2098,10 +2127,10 @@ public SQLStateManager getBeforeImage() { // Do not try to get before image if not required if (beforeImage == null && isBeforeImageRequired()) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - logger.fine("sqlstore.sqlstatemanager.getbeforeimage", // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.getbeforeimage", persistenceConfig.getPersistenceCapableClass().getName()); } @@ -2115,7 +2144,7 @@ public SQLStateManager getBeforeImage() { } if (debug) { - logger.fine("sqlstore.sqlstatemanager.getbeforeimage.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.getbeforeimage.exit"); } } @@ -2134,11 +2163,8 @@ public boolean isBeforeImageRequired() { getUpdateDesc().hasChangedRelationships() || t.getRetainValues() || t.getRestoreValues() || persistenceConfig.hasModifiedCheckAtCommitConsistency(); - if (logger.isLoggable(Logger.FINER)) { - logger.finer("sqlstore.sqlstatemanager.isbeforeimagerequired", // NOI18N - Boolean.valueOf(isBeforeImageRequired)); - } - return isBeforeImageRequired; + LOG.log(DEBUG, "sqlstore.sqlstatemanager.isbeforeimagerequired", Boolean.valueOf(isBeforeImageRequired)); + return isBeforeImageRequired; } private SQLStateManager copyPersistent() { @@ -2161,6 +2187,7 @@ private SQLStateManager copyPersistent() { * not instanceof SQLStateManager, or is not managing the * same type of persistent instance as this StateManager. */ + @Override public void copyFields(StateManager source) { if (!(source instanceof SQLStateManager)) { String className = @@ -2171,16 +2198,10 @@ public void copyFields(StateManager source) { SQLStateManager sqlSource = (SQLStateManager) source; if (persistenceConfig != sqlSource.getPersistenceConfig()) { - Class thisPCClass = - persistenceConfig.getPersistenceCapableClass(); - Class sourcePCClass = - sqlSource.getPersistenceConfig().getPersistenceCapableClass(); - throw new IllegalArgumentException( - I18NHelper.getMessage( - messages, - "core.statemanager.copyFields.mismatch", // NOI18N - thisPCClass.getName(), - sourcePCClass.getName())); + Class thisPCClass = persistenceConfig.getPersistenceCapableClass(); + Class sourcePCClass = sqlSource.getPersistenceConfig().getPersistenceCapableClass(); + throw new IllegalArgumentException(I18NHelper.getMessage(messages, "core.statemanager.copyFields.mismatch", + thisPCClass.getName(), sourcePCClass.getName())); } copyFields(sqlSource, false, true); @@ -2197,7 +2218,7 @@ public void copyFields(StateManager source) { private void copyFields(SQLStateManager source, boolean copyRelationships, boolean clone) { - ArrayList fields = null; + List fields = null; // Reset the field masks, as the instance will // be populated with the state from the source. @@ -2212,7 +2233,7 @@ private void copyFields(SQLStateManager source, } for (int j = 0; (fields != null) && (j < fields.size()); j++) { - FieldDesc f = (FieldDesc) fields.get(j); + FieldDesc f = fields.get(j); if (!copyRelationships && f.isRelationshipField()) { continue; @@ -2243,10 +2264,10 @@ private Object cloneObjectMaybe(Object source) { !(source instanceof com.sun.jdo.api.persistence.support.PersistenceCapable) && !(source instanceof byte[])) { try { - Class type = source.getClass(); + Class type = source.getClass(); if (!type.isArray()) { - Method m = type.getMethod("clone", (Class []) null); // NOI18N + Method m = type.getMethod("clone", (Class []) null); if (m != null) { return m.invoke(source, (Object []) null); @@ -2261,13 +2282,8 @@ private Object cloneObjectMaybe(Object source) { } return dstArray; } - } catch (NoSuchMethodException e) { - if (logger.isLoggable()) { - Object[] items = new Object[] {e, source.getClass().getName()}; - logger.fine("sqlstore.sqlstatemanager.nosuchmethodexcep.clone", items); // NOI18N - } - } catch (InvocationTargetException e) { - } catch (IllegalAccessException e) { + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + LOG.log(DEBUG, "sqlstore.sqlstatemanager.nosuchmethodexcep.clone", e, source.getClass().getName()); } } } @@ -2288,7 +2304,7 @@ private Object cloneObjectMaybe(Object source) { * State managers of autopersistent objects will be added to this list. * @see #prepareUpdateFieldSpecial */ - private void prepareUpdateField(FieldDesc fieldDesc, ArrayList newlyRegisteredSMs) { + private void prepareUpdateField(FieldDesc fieldDesc, ArrayList newlyRegisteredSMs) { // No updates for key fields. As this method is called by // loadForUpdate for _all_ DFG fields (to prepare a hollow @@ -2300,11 +2316,10 @@ private void prepareUpdateField(FieldDesc fieldDesc, ArrayList newlyRegisteredSM getUpdateDesc().markRelationshipChange(fieldDesc); - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { - Object[] items = new Object[] {fieldDesc.getName(),state}; - logger.fine("sqlstore.sqlstatemanager.prepareupdatefield", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.prepareupdatefield", fieldDesc.getName(),state); } boolean optimistic = persistenceManager.isOptimisticTransaction(); @@ -2345,7 +2360,7 @@ private void prepareUpdateField(FieldDesc fieldDesc, ArrayList newlyRegisteredSM recordUpdatedField(fieldDesc); if (debug) { - logger.fine("sqlstore.sqlstatemanager.prepareupdatefield.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.prepareupdatefield.exit"); } } @@ -2372,11 +2387,7 @@ private void updateBeforeImage(FieldDesc fieldDesc, Object value) { } if (value != null) { - if (logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {fieldDesc, value}; - logger.finest("sqlstore.sqlstatemanager.updatebeforeimage", items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.sqlstatemanager.updatebeforeimage", fieldDesc, value); fieldDesc.setValue(beforeImage, cloneObjectMaybe(value)); beforeImage.setPresenceMaskBit(fieldDesc.absoluteID); } @@ -2390,19 +2401,13 @@ private void updateBeforeImage(FieldDesc fieldDesc, Object value) { * @param fieldDesc Updated field. */ private void recordUpdatedField(FieldDesc fieldDesc) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (!fieldDesc.isRelationshipField() && (fieldDesc.sqlProperties & FieldDesc.PROP_RECORD_ON_UPDATE) > 0) { - if (debug) { - logger.finest("sqlstore.sqlstatemanager.recordingfield", fieldDesc); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.recordingfield", fieldDesc); getUpdateDesc().recordUpdatedField((LocalFieldDesc) fieldDesc); } - if (debug) { - logger.finest("sqlstore.sqlstatemanager.makedirtyfield", fieldDesc); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.makedirtyfield", fieldDesc); setSetMaskBit(fieldDesc.absoluteID); } @@ -2413,12 +2418,10 @@ private void recordUpdatedField(FieldDesc fieldDesc) { * @param sm Second state manager. * @see StateManager#addDependency(StateManager sm) */ + @Override public void addDependency(StateManager sm) { - if (logger.isLoggable()) { - Object[] items = new Object[] {this, sm}; - logger.fine("sqlstore.sqlstatemanager.adddependency", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.adddependency", this, sm); // The simple solution is to call addUpdatedForeignReference() // internally. It might try to reregister both instances again, @@ -2452,16 +2455,15 @@ public void addDependency(StateManager sm) { * This method checks the dependencies for all instances waiting for the * current state manager to be flushed to the store. */ + @Override public void resolveDependencies() { - if (logger.isLoggable()) { - logger.fine("sqlstore.sqlstatemanager.resolvedependencies", this.getPersistent()); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.resolvedependencies", this.getPersistent()); if (updatedForeignReferences != null) { - Iterator iter = updatedForeignReferences.iterator(); + Iterator iter = updatedForeignReferences.iterator(); while (iter.hasNext()) { - final UpdatedForeignReference ufr = (UpdatedForeignReference) iter.next(); + final UpdatedForeignReference ufr = iter.next(); final ForeignFieldDesc fieldDesc = ufr.getFieldDesc(); final SQLStateManager foreignSM = ufr.getStateManager(); @@ -2531,9 +2533,9 @@ private boolean resolveDependency(ForeignFieldDesc fieldDesc, } } - if (removeDependency && logger.isLoggable()) { + if (removeDependency && LOG.isLoggable(DEBUG)) { Object[] items = new Object[] {this.getPersistent(), fieldDesc.getName(), pc}; - logger.fine("sqlstore.sqlstatemanager.resolvedependency", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.resolvedependency", items); } return removeDependency; } @@ -2571,7 +2573,7 @@ static private boolean checkRelationship(SQLStateManager sm, if (fieldDesc.cardinalityUPB > 1) { // Checking directly for contains doesn't work for deferred SCOCollections. - Collection c = sm.getCollectionValue(fieldDesc); + Collection c = sm.getCollectionValue(fieldDesc); // Resulting collection can't be null because the presence mask is set. related = c.contains(pc); @@ -2654,7 +2656,7 @@ private void addUpdatedForeignReference(ForeignFieldDesc fieldDesc, SQLStateMana // a problem after this instance has been flushed, and updatedForeignReferences // is now an empty collection. if (updatedForeignReferences == null) { - updatedForeignReferences = new HashSet(); + updatedForeignReferences = new HashSet<>(); // Register this instance disregarding it's LifeCycle state. // Otherwise, its state may never be reset after the transaction commits. @@ -2668,12 +2670,9 @@ private void addUpdatedForeignReference(ForeignFieldDesc fieldDesc, SQLStateMana sm.stateFlags |= ST_UPDATE_DISABLED; sm.referenceCount++; - if (logger.isLoggable() ) { - String fieldName = (fieldDesc != null) ? fieldDesc.getName() : null; - Object[] items = new Object[] {this.persistentObject, fieldName, - sm.persistentObject, new Integer(sm.referenceCount)}; - logger.fine("sqlstore.sqlstatemanager.addupdate", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.addupdate", this.persistentObject, + fieldDesc == null ? null : fieldDesc.getName(), + sm.persistentObject, sm.referenceCount); // Register this instance disregarding it's LifeCycle state. // Otherwise, its state may never be reset after the transaction commits. @@ -2703,12 +2702,9 @@ private void removeUpdatedForeignReference(ForeignFieldDesc fieldDesc, SQLStateM if (updatedForeignReferences.remove(new UpdatedForeignReference(fieldDesc, sm))) { sm.referenceCount--; - if (logger.isLoggable()) { - String fieldName = (fieldDesc != null) ? fieldDesc.getName() : null; - Object[] items = new Object[] {this.persistentObject, fieldName, - sm.persistentObject, new Integer(sm.referenceCount)}; - logger.fine("sqlstore.sqlstatemanager.removeupdate", items); // NOI18N - } + String fieldName = (fieldDesc != null) ? fieldDesc.getName() : null; + LOG.log(DEBUG, "sqlstore.sqlstatemanager.removeupdate", this.persistentObject, fieldName, + sm.persistentObject, sm.referenceCount); if (sm.referenceCount == 0) { sm.stateFlags &= ~ST_UPDATE_DISABLED; @@ -2740,11 +2736,11 @@ private boolean updateObjectField(ForeignFieldDesc fieldDesc, boolean updateInverseRelationshipField, boolean managedRelationshipInProgress) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { Object[] items = new Object[] {fieldDesc.getName(),fieldDesc.getComponentType()}; - logger.fine("sqlstore.sqlstatemanager.updateobjfield", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updateobjfield", items); } Object removedObject = fieldDesc.getValue(this); @@ -2759,7 +2755,7 @@ private boolean updateObjectField(ForeignFieldDesc fieldDesc, // If the new value is already deleted, we throw an exception. if (addedSM != null && addedSM.isDeleted()) { JDOUserException ex = new JDOUserException(I18NHelper.getMessage(messages, - "jdo.lifecycle.deleted.accessField")); // NOI18N + "jdo.lifecycle.deleted.accessField")); ex.addFailedObject(addedObject); throw ex; } @@ -2778,7 +2774,7 @@ private boolean updateObjectField(ForeignFieldDesc fieldDesc, } if (debug) { - logger.fine("sqlstore.sqlstatemanager.updateobjfield.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.updateobjfield.exit"); } return true; @@ -3031,7 +3027,7 @@ private void manageDependencyForObjectField(ForeignFieldDesc fieldDesc, * @return State manager for the added object. The statemanager will * be not null for all persistence capable objects != null. */ - private SQLStateManager getAddedSM(Object addedObject, ArrayList newlyRegisteredSMs) { + private SQLStateManager getAddedSM(Object addedObject, List newlyRegisteredSMs) { SQLStateManager addedSM = null; if (addedObject != null) { @@ -3090,13 +3086,13 @@ private SQLStateManager getRemovedSM(Object removedObject) { * @see #prepareSetField(FieldDesc,Object,boolean) */ private void processCollectionUpdates(ForeignFieldDesc fieldDesc, - ArrayList removedList, - ArrayList addedList, - ArrayList newlyRegisteredSMs, + List removedList, + List addedList, + List newlyRegisteredSMs, boolean updateInverseRelationshipField, boolean managedRelationshipInProgress) { - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); ForeignFieldDesc inverseFieldDesc = fieldDesc.getInverseRelationshipField(); // RESOLVE: What if @@ -3105,7 +3101,7 @@ private void processCollectionUpdates(ForeignFieldDesc fieldDesc, if (debug) { Object[] items = new Object[] {removedList,addedList}; - logger.fine("sqlstore.sqlstatemanager.processcollectionupdate", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.processcollectionupdate", items); } // removedList contains the list of objects removed. @@ -3122,7 +3118,7 @@ private void processCollectionUpdates(ForeignFieldDesc fieldDesc, } if (debug) { - logger.fine("sqlstore.sqlstatemanager.processcollectionupdate.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.processcollectionupdate.exit"); } } @@ -3140,7 +3136,7 @@ private void processCollectionUpdates(ForeignFieldDesc fieldDesc, * @see #processCollectionUpdates */ private void removeCollectionRelationship(ForeignFieldDesc fieldDesc, - ArrayList removedList, + List removedList, ForeignFieldDesc inverseFieldDesc, boolean updateInverseRelationshipField, boolean managedRelationshipInProgress) { @@ -3197,13 +3193,13 @@ private void nullifyForeignKey(ForeignFieldDesc fieldDesc, // which can also be retrieved from inverseFieldDesc. if (fieldDesc != null) { for (int i = 0; i < fieldDesc.localFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) fieldDesc.localFields.get(i); + LocalFieldDesc la = fieldDesc.localFields.get(i); nullifyForeignKey(fieldDesc, la); } } else { for (int i = 0; i < inverseFieldDesc.foreignFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) inverseFieldDesc.foreignFields.get(i); + LocalFieldDesc la = inverseFieldDesc.foreignFields.get(i); nullifyForeignKey(fieldDesc, la); } @@ -3311,7 +3307,7 @@ private void removeJoinTableEntry(ForeignFieldDesc fieldDesc, } } else if (fieldDesc == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantschedulejointable", // NOI18N + "core.statemanager.cantschedulejointable", this.getPersistenceConfig().getPersistenceCapableClass().getName(), removedSM.getPersistenceConfig().getPersistenceCapableClass().getName())); } @@ -3361,9 +3357,9 @@ private void removeRelationship(ForeignFieldDesc fieldDesc, SQLStateManager remo * @see #processCollectionUpdates */ private void addCollectionRelationship(ForeignFieldDesc fieldDesc, - ArrayList addedList, + List addedList, ForeignFieldDesc inverseFieldDesc, - ArrayList newlyRegisteredSMs, + List newlyRegisteredSMs, boolean updateInverseRelationshipField, boolean managedRelationshipInProgress) { @@ -3384,7 +3380,7 @@ private void addCollectionRelationship(ForeignFieldDesc fieldDesc, if (inverseFieldDesc != null) { if (ex == null) { ex = new JDOUserException(I18NHelper.getMessage(messages, - "jdo.lifecycle.deleted.accessField")); // NOI18N + "jdo.lifecycle.deleted.accessField")); } ex.addFailedObject(addedObject); @@ -3438,15 +3434,15 @@ private void setForeignKey(ForeignFieldDesc fieldDesc, // which can also be retrieved from inverseFieldDesc. if (fieldDesc != null) { for (int i = 0; i < fieldDesc.localFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) fieldDesc.localFields.get(i); - LocalFieldDesc fa = (LocalFieldDesc) fieldDesc.foreignFields.get(i); + LocalFieldDesc la = fieldDesc.localFields.get(i); + LocalFieldDesc fa = fieldDesc.foreignFields.get(i); setForeignKey(fieldDesc, la, fa.getValue(addedSM)); } } else { for (int i = 0; i < inverseFieldDesc.foreignFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) inverseFieldDesc.foreignFields.get(i); - LocalFieldDesc fa = (LocalFieldDesc) inverseFieldDesc.localFields.get(i); + LocalFieldDesc la = inverseFieldDesc.foreignFields.get(i); + LocalFieldDesc fa = inverseFieldDesc.localFields.get(i); setForeignKey(fieldDesc, la, fa.getValue(addedSM)); } @@ -3530,7 +3526,7 @@ private void addJoinTableEntry(ForeignFieldDesc fieldDesc, } } else if (fieldDesc == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantschedulejointable", // NOI18N + "core.statemanager.cantschedulejointable", this.getPersistenceConfig().getPersistenceCapableClass().getName(), addedSM.getPersistenceConfig().getPersistenceCapableClass().getName())); } @@ -3604,16 +3600,16 @@ private synchronized void prepareUpdateFieldSpecial(FieldDesc fieldDesc, boolean createDeferredCollection) { if (fieldDesc.isKeyField()) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "core.statemanager.nopkupdate")); // NOI18N + "core.statemanager.nopkupdate")); } getUpdateDesc().markRelationshipChange(fieldDesc); - boolean debug = logger.isLoggable(); + boolean debug = LOG.isLoggable(DEBUG); if (debug) { Object[] items = new Object[] {fieldDesc.getName(),state}; - logger.fine("sqlstore.sqlstatemanager.prepareupdatefieldspl", items); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.prepareupdatefieldspl", items); } boolean optimistic = persistenceManager.isOptimisticTransaction(); @@ -3678,7 +3674,7 @@ private synchronized void prepareUpdateFieldSpecial(FieldDesc fieldDesc, recordUpdatedField(fieldDesc); if (debug) { - logger.fine("sqlstore.sqlstatemanager.prepareupdatefieldspl.exit"); // NOI18N + LOG.log(DEBUG, "sqlstore.sqlstatemanager.prepareupdatefieldspl.exit"); } } @@ -3708,24 +3704,19 @@ private void updateTrackedFields(FieldDesc fieldDesc, Object value, ForeignFieldDesc fieldToIgnore) { - ArrayList trackedFields = fieldDesc.getTrackedFields(); + List trackedFields = fieldDesc.getTrackedFields(); if (trackedFields == null) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - Object[] items = new Object[] {fieldDesc.getName(), value, - ((fieldToIgnore != null) ? fieldToIgnore.getName() : null)}; - logger.finest("sqlstore.sqlstatemanager.updatetrackedfields", items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.updatetrackedfields", fieldDesc.getName(), value, + (fieldToIgnore != null ? fieldToIgnore.getName() : null)); Object currentValue = fieldDesc.getValue(this); int size = trackedFields.size(); - ArrayList fieldsToIgnore = ((fieldToIgnore != null) ? fieldToIgnore.getTrackedFields() : null); + List fieldsToIgnore = ((fieldToIgnore != null) ? fieldToIgnore.getTrackedFields() : null); if (fieldDesc instanceof ForeignFieldDesc) { // For tracked relationship fields, we simply set the new value. @@ -3745,7 +3736,7 @@ private void updateTrackedFields(FieldDesc fieldDesc, } for (int i = 0; i < size; i++) { - FieldDesc tf = (FieldDesc) trackedFields.get(i); + FieldDesc tf = trackedFields.get(i); if (tf instanceof LocalFieldDesc) { Object convertedValue = null; @@ -3762,7 +3753,7 @@ private void updateTrackedFields(FieldDesc fieldDesc, // NOTE: We don't have to revert relationship fields // because they come after all the primitive fields. for (int j = 0; j < i; j++) { - tf = (FieldDesc) trackedFields.get(j); + tf = trackedFields.get(j); tf.setValue(this, previousValues[j]); } @@ -3804,9 +3795,7 @@ private void updateTrackedFields(FieldDesc fieldDesc, } } - if (debug) { - logger.finest("sqlstore.sqlstatemanager.updatetrackedfields.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.updatetrackedfields.exit"); } /** @@ -3871,7 +3860,7 @@ private Object doUpdateField(FieldDesc fieldDesc, if (fieldDesc instanceof ForeignFieldDesc) { ForeignFieldDesc ff = (ForeignFieldDesc) fieldDesc; if (ff.cardinalityUPB > 1) { - updateCollectionField(ff, (Collection) value, + updateCollectionField(ff, (Collection) value, managedRelationshipInProgress); } else { updateObjectField(ff, value, true, @@ -3931,11 +3920,7 @@ private Object prepareSetField(FieldDesc fieldDesc, Object value, private Object prepareSetField(FieldDesc fieldDesc, Object value, boolean managedRelationshipInProgress, boolean acquireShareLock) { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - logger.finest("sqlstore.sqlstatemanager.preparesetfield", fieldDesc.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.preparesetfield", fieldDesc.getName()); if (acquireShareLock) { persistenceManager.acquireShareLock(); @@ -3946,7 +3931,7 @@ private Object prepareSetField(FieldDesc fieldDesc, Object value, if ((fieldDesc.sqlProperties & FieldDesc.PROP_READ_ONLY) > 0) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.statemanager.readonly", fieldDesc.getName(), // NOI18N + "core.statemanager.readonly", fieldDesc.getName(), persistentObject.getClass().getName())); } @@ -3969,18 +3954,15 @@ private Object prepareSetField(FieldDesc fieldDesc, Object value, } catch (JDOException e) { throw e; } catch (Exception e) { - logger.log(Logger.FINE,"sqlstore.exception.log", e); throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.setfieldfailed"), e); // NOI18N + "core.statemanager.setfieldfailed"), e); } finally { if (acquireShareLock) { persistenceManager.releaseShareLock(); } releaseLock(); - if (debug) { - logger.finest("sqlstore.sqlstatemanager.preparesetfield.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.preparesetfield.exit"); } } @@ -3994,22 +3976,18 @@ private Object prepareSetField(FieldDesc fieldDesc, Object value, * True during relationship management. */ private void updateCollectionField(ForeignFieldDesc fieldDesc, - Collection value, + Collection value, boolean managedRelationshipInProgress) { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - Object[] items = new Object[] {value,((value == null)? "NO" : value.getClass().getName())}; // NOI18N - logger.finest("sqlstore.sqlstatemanager.processforeignfield", items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlstatemanager.processforeignfield", value, + (value == null ? "NO" : value.getClass().getName())); Object currVal = fieldDesc.getValue(this); // Do nothing if the current value is identical to the new value. if (currVal != value) { Object owner = null; - ArrayList added = null; - ArrayList removed = null; + ArrayList added = null; + ArrayList removed = null; // Verify SCO owner and fieldName if any if (value != null && value instanceof SCOCollection) { @@ -4024,49 +4002,43 @@ private void updateCollectionField(ForeignFieldDesc fieldDesc, !fieldDesc.getName().equals(sco.getFieldName())) { throw new JDOUserException(I18NHelper.getMessage( - messages, "core.statemanager.anotherowner"), // NOI18N + messages, "core.statemanager.anotherowner"), new Object[]{owner, sco.getFieldName()}); } // SCO should not behave as a JDK collection, // but become owned and tracked at setXXX operation. - added = new ArrayList(value); + added = new ArrayList<>(value); } Object befrVal = fieldDesc.getValue(beforeImage); if (currVal != null) { - if (debug) - logger.finest("sqlstore.sqlstatemanager.processforeignfield.remove"); // NOI18N + LOG.log(TRACE, "sqlstore.sqlstatemanager.processforeignfield.remove"); // This is a setXXX (i.e. replace) operation, we need to // "remove" elements from the current SCOCollection and mark it as not used - if (((Collection) currVal).size() > 0) { - removed = new ArrayList((Collection) currVal); + if (((Collection) currVal).size() > 0) { + removed = new ArrayList<>((Collection) currVal); } if (currVal instanceof SCOCollection) { - if (debug) - logger.finest("sqlstore.sqlstatemanager.processforeignfield.reset"); // NOI18N + LOG.log(TRACE, "sqlstore.sqlstatemanager.processforeignfield.reset"); // SCOCollection: mark it as not used ((SCO) currVal).unsetOwner(); } - } else if (getSetMaskBit(fieldDesc.absoluteID) == false && befrVal != null) - // && value instanceof SCOCollection && owner != null) - { - if (debug) - logger.finest("sqlstore.sqlstatemanager.processforeignfield.remove_from_bi"); // NOI18N + } else if (getSetMaskBit(fieldDesc.absoluteID) == false && befrVal != null) { + LOG.log(TRACE, "sqlstore.sqlstatemanager.processforeignfield.remove_from_bi"); // Replace with SCOCollection: mark beforeImage as removed - - if (((Collection) befrVal).size() > 0) { - removed = new ArrayList((Collection) befrVal); + if (((Collection) befrVal).size() > 0) { + removed = new ArrayList<>((Collection) befrVal); } } - processCollectionUpdates(fieldDesc, removed, added, null, true, - managedRelationshipInProgress); + processCollectionUpdates(fieldDesc, removed, added, null, true, managedRelationshipInProgress); } } + @Override public Object clone() { SQLStateManager clone = new SQLStateManager(store, persistenceConfig); clone.persistenceManager = persistenceManager; @@ -4075,9 +4047,10 @@ public Object clone() { } private void assertNotPK(int fieldNumber) { - if (persistenceConfig.isPKField(fieldNumber)) + if (persistenceConfig.isPKField(fieldNumber)) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "core.statemanager.nopkupdate")); // NOI18N + "core.statemanager.nopkupdate")); + } } private void assertPKUpdate(FieldDesc f, Object value) { @@ -4096,13 +4069,14 @@ private void assertPKUpdate(FieldDesc f, Object value) { if (throwException) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "core.statemanager.nopkupdate")); // NOI18N + "core.statemanager.nopkupdate")); } } /** * ... */ + @Override public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceManagerInternal() { return persistenceManager; } @@ -4110,6 +4084,7 @@ public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceMana /** * ... */ + @Override public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceManager() { return (persistenceManager == null)? null : persistenceManager.getCurrentWrapper(); } @@ -4119,6 +4094,7 @@ public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceMana * ... */ // !!! olsen: changed to return byte instead of void (->PC.jdoSetFlags()) + @Override public byte setFlags(byte flags) { // RESOLVE: Need to verify that the flags are valid with the current // state of the state manager. @@ -4129,12 +4105,9 @@ public byte setFlags(byte flags) { * Triggers the state transition for READ and registers the * instance in the transaction cache. */ + @Override public void loadForRead() { - boolean debug = logger.isLoggable(Logger.FINER); - - if (debug) { - logger.finer("sqlstore.sqlstatemanager.loadforread"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.loadforread"); persistenceManager.acquireShareLock(); @@ -4171,9 +4144,7 @@ public void loadForRead() { persistenceManager.releaseShareLock(); releaseLock(); - if (debug) { - logger.finer("sqlstore.sqlstatemanager.loadforread.exit"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.loadforread.exit"); } } @@ -4181,12 +4152,9 @@ public void loadForRead() { * Triggers the state transition for WRITE and registers the instance * in the transaction cache. Prepares all DFG fields for update. */ + @Override public void loadForUpdate() { - boolean debug = logger.isLoggable(Logger.FINER); - - if (debug) { - logger.finer("sqlstore.sqlstatemanager.loadforupdate"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.loadforupdate"); persistenceManager.acquireShareLock(); @@ -4203,12 +4171,12 @@ public void loadForUpdate() { persistenceManager.setFlags(persistentObject, READ_WRITE_OK); - ArrayList fields = persistenceConfig.fields; + List fields = persistenceConfig.fields; try { // Mark all the fields in the dfg dirty. for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); if (f.fetchGroup == FieldDesc.GROUP_DEFAULT) { //prepareSetField(f, null); @@ -4224,9 +4192,7 @@ public void loadForUpdate() { persistenceManager.releaseShareLock(); releaseLock(); - if (debug) { - logger.finer("sqlstore.sqlstatemanager.loadforupdate.exit"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstatemanager.loadforupdate.exit"); } } @@ -4238,8 +4204,8 @@ public void loadForUpdate() { * it calls applyDeferredUpdates on the collection passing in c. Otherwise, * it clears the collection and repopulates with elements in c. */ - public synchronized void replaceCollection(ForeignFieldDesc ff, Collection c) { - Collection collection = (Collection) ff.getValue(this); + public synchronized void replaceCollection(ForeignFieldDesc ff, Collection c) { + Collection collection = (Collection) ff.getValue(this); SCOCollection scoCollection = null; @@ -4257,7 +4223,7 @@ public synchronized void replaceCollection(ForeignFieldDesc ff, Collection c) { scoCollection.applyDeferredUpdates(c); // We need to mark all the tracked fields as present. - ArrayList trackedFields = ff.getTrackedFields(); + List trackedFields = ff.getTrackedFields(); if (trackedFields != null) { for (int i = 0; i < trackedFields.size(); i++) { ForeignFieldDesc tf = (ForeignFieldDesc) trackedFields.get(i); @@ -4296,6 +4262,7 @@ protected LifeCycleState getCurrentState() { /** * ... */ + @Override public boolean isDirty() { if (state != null) { return state.isDirty(); @@ -4307,6 +4274,7 @@ public boolean isDirty() { /** * ... */ + @Override public boolean isTransactional() { if (state != null) { return state.isTransactional(); @@ -4318,6 +4286,7 @@ public boolean isTransactional() { /** * ... */ + @Override public boolean isNew() { if (state != null) { return state.isNew(); @@ -4329,6 +4298,7 @@ public boolean isNew() { /** * ... */ + @Override public boolean isDeleted() { if (state != null) { return state.isDeleted(); @@ -4340,6 +4310,7 @@ public boolean isDeleted() { /** * ... */ + @Override public boolean isPersistent() { if (state != null) { return state.isPersistent(); @@ -4351,6 +4322,7 @@ public boolean isPersistent() { /** * @inheritDoc */ + @Override public boolean needsRegisterWithVersionConsistencyCache() { boolean rc = hasVersionConsistency(); if (rc && state != null) { @@ -4367,6 +4339,7 @@ public boolean needsRegisterWithVersionConsistencyCache() { /** * @inheritDoc */ + @Override public boolean needsUpdateInVersionConsistencyCache() { boolean rc = hasVersionConsistency(); if (rc && state != null) { @@ -4385,100 +4358,118 @@ public boolean needsUpdateInVersionConsistencyCache() { // serve as the hook for keeping track of changes made to the // StateManager. + @Override public boolean setBooleanField(int fieldNumber, boolean value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Boolean(value)); return value; } + @Override public boolean[] setBooleanArrayField(int fieldNumber, boolean[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public byte setByteField(int fieldNumber, byte value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Byte(value)); return value; } + @Override public byte[] setByteArrayField(int fieldNumber, byte[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public short setShortField(int fieldNumber, short value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Short(value)); return value; } + @Override public short[] setShortArrayField(int fieldNumber, short[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public int setIntField(int fieldNumber, int value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Integer(value)); return value; } + @Override public int[] setIntArrayField(int fieldNumber, int[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public long setLongField(int fieldNumber, long value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Long(value)); return value; } + @Override public long[] setLongArrayField(int fieldNumber, long[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public char setCharField(int fieldNumber, char value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Character(value)); return value; } + @Override public char setCharArrayField(int fieldNumber, char value) { prepareSetField(fieldNumber, null); return value; } + @Override public float setFloatField(int fieldNumber, float value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Float(value)); return value; } + @Override public float[] setFloatArrayField(int fieldNumber, float[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public double setDoubleField(int fieldNumber, double value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, new Double(value)); return value; } + @Override public double[] setDoubleArrayField(int fieldNumber, double[] value) { prepareSetField(fieldNumber, null); return value; } + @Override public String setStringField(int fieldNumber, String value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, value); return value; } + @Override public String[] setStringArrayField(int fieldNumber, String[] value) { prepareSetField(fieldNumber, null); return value; @@ -4487,28 +4478,33 @@ public String[] setStringArrayField(int fieldNumber, String[] value) { /** * This method sets object fields, e.g. relationship fields. */ + @Override public Object setObjectField(int fieldNumber, Object value) { assertNotPK(fieldNumber); prepareSetField(fieldNumber, value); return value; } + @Override public Object[] setObjectArrayField(int fieldNumber, Object[] value) { prepareSetField(fieldNumber, value); return value; } + @Override public boolean testIsLoaded(int fieldNumber) { return getPresenceMaskBit(fieldNumber); } + @Override public boolean testIsLoaded(String fieldName) { FieldDesc f = persistenceConfig.getField(fieldName); return testIsLoaded(f.absoluteID); } + @Override public boolean testIsAutoPersistent() { return state.isAutoPersistent(); } @@ -4519,6 +4515,7 @@ public boolean testIsAutoPersistent() { * Used for replacing a deleted instance with the newly persistent with * the same object id. */ + @Override public void markNotRegistered() { needsRegisterAtRollback = true; } @@ -4527,6 +4524,7 @@ public void markNotRegistered() { * Marks this instance as needs to be verified at the time it is removed from the * global (weak) cache at rollback if it transitions to transient state. */ + @Override public void markVerifyAtDeregister() { needsVerifyAtDeregister = true; } @@ -4535,6 +4533,7 @@ public void markVerifyAtDeregister() { * Marks this instance as a replacement for a deleted instance with the same * ObjectId. */ + @Override public void markReplacement() { isReplacementInstance = true; } @@ -4543,6 +4542,7 @@ public void markReplacement() { * Lock this instance. */ // For consistency's sake, this should be changed to acquireLock. + @Override public void getLock() { lock.acquire(); } @@ -4550,6 +4550,7 @@ public void getLock() { /** * Release lock. */ + @Override public void releaseLock() { lock.release(); } @@ -4558,6 +4559,7 @@ public void releaseLock() { /** * Return value for valid flag. */ + @Override public boolean isValid() { return valid; } @@ -4566,6 +4568,7 @@ public boolean isValid() { * Mark this StateManager as valid. Called before returning from * getObjectById. */ + @Override public void setValid() { try { getLock(); @@ -4598,6 +4601,7 @@ private SQLStateManager getStateManager() { return sm; } + @Override public boolean equals(Object obj) { if (obj != null && this.getClass().equals(obj.getClass())) { @@ -4608,6 +4612,7 @@ public boolean equals(Object obj) { return (false); } + @Override public int hashCode() { int hashCode = sm.hashCode(); if (fieldDesc != null) { diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStoreManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStoreManager.java index ffd6ab1a84a..918379bd447 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStoreManager.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/SQLStoreManager.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,16 +15,8 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * SQLStoreManager.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore; -// use internal version: import com.sun.jdo.api.persistence.support.Transaction; import com.sun.jdo.api.persistence.support.JDODataStoreException; import com.sun.jdo.api.persistence.support.JDOException; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -38,23 +31,28 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.DBStatement; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.SelectQueryPlan; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.SelectStatement; +import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.Statement; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateQueryPlan; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateStatement; import com.sun.jdo.spi.persistence.utility.StringHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; + /** *

This class connects to a persistent store. It supports * relational databases such as Oracle and MS SQLServer. This class @@ -69,19 +67,13 @@ public class SQLStoreManager implements PersistenceStore { /** Encapsulates database type. */ private DBVendorType vendorType; - /** The logger. */ - private static Logger logger = LogHelperSQLStore.getLogger(); - - /** The sql logger. */ - private static Logger sqlLogger = LogHelperSQLStore.getSqlLogger(); - /** I18N message handler. */ - private final static ResourceBundle messages = I18NHelper.loadBundle( - SQLStoreManager.class); + private final static ResourceBundle messages = I18NHelper.loadBundle(SQLStoreManager.class); + private static final Logger LOG = System.getLogger(SQLStoreManager.class.getName(), RESOURCE_BUNDLE); /** Fetch size for query statements. */ private static int fetchSize = - Integer.getInteger("com.sun.jdo.spi.persistence.support.sqlstore.SQLStoreManager.fetchSize", // NOI18N + Integer.getInteger("com.sun.jdo.spi.persistence.support.sqlstore.SQLStoreManager.fetchSize", -1).intValue(); // -1 not set /** @@ -91,17 +83,16 @@ public class SQLStoreManager implements PersistenceStore { * a new instance is created, initialized and put into the cache. * The access to the model cache is synchronized. */ - public PersistenceConfig getPersistenceConfig(Class classType) { - if (logger.isLoggable(Logger.FINER)) { - logger.finer("sqlstore.sqlstoremanager.getpersistenceconfig", - classType.getName()); // NOI18N - } + @Override + public PersistenceConfig getPersistenceConfig(Class classType) { + LOG.log(DEBUG, "sqlstore.sqlstoremanager.getpersistenceconfig", classType.getName()); return configCache.getPersistenceConfig(classType); } /** * @inheritDoc */ + @Override public ConfigCache getConfigCache() { return configCache; } @@ -114,11 +105,12 @@ public ConfigCache getConfigCache() { * Will be thrown in case of errors or if the affected rows are * less than the minimum rows required. */ - public void execute(PersistenceManager pm, Collection actions) { - Iterator iter = actions.iterator(); + @Override + public void execute(PersistenceManager pm, Collection actions) { + Iterator iter = actions.iterator(); while (iter.hasNext()) { - ActionDesc action = (ActionDesc) iter.next(); + ActionDesc action = iter.next(); if (action instanceof UpdateObjectDescImpl) { UpdateObjectDescImpl request = (UpdateObjectDescImpl) action; @@ -135,9 +127,9 @@ public void execute(PersistenceManager pm, Collection actions) { } } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N + "core.generic.notinstanceof", action.getClass().getName(), - "UpdateObjectDescImpl")); // NOI18N + "UpdateObjectDescImpl")); } } } @@ -176,17 +168,11 @@ private void executeUpdate(PersistenceManager pm, UpdateStatement updateStatement, UpdateObjectDescImpl updateDesc) { int affectedRows = 0; - boolean debug = logger.isLoggable(); - - if (debug) { - logger.fine("sqlstore.sqlstoremanager.executeupdate"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdate"); String sqlText = updateStatement.getText(); if (sqlText.length() > 0) { - if (sqlLogger.isLoggable()) { - sqlLogger.fine(updateStatement.getFormattedSQLText()); - } + LOG.log(DEBUG, updateStatement.getFormattedSQLText()); Transaction tran = (Transaction) pm.currentTransaction(); Connection conn = tran.getConnection(); @@ -227,23 +213,22 @@ private void executeUpdate(PersistenceManager pm, } } - if (debug) { - logger.fine("sqlstore.sqlstoremanager.executeupdate.exit", // NOI18N - new Integer(affectedRows)); - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdate.exit", affectedRows); } /** * */ - public Class getClassByOidClass(Class oidType) { + @Override + public Class getClassByOidClass(Class oidType) { return configCache.getClassByOidClass(oidType); } /** * */ - public StateManager getStateManager(Class classType) { + @Override + public StateManager getStateManager(Class classType) { ClassDesc c = (ClassDesc) getPersistenceConfig(classType); if (c != null) { @@ -259,7 +244,8 @@ public StateManager getStateManager(Class classType) { * @param classType Type of the persistence capable class to be queried. * @return A new retrieve descriptor for anexternal (user) query. */ - public RetrieveDesc getRetrieveDesc(Class classType) { + @Override + public RetrieveDesc getRetrieveDesc(Class classType) { return new RetrieveDescImpl(classType, (ClassDesc) getPersistenceConfig(classType)); } @@ -272,7 +258,8 @@ public RetrieveDesc getRetrieveDesc(Class classType) { * @param classType Persistence capable class including fieldName. * @return A new retrieve descriptor for anexternal (user) query. */ - public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { + @Override + public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { ClassDesc c = (ClassDesc) getPersistenceConfig(classType); if (c != null) { @@ -289,7 +276,8 @@ public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { /** */ - public UpdateObjectDesc getUpdateObjectDesc(Class classType) { + @Override + public UpdateObjectDesc getUpdateObjectDesc(Class classType) { return new UpdateObjectDescImpl(classType); } @@ -317,18 +305,14 @@ private void setVendorType(DatabaseMetaData databaseMetaData, try { vendorType = new DBVendorType(databaseMetaData, identifier); - if (logger.isLoggable()) { - logger.fine("sqlstore.sqlstoremanager.vendortype",vendorType.getName()); // NOI18N - - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.vendortype",vendorType.getName()); } catch (Exception e) { if (e instanceof JDOException) { throw (JDOException) e; - } else { - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.getvendortypefailed"), e); // NOI18N } + throw new JDOFatalInternalException( + I18NHelper.getMessage(messages, "core.configuration.getvendortypefailed"), e); } } @@ -347,25 +331,26 @@ public DBVendorType getVendorType() { * @param parameters * Query parameters. */ + @Override public Object retrieve(PersistenceManager pm, RetrieveDesc action, ValueFetcher parameters) { if (action == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.nullparam", "action")); // NOI18N + "core.generic.nullparam", "action")); } if (!(action instanceof RetrieveDescImpl)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N + "core.generic.notinstanceof", action.getClass().getName(), - "RetrieveDescImpl")); // NOI18N + "RetrieveDescImpl")); } RetrieveDescImpl retrieveAction = ((RetrieveDescImpl) action); ClassDesc config = retrieveAction.getConfig(); Concurrency concurrency = config.getConcurrency(pm.isOptimisticTransaction()); SelectQueryPlan plan = retrieveAction.buildQueryPlan(this, concurrency); - ArrayList statements = plan.getStatements(); + List statements = plan.getStatements(); Object result = null; SelectStatement s = (SelectStatement) statements.get(0); @@ -380,8 +365,8 @@ public Object retrieve(PersistenceManager pm, RetrieveDesc action, ValueFetcher if (((plan.options & RetrieveDescImpl.OPT_FOR_UPDATE) > 0 && !vendorType.isDistinctSupportedWithUpdateLock()) ) { - HashSet hash = new HashSet(); - for (Iterator iter = ((Collection)result).iterator(); iter.hasNext(); ) { + HashSet hash = new HashSet<>(); + for (Iterator iter = ((Collection)result).iterator(); iter.hasNext(); ) { Object temp = iter.next(); if (!hash.contains(temp)) { hash.add(temp); @@ -416,16 +401,11 @@ private Object executeQuery(PersistenceManager pm, ValueFetcher parameters) { Object result = null; - boolean debug = logger.isLoggable(); - if (debug) { - logger.fine("sqlstore.sqlstoremanager.executeQuery"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeQuery"); String sqlText = statement.getText(); if (sqlText.length() > 0) { - if (sqlLogger.isLoggable()) { - sqlLogger.fine(statement.getFormattedSQLText(parameters)); - } + LOG.log(DEBUG, statement.getFormattedSQLText(parameters)); Transaction tran = null; if (concurrency != null) { @@ -480,9 +460,7 @@ private Object executeQuery(PersistenceManager pm, } } - if (debug) { - logger.fine("sqlstore.sqlstoremanager.executeQuery.exit"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeQuery.exit"); return result; } @@ -498,6 +476,7 @@ private Object executeQuery(PersistenceManager pm, * @param request the request corresponding with the current state manager * @param forceFlush all in the update query plan must be executed */ + @Override public void executeBatch(PersistenceManager pm, UpdateObjectDesc request, boolean forceFlush) @@ -509,9 +488,9 @@ public void executeBatch(PersistenceManager pm, objectRequest = (UpdateObjectDescImpl) request; } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N + "core.generic.notinstanceof", request.getClass().getName(), - "UpdateObjectDescImpl")); // NOI18N + "UpdateObjectDescImpl")); } ClassDesc config = objectRequest.getConfig(); @@ -542,8 +521,9 @@ public void executeBatch(PersistenceManager pm, // keep the DBStatement. cleanup = forceFlush; } finally { - if (cleanup) + if (cleanup) { closeDBStatements(plan, tran); + } closeConnection(tran, conn); } } @@ -564,20 +544,16 @@ private void executeUpdateBatch(Transaction tran, boolean doFlush) { int[] affectedRows = null; - boolean debug = logger.isLoggable(); - - if (debug) { - logger.fine("sqlstore.sqlstoremanager.executeupdatebatch"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdatebatch"); String sqlText = updateStatement.getText(); if (sqlText.length() > 0) { - if (sqlLogger.isLoggable()) { + if (LOG.isLoggable(DEBUG)) { String formattedText = updateStatement.getFormattedSQLText(updateDesc); if (doFlush) { - sqlLogger.fine("sqlstore.sqlstoremanager.executeupdatebatch.flushbatch", formattedText); + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdatebatch.flushbatch", formattedText); } else { - sqlLogger.fine("sqlstore.sqlstoremanager.executeupdatebatch.addbatch", formattedText); + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdatebatch.addbatch", formattedText); } } @@ -611,13 +587,11 @@ private void executeUpdateBatch(Transaction tran, } } - if (debug) { - if (doFlush) { - logger.fine("sqlstore.sqlstoremanager.executeupdatebatch.exit.flush", '[' + // NOI18N - StringHelper.intArrayToSeparatedList(affectedRows, ",") + ']'); //NOI18N - } else { - logger.fine("sqlstore.sqlstoremanager.executeupdatebatch.exit"); //NOI18N - } + if (doFlush) { + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdatebatch.exit.flush", + '[' + StringHelper.intArrayToSeparatedList(affectedRows, ",") + ']'); + } else { + LOG.log(DEBUG, "sqlstore.sqlstoremanager.executeupdatebatch.exit"); } } @@ -636,7 +610,7 @@ private void executeUpdateBatch(Transaction tran, static private void throwJDOSqlException(SQLException e, String sqlText) { String exceptionMessage = I18NHelper.getMessage(messages, - "core.persistencestore.jdbcerror", sqlText); // NOI18N + "core.persistencestore.jdbcerror", sqlText); throw new JDODataStoreException(exceptionMessage, e); } @@ -648,10 +622,10 @@ static private void throwJDOSqlException(SQLException e, String sqlText) { * @param sqlText Executed SQL statement. */ static private void throwJDOConcurrentAccessException(String sqlText) { - String operation = sqlText.substring(0, sqlText.indexOf(' ')); // NOI18N + String operation = sqlText.substring(0, sqlText.indexOf(' ')); throw new JDODataStoreException(I18NHelper.getMessage(messages, - "core.store.concurrentaccess", operation)); // NOI18N + "core.store.concurrentaccess", operation)); } /** @@ -664,8 +638,8 @@ static private void close(ResultSet r) { r.close(); } catch (SQLException ex) { // only log exception - logger.finest(I18NHelper.getMessage(messages, - "sqlstore.sqlstoremanager.errorcloseresultset", // NOI18N + LOG.log(TRACE, I18NHelper.getMessage(messages, + "sqlstore.sqlstoremanager.errorcloseresultset", ex.getLocalizedMessage())); } } @@ -681,8 +655,8 @@ static private void close(DBStatement s) { s.close(); } catch (SQLException ex) { // only log exception - logger.finest(I18NHelper.getMessage(messages, - "sqlstore.sqlstoremanager.errorclosestatement", // NOI18N + LOG.log(TRACE, I18NHelper.getMessage(messages, + "sqlstore.sqlstoremanager.errorclosestatement", ex.getLocalizedMessage())); } } @@ -704,8 +678,8 @@ static private void closeConnection(Transaction t, Connection c) { */ static private void closeDBStatements(UpdateQueryPlan plan, Transaction tran) { if ((plan != null) && (tran != null)) { - for (Iterator i = plan.getStatements().iterator(); i.hasNext(); ) { - UpdateStatement updateStmt = (UpdateStatement)i.next(); + for (Iterator i = plan.getStatements().iterator(); i.hasNext(); ) { + UpdateStatement updateStmt = (UpdateStatement) i.next(); DBStatement s = updateStmt.removeDBStatement(tran); close(s); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/StateManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/StateManager.java index e103d695dbc..84c8de12989 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/StateManager.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/StateManager.java @@ -193,7 +193,7 @@ public interface StateManager * This is the second phase of the commit processing. It populates phase3sms with all * the autopersistence instances that are no longer reachable from a persistent instance. */ - void prepareToUpdatePhaseII(java.util.HashSet phase3sms); + void prepareToUpdatePhaseII(java.util.HashSet phase3sms); /** * This is the third phase of commit processing. It sets up the delete dependencies among diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/VersionConsistencyCache.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/VersionConsistencyCache.java index 8f181b63461..29e84118475 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/VersionConsistencyCache.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/VersionConsistencyCache.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 @@ -32,14 +33,14 @@ public interface VersionConsistencyCache { * @param oid Object id, used as key in inner map. * @param sm StateManager bound to oid in inner map. */ - public StateManager put(Class pcType, Object oid, StateManager sm); + public StateManager put(Class pcType, Object oid, StateManager sm); /** * Returns an SM, if found, else null. * @param pcType class of instance, used as key in outer map. * @param oid Object id, used as key in inner map. */ - public StateManager get(Class pcType, Object oid); + public StateManager get(Class pcType, Object oid); /** * Removes entry based on pc and oid. If map is empty after remove, @@ -47,18 +48,18 @@ public interface VersionConsistencyCache { * @param pcType class of instance, used as key in outer map. * @param oid Object id, used as key in inner map. */ - public StateManager remove(Class pcType, Object oid); + public StateManager remove(Class pcType, Object oid); /** * Informs the cache to expect that the given pcType will be used as a key * for the outer map in subsequent putEntry operations. * @param pcType class of instance, used as key in outer map. */ - public void addPCType(Class pcType); + public void addPCType(Class pcType); /** * Removes the map for the given pcType and all its elements. * @param pcType class of instance, used as key in outer map. */ - public void removePCType(Class pcType); + public void removePCType(Class pcType); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionImpl.java index e4459129fe8..ce10a46358b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionImpl.java @@ -24,11 +24,10 @@ import com.sun.jdo.api.persistence.support.JDODataStoreException; 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.EJBHelper; import com.sun.jdo.spi.persistence.utility.Linkable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; @@ -47,6 +46,9 @@ import java.util.Properties; import java.util.concurrent.Executor; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** * This class implements the java.sql.Connection * interface, which is part of the JDBC API. You should use @@ -109,7 +111,7 @@ public class ConnectionImpl implements Connection, Linkable { /** * The logger */ - private static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(ConnectionImpl.class.getName(), RESOURCE_BUNDLE); /** @@ -118,8 +120,7 @@ public class ConnectionImpl implements Connection, Linkable { * * @param conn Connection */ - public ConnectionImpl(Connection conn, String url, String userName, - ConnectionManager connMgr) { + public ConnectionImpl(Connection conn, String url, String userName, ConnectionManager connMgr) { super(); this.connection = conn; this.url = url; @@ -142,24 +143,28 @@ public ConnectionImpl(Connection conn, String url, String userName, // @return A StatementImpl wrapper object. // @exception SQLException if a database error occurs. // + @Override public synchronized Statement createStatement() throws SQLException { this.checkXact(); return connection.createStatement(); } + @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return (null); } + @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return (null); } + @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) @@ -175,6 +180,7 @@ public CallableStatement prepareCall(String sql, // @return A StatementImpl wrapper object. // @exception SQLException if a database error occurs. // + @Override public synchronized PreparedStatement prepareStatement(String sql) throws SQLException { checkXact(); @@ -188,11 +194,13 @@ public synchronized PreparedStatement prepareStatement(String sql) // @return a ForteCallableStatement wrapper object. // @exception SQLException if a database error occurs. // + @Override public synchronized CallableStatement prepareCall(String sql) throws SQLException { return connection.prepareCall(sql); } + @Override public synchronized String nativeSQL(String sql) throws SQLException { try { return (this.connection.nativeSQL(sql)); @@ -201,6 +209,7 @@ public synchronized String nativeSQL(String sql) throws SQLException { } } + @Override public synchronized void setAutoCommit(boolean autoCommit) throws SQLException { try { @@ -210,6 +219,7 @@ public synchronized void setAutoCommit(boolean autoCommit) } } + @Override public synchronized boolean getAutoCommit() throws SQLException { try { return (this.connection.getAutoCommit()); @@ -218,6 +228,7 @@ public synchronized boolean getAutoCommit() throws SQLException { } } + @Override public synchronized void commit() throws SQLException { try { @@ -226,7 +237,7 @@ public synchronized void commit() throws SQLException { if (this.connectionManager.shutDownPending) { try { this.connection.close(); - logger.finest("sqlstore.connectionimpl.commit"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.commit"); } catch (SQLException se) { ; } @@ -244,15 +255,16 @@ public synchronized void commit() throws SQLException { } } + @Override public synchronized void rollback() throws SQLException { - logger.finest("sqlstore.connectionimpl.rollback"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.rollback"); try { this.connection.rollback(); if (this.freePending) { if (this.connectionManager.shutDownPending) { this.connection.close(); - logger.finest("sqlstore.connectionimpl.rollback.close"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.rollback.close"); } else { this.freePending = false; this.connectionManager.freeList.insertAtTail(this); @@ -267,9 +279,10 @@ public synchronized void rollback() throws SQLException { } } + @Override public synchronized void close() throws SQLException { if (EJBHelper.isManaged()) { - logger.finest("sqlstore.connectionimpl.close"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.close"); // ignore - this can happen in test 'ejb' only return; @@ -280,41 +293,29 @@ public synchronized void close() throws SQLException { private synchronized void closeInternal() throws SQLException { - boolean debug = logger.isLoggable(Logger.FINEST); - - ConnectionImpl conn = (ConnectionImpl) this; + ConnectionImpl conn = this; - if (debug) { - logger.finest("sqlstore.connectionimpl.close_arg",conn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connectionimpl.close_arg", conn); try { - conn.connectionManager.busyList.removeFromList((Linkable) conn); + conn.connectionManager.busyList.removeFromList(conn); if (conn.xactPending() == true) { conn.setFreePending(true); - if (debug) { - logger.finest("sqlstore.connectionimpl.close.freepending"); // NOI18N - } + LOG.log(TRACE, "sqlstore.connectionimpl.close.freepending"); } else if ((conn.getPooled() == true) && (conn.connectionManager.shutDownPending == false)) { - conn.connectionManager.freeList.insertAtTail((Linkable) conn); - if (debug) { - logger.finest("sqlstore.connectionimpl.close.putfreelist"); // NOI18N - } + conn.connectionManager.freeList.insertAtTail(conn); + LOG.log(TRACE, "sqlstore.connectionimpl.close.putfreelist"); } else { if (EJBHelper.isManaged()) { // RESOLVE: do we need it here? this.connection.close(); - if (debug) { - logger.finest("sqlstore.connectionimpl.close.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.connectionimpl.close.exit"); } else { // Save reference to this connection and close it only when // another free becomes available. This reduces time to // get a new connection. this.connectionManager.replaceFreeConnection(this); - if (debug) { - logger.finest("sqlstore.connectionimpl.close.replaced"); // NOI18N - } + LOG.log(TRACE, "sqlstore.connectionimpl.close.replaced"); } } @@ -333,9 +334,10 @@ protected void release() { } catch (SQLException se) { // ignore } - logger.finest("sqlstore.connectionimpl.close.connrelease"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.close.connrelease"); } + @Override public synchronized boolean isClosed() throws SQLException { try { return (this.connection.isClosed()); @@ -344,6 +346,7 @@ public synchronized boolean isClosed() throws SQLException { } } + @Override public synchronized DatabaseMetaData getMetaData() throws SQLException { try { return (this.connection.getMetaData()); @@ -352,6 +355,7 @@ public synchronized DatabaseMetaData getMetaData() throws SQLException { } } + @Override public synchronized void setReadOnly(boolean readOnly) throws SQLException { try { this.connection.setReadOnly(readOnly); @@ -360,6 +364,7 @@ public synchronized void setReadOnly(boolean readOnly) throws SQLException { } } + @Override public synchronized boolean isReadOnly() throws SQLException { try { return (this.connection.isReadOnly()); @@ -368,6 +373,7 @@ public synchronized boolean isReadOnly() throws SQLException { } } + @Override public synchronized void setCatalog(String catalog) throws SQLException { try { this.connection.setCatalog(catalog); @@ -376,6 +382,7 @@ public synchronized void setCatalog(String catalog) throws SQLException { } } + @Override public synchronized String getCatalog() throws SQLException { try { return (this.connection.getCatalog()); @@ -384,6 +391,7 @@ public synchronized String getCatalog() throws SQLException { } } + @Override public synchronized void setTransactionIsolation(int level) throws SQLException { try { @@ -393,6 +401,7 @@ public synchronized void setTransactionIsolation(int level) } } + @Override public synchronized int getTransactionIsolation() throws SQLException { try { return (this.connection.getTransactionIsolation()); @@ -401,6 +410,7 @@ public synchronized int getTransactionIsolation() throws SQLException { } } + @Override public synchronized SQLWarning getWarnings() throws SQLException { try { return (this.connection.getWarnings()); @@ -409,6 +419,7 @@ public synchronized SQLWarning getWarnings() throws SQLException { } } + @Override public synchronized void clearWarnings() throws SQLException { try { this.connection.clearWarnings(); @@ -417,6 +428,7 @@ public synchronized void clearWarnings() throws SQLException { } } + @Override public synchronized java.util.Map getTypeMap() throws SQLException { try { @@ -426,6 +438,7 @@ public synchronized java.util.Map getTypeMap() } } + @Override public synchronized void setTypeMap(java.util.Map map) throws SQLException { try { @@ -437,30 +450,35 @@ public synchronized void setTypeMap(java.util.Map map) //-------------Begin New methods added in JDBC 3.0 -------------- + @Override public synchronized void setHoldability(int holdability) throws SQLException { throw new UnsupportedOperationException(); } + @Override public synchronized int getHoldability() throws SQLException { throw new UnsupportedOperationException(); } + @Override public synchronized Savepoint setSavepoint() throws SQLException { throw new UnsupportedOperationException(); } + @Override public synchronized Savepoint setSavepoint(String name) throws SQLException { throw new UnsupportedOperationException(); } + @Override public synchronized void rollback(Savepoint savepoint) throws SQLException { @@ -468,12 +486,14 @@ public synchronized void rollback(Savepoint savepoint) } + @Override public synchronized void releaseSavepoint(Savepoint savepoint) throws SQLException { throw new UnsupportedOperationException(); } + @Override public synchronized Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) @@ -482,6 +502,7 @@ public synchronized Statement createStatement(int resultSetType, throw new UnsupportedOperationException(); } + @Override public synchronized PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, @@ -491,6 +512,7 @@ public synchronized PreparedStatement prepareStatement(String sql, throw new UnsupportedOperationException(); } + @Override public synchronized CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, @@ -500,6 +522,7 @@ public synchronized CallableStatement prepareCall(String sql, throw new UnsupportedOperationException(); } + @Override public synchronized PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { @@ -507,6 +530,7 @@ public synchronized PreparedStatement prepareStatement(String sql, throw new UnsupportedOperationException(); } + @Override public synchronized PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { @@ -514,6 +538,7 @@ public synchronized PreparedStatement prepareStatement(String sql, throw new UnsupportedOperationException(); } + @Override public synchronized PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { @@ -523,54 +548,67 @@ public synchronized PreparedStatement prepareStatement(String sql, //-------------End New methods added in JDBC 3.0 -------------- //-------------Begin New methods added in JDBC 4.0 -------------- + @Override public Clob createClob() throws SQLException { throw new UnsupportedOperationException(); } + @Override public Blob createBlob() throws SQLException { throw new UnsupportedOperationException(); } + @Override public NClob createNClob() throws SQLException { throw new UnsupportedOperationException(); } + @Override public SQLXML createSQLXML() throws SQLException { throw new UnsupportedOperationException(); } + @Override public boolean isValid(int timeout) throws SQLException { throw new UnsupportedOperationException(); } + @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { throw new UnsupportedOperationException(); } + @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { throw new UnsupportedOperationException(); } + @Override public String getClientInfo(String name) throws SQLException { throw new UnsupportedOperationException(); } + @Override public Properties getClientInfo() throws SQLException { throw new UnsupportedOperationException(); } + @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { throw new UnsupportedOperationException(); } + @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { throw new UnsupportedOperationException(); } + @Override public T unwrap(Class iface) throws SQLException { throw new UnsupportedOperationException(); } + @Override public boolean isWrapperFor(Class iface) throws SQLException { throw new UnsupportedOperationException(); } @@ -612,7 +650,7 @@ synchronized void checkXact() throws SQLException { { if (this.transaction != null) { - throw new SQLException("Thread is no longer in transaction."); // NOI18N + throw new SQLException("Thread is no longer in transaction."); } else { @@ -642,7 +680,7 @@ else if (this.transaction == null) } else if (!tran.equals(this.transaction)) { - throw new SQLException("Wrong Transaction."); // NOI18N + throw new SQLException("Wrong Transaction."); } else { @@ -684,6 +722,7 @@ synchronized boolean xactPending() { *

* @return The previous ConnectionImpl in a chain. */ + @Override public Linkable getPrevious() { return (this.previous); } @@ -693,6 +732,7 @@ public Linkable getPrevious() { *

* @param conn The ConnectionImpl to hook on the chain. */ + @Override public void setPrevious(Linkable conn) { this.previous = conn; } @@ -702,6 +742,7 @@ public void setPrevious(Linkable conn) { *

* @return The next ConnectionImpl in a chain. */ + @Override public Linkable getNext() { return (this.next); } @@ -711,6 +752,7 @@ public Linkable getNext() { *

* @param conn The ConnectionImpl to hook on the chain. */ + @Override public void setNext(Linkable conn) { this.next = conn; } @@ -759,7 +801,7 @@ synchronized String getUserName() { *

*/ public synchronized void internalCommit() { - logger.finest("sqlstore.connectionimpl.internalcommit"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.internalcommit"); try { this.connection.commit(); @@ -785,7 +827,7 @@ public synchronized void internalCommit() { *

*/ public synchronized void internalRollback() { - logger.finest("sqlstore.connectionimpl.internalrollback"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.internalrollback"); try { this.connection.rollback(); } catch (Exception e1) { @@ -802,25 +844,25 @@ public synchronized void internalRollback() { *

*/ private void clearXact() { - logger.finest("sqlstore.connectionimpl.clearxact"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.clearxact"); try { if (this.freePending) { this.freePending = false; if (this.pooled) { this.connectionManager.disassociateXact(this.transaction, this, true); - logger.finest("sqlstore.connectionimpl.pendingdisassocxact"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.pendingdisassocxact"); } else { this.connectionManager.disassociateXact(this.transaction, this, false); // Make sure the last things done are the only things // that can throw exceptions. this.connection.close(); - logger.finest("sqlstore.connectionimpl.clearxact.close"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.clearxact.close"); } } else { this.connectionManager.disassociateXact(this.transaction, this, false); - logger.finest("sqlstore.connectionimpl.clearxact.disassocxact"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.clearxact.disassocxact"); } this.connection.setAutoCommit(true); } catch (SQLException ex) { @@ -837,12 +879,13 @@ private void clearXact() { * @return String describing contents of this ConnectionImpl * object. */ + @Override public synchronized String toString() { int xactIsolation = 0; - String buffer = "Connect@"; // NOI18N + String buffer = "Connect@"; String strTran = (this.transaction == null) ? - " NULL" : this.transaction.toString(); // NOI18N + " NULL" : this.transaction.toString(); int hash = this.hashCode(); try { @@ -851,40 +894,46 @@ public synchronized String toString() { xactIsolation = -1; } - buffer = buffer + hash + "\n" + // NOI18N - " pooled = " + this.pooled + "\n" + // NOI18N - " freePending = " + this.freePending + "\n" + // NOI18N - " xactIsolation = " + xactIsolation + "\n" + // NOI18N - " Tran = " + strTran + "\n"; // NOI18N + buffer = buffer + hash + "\n" + + " pooled = " + this.pooled + "\n" + + " freePending = " + this.freePending + "\n" + + " xactIsolation = " + xactIsolation + "\n" + + " Tran = " + strTran + "\n"; return buffer; } + @Override protected void finalize() { try { this.connection.close(); - logger.finest("sqlstore.connectionimpl.finalize"); // NOI18N + LOG.log(TRACE, "sqlstore.connectionimpl.finalize"); } catch (SQLException se) { ; } } + @Override public void setSchema(String schema) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } + @Override public String getSchema() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } + @Override public void abort(Executor executor) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } + @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } + @Override public int getNetworkTimeout() throws SQLException { throw new UnsupportedOperationException("Not supported yet."); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionManager.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionManager.java index d39ea5ce511..329d22779f5 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionManager.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/connection/ConnectionManager.java @@ -23,12 +23,10 @@ package com.sun.jdo.spi.persistence.support.sqlstore.connection; 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.utility.StringScanner; import com.sun.jdo.spi.persistence.utility.DoubleLinkedList; -import com.sun.jdo.spi.persistence.utility.Linkable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; @@ -37,6 +35,9 @@ import org.glassfish.persistence.common.I18NHelper; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** *

This class represents a connection manager, which creates a * JDBC driver manager and manages @@ -117,14 +118,14 @@ * You can also specify a user name, password, and database URL on the * getConnection method. * - *

Example of Using ConnectionManager without Pooling
- *
+ * 
Example of Using ConnectionManager without Pooling
+ *
{@code
  * import java.sql.*;
  * import com.sun.jdo.api.persistence.support.*;
  * Connection con = myTransaction.getConnection();
  * Statement stmt = con.createStatement();
  * ResultSet rs = stmt.executeQuery("SELECT * FROM T1");
- * 
+ * }
* *

Using a Pool of Database Connections (Application-based Security)

*

When you create a connection manager using the @@ -174,7 +175,7 @@ * connections on a request-by-request basis. * *

Example of Using ConnectionManager with Pooling
- *
+ * 
{@code
  * import com.sun.jdo.api.persistence.support.*;
  * void getT1Data() {
  *     // The following connection is from the connection pool.
@@ -196,7 +197,7 @@
  *     .
  *     .
  * }
- * 
+ * }
*/ public class ConnectionManager { /** @@ -288,7 +289,7 @@ public class ConnectionManager { * transaction object (jakarta.transaction.Transaction). * @serial */ - private transient Hashtable xactConnections; + private transient Hashtable xactConnections; /** * Flag that a shutdown to this ConnectionManager object is pending. @@ -343,13 +344,13 @@ public class ConnectionManager { /** * The logger */ - private static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(ConnectionManager.class.getName(), RESOURCE_BUNDLE); /** * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", ConnectionManager.class.getClassLoader()); @@ -360,411 +361,411 @@ public class ConnectionManager { // // SQL92 "00000" Successful completion. // - static final String SQL_SUCCESS = "00000"; // NOI18N + static final String SQL_SUCCESS = "00000"; // // SQL92 "01000" Warning. // - static final String SQL_WARNING = "01000"; // NOI18N + static final String SQL_WARNING = "01000"; // // SQL92 "01001" Warning; cursor operation conflict. // - static final String SQL_CURSOR_OP = "01001"; // NOI18N + static final String SQL_CURSOR_OP = "01001"; // // SQL92 "01002" Warning; disconnect error. // - static final String SQL_DISCONNECT = "01002"; // NOI18N + static final String SQL_DISCONNECT = "01002"; // // SQL92 "01003" Warning; null value eliminated in set function. // - static final String SQL_NULL_ELIM = "01003"; // NOI18N + static final String SQL_NULL_ELIM = "01003"; // // SQL92 "01004" Warning; string date, right truncation. // - static final String SQL_R_TRUNC = "01004"; // NOI18N + static final String SQL_R_TRUNC = "01004"; // // SQL92 "01005" Warning; insufficient item descriptor areas. // - static final String SQL_INSUFF_ITEM = "01005"; // NOI18N + static final String SQL_INSUFF_ITEM = "01005"; // // SQL92 "01006" Warning; privilege not revoked. // - static final String SQL_NOT_REVOKED = "01006"; // NOI18N + static final String SQL_NOT_REVOKED = "01006"; // // SQL92 "01007" Warning; privilege not granted. // - static final String SQL_NOT_GRANTED = "01007"; // NOI18N + static final String SQL_NOT_GRANTED = "01007"; // // SQL92 "01008" Warning; implicit zero-bit padding. // - static final String SQL_ZERO_BIT_PAD = "01008"; // NOI18N + static final String SQL_ZERO_BIT_PAD = "01008"; // // SQL92 "01009" Warning; search condition too long for // information schema. // - static final String SQL_COND_TOO_LONG = "01009"; // NOI18N + static final String SQL_COND_TOO_LONG = "01009"; // // SQL92 "0100A" Warning; query condition too long for // information schema. // - static final String SQL_QUERY_TOO_LONG = "0100A"; // NOI18N + static final String SQL_QUERY_TOO_LONG = "0100A"; // // SQL92 "02000" No data. // - static final String SQL_NO_DATA = "02000"; // NOI18N + static final String SQL_NO_DATA = "02000"; // // SQL92 "07000" Dynamic SQL error. // - static final String SQL_DYN_ERROR = "07000"; // NOI18N + static final String SQL_DYN_ERROR = "07000"; // // SQL92 "07001" Dynamic SQL error; using clause does not // match dynamic parameter specifications. // - static final String SQL_USING_NO_PARAM = "07001"; // NOI18N + static final String SQL_USING_NO_PARAM = "07001"; // // SQL92 "07002" Dynamic SQL error; using clause does not // match target specifications. // - static final String SQL_USING_NO_TARGET = "07002"; // NOI18N + static final String SQL_USING_NO_TARGET = "07002"; // // SQL92 "07003" Dynamic SQL error; cursor specification // cannot be executed. // - static final String SQL_CURSOR_NOEXE = "07003"; // NOI18N + static final String SQL_CURSOR_NOEXE = "07003"; // // SQL92 "07004" Dynamic SQL error; using clause // required for dynamic parameters. // - static final String SQL_USING_REQ = "07004"; // NOI18N + static final String SQL_USING_REQ = "07004"; // // SQL92 "07005" Dynamic SQL error; prepared statement // not a cursor specification. // - static final String SQL_PREP_NO_CURSOR = "07005"; // NOI18N + static final String SQL_PREP_NO_CURSOR = "07005"; // // SQL92 "07006" Dynamic SQL error; restricted datatype // attribute violation. // - static final String SQL_RESTRIC_ATTR = "07006"; // NOI18N + static final String SQL_RESTRIC_ATTR = "07006"; // // SQL92 "07007" Dynamic SQL error; using caluse required // for result fields. // - static final String SQL_USING_RESULTS = "07007"; // NOI18N + static final String SQL_USING_RESULTS = "07007"; // // SQL92 "07008" Dynamic SQL error; invalid descriptor count. // - static final String SQL_INVAL_DESC_CNT = "07008"; // NOI18N + static final String SQL_INVAL_DESC_CNT = "07008"; // // SQL92 "07009" Dynamic SQL error; invalid descriptor index. // - static final String SQL_INVAL_DESC_IDX = "07009"; // NOI18N + static final String SQL_INVAL_DESC_IDX = "07009"; // // SQL92 "08000" Connection exception. // - static final String SQL_CONN = "08000"; // NOI18N + static final String SQL_CONN = "08000"; // // SQL92 "08001" Connection exception; SQL-client unable // to establish SQL-connection. // - static final String SQL_CLIENT_NO_CONN = "08001"; // NOI18N + static final String SQL_CLIENT_NO_CONN = "08001"; // // SQL92 "08002" Connection exception; connection name // in use. // - static final String SQL_CONN_IN_USE = "08002"; // NOI18N + static final String SQL_CONN_IN_USE = "08002"; // // SQL92 "08003" Connection exception; connection does not exist. // - static final String SQL_NO_CONN = "08003"; // NOI18N + static final String SQL_NO_CONN = "08003"; // // SQL92 "08004" Connection exception; SQL-server rejected // establishment of SQL-connection. // - static final String SQL_REJECT_CONN = "08004"; // NOI18N + static final String SQL_REJECT_CONN = "08004"; // // SQL92 "08006" Connection exception; connection failure. // - static final String SQL_CONN_FAIL = "08006"; // NOI18N + static final String SQL_CONN_FAIL = "08006"; // // SQL92 "08007" Connection exception; transaction resolution unknown. // - static final String SQL_TRANS_UNK = "08007"; // NOI18N + static final String SQL_TRANS_UNK = "08007"; // // SQL92 "0A000" Feature not supported. // - static final String SQL_NO_SUPPORT = "0A000"; // NOI18N + static final String SQL_NO_SUPPORT = "0A000"; // // SQL92 "0A001" Feature not supported; multiple // server transactions // - static final String SQL_NO_SUPPORT_MULTI = "0A001"; // NOI18N + static final String SQL_NO_SUPPORT_MULTI = "0A001"; // // SQL92 "21000" Cardinality violation. // - static final String SQL_INVALID_VALUE = "21000"; // NOI18N + static final String SQL_INVALID_VALUE = "21000"; // // SQL92 "22000" Data exception. // - static final String SQL_DATA = "22000"; // NOI18N + static final String SQL_DATA = "22000"; // // SQL92 "22001" Data exception; string data, // right trunctation. // - static final String SQL_DATA_RTRUNC = "22001"; // NOI18N + static final String SQL_DATA_RTRUNC = "22001"; // // SQL92 "22002" Data exception; null value, no // indicator parameter. // - static final String SQL_DATA_NULL = "22002"; // NOI18N + static final String SQL_DATA_NULL = "22002"; // // SQL92 "22003" Data exception; numeric value out // of range. // - static final String SQL_OUT_OF_RANGE = "22003"; // NOI18N + static final String SQL_OUT_OF_RANGE = "22003"; // // SQL92 "22005" Data exception; error in assignment. // - static final String SQL_DATA_EXCEPT = "22005"; // NOI18N + static final String SQL_DATA_EXCEPT = "22005"; // // SQL92 "22007" Data exception; invalid datetime format. // - static final String SQL_DATETIME_FMT = "22007"; // NOI18N + static final String SQL_DATETIME_FMT = "22007"; // // SQL92 "22008" Data exception; datetime field overflow. // - static final String SQL_DATETIME_OVFLO = "22008"; // NOI18N + static final String SQL_DATETIME_OVFLO = "22008"; // // SQL92 "22009" Data exception; invalid time zone // displacement value. // - static final String SQL_TIMEZONE = "22009"; // NOI18N + static final String SQL_TIMEZONE = "22009"; // // SQL92 "22011" Data exception; substring error. // - static final String SQL_SUBSTR_ERROR = "22011"; // NOI18N + static final String SQL_SUBSTR_ERROR = "22011"; // // SQL92 "22012" Data exception; division by zero. // - static final String SQL_DIV_BY_ZERO = "22012"; // NOI18N + static final String SQL_DIV_BY_ZERO = "22012"; // // SQL92 "22015" Data exception; interval field overflow. // - static final String SQL_INTERVAL_OVFLO = "22015"; // NOI18N + static final String SQL_INTERVAL_OVFLO = "22015"; // // SQL92 "22018" Data exception; invalid character value // for cast. // - static final String SQL_INVAL_CHAR_CAST = "22018"; // NOI18N + static final String SQL_INVAL_CHAR_CAST = "22018"; // // SQL92 "22019" Data exception; invalid escape character. // - static final String SQL_INVAL_ESCAPE_CHAR = "22019"; // NOI18N + static final String SQL_INVAL_ESCAPE_CHAR = "22019"; // // SQL92 "22021" Data exception; character not in repertoire. // - static final String SQL_CHAR_NOT_REP = "22021"; // NOI18N + static final String SQL_CHAR_NOT_REP = "22021"; // // SQL92 "22022" Data exception; indicator overflow. // - static final String SQL_IND_OVERFLOW = "22022"; // NOI18N + static final String SQL_IND_OVERFLOW = "22022"; // // SQL92 "22023" Data exception; invalid parameter value. // - static final String SQL_INVAL_PARAM_VALUE = "22023"; // NOI18N + static final String SQL_INVAL_PARAM_VALUE = "22023"; // // SQL92 "22024" Data exception; unterminated C string. // - static final String SQL_UNTERM_C_STR = "22024"; // NOI18N + static final String SQL_UNTERM_C_STR = "22024"; // // SQL92 "22025" Data exception; invalid escape sequence. // - static final String SQL_INVAL_ESCAPE_SEQ = "22025"; // NOI18N + static final String SQL_INVAL_ESCAPE_SEQ = "22025"; // // SQL92 "22026" Data exception; string data, length mismatch. // - static final String SQL_STR_LEN_MISMATCH = "22026"; // NOI18N + static final String SQL_STR_LEN_MISMATCH = "22026"; // // SQL92 "22027" Data exception; trim error. // - static final String SQL_TRIM_ERROR = "22027"; // NOI18N + static final String SQL_TRIM_ERROR = "22027"; // // SQL92 "23000" Integrity constraint violation. // - static final String SQL_INTEG_CONSTRAINT = "23000"; // NOI18N + static final String SQL_INTEG_CONSTRAINT = "23000"; // // SQL92 "24000" Invalid cursor state. // - static final String SQL_INVAL_CURSOR_STATE = "24000"; // NOI18N + static final String SQL_INVAL_CURSOR_STATE = "24000"; // // SQL92 "25000" Invalid transaction state // - static final String SQL_INVAL_TRANS_STATE = "25000"; // NOI18N + static final String SQL_INVAL_TRANS_STATE = "25000"; // // SQL92 "26000" Invalid SQL statement name. // - static final String SQL_INVAL_SQL_NAME = "26000"; // NOI18N + static final String SQL_INVAL_SQL_NAME = "26000"; // // SQL92 "28000" Invalid authorization specification. // - static final String SQL_INVAL_AUTH = "28000"; // NOI18N + static final String SQL_INVAL_AUTH = "28000"; // // SQL92 "2A000" Syntax error or access rule violation // in direct SQL statement. // - static final String SQL_SYNTAX_DIRECT = "2A000"; // NOI18N + static final String SQL_SYNTAX_DIRECT = "2A000"; // // SQL92 "2B000" Dependent privilege descriptors // still exist. // - static final String SQL_DESC_EXIST = "2B000"; // NOI18N + static final String SQL_DESC_EXIST = "2B000"; // // SQL92 "2C000" Invalid character set name. // - static final String SQL_INVAL_CHAR_SET = "2C000"; // NOI18N + static final String SQL_INVAL_CHAR_SET = "2C000"; // // SQL92 "2D000" Invalid transaction termination. // - static final String SQL_INVAL_TRANS_TERM = "2D000"; // NOI18N + static final String SQL_INVAL_TRANS_TERM = "2D000"; // // SQL92 "2E000" Invalid connection name. // - static final String SQL_INVAL_CONN_NAME = "2E000"; // NOI18N + static final String SQL_INVAL_CONN_NAME = "2E000"; // // SQL92 "33000" Invalid SQL descriptor name // - static final String SQL_INVAL_SQL_DESC_NAME = "33000"; // NOI18N + static final String SQL_INVAL_SQL_DESC_NAME = "33000"; // // SQL92 "34000" Invalid cursor name. // - static final String SQL_INVAL_CURSOR_NAME = "34000"; // NOI18N + static final String SQL_INVAL_CURSOR_NAME = "34000"; // // SQL92 "35000" Invalid condition number // - static final String SQL_INVAL_COND_NUM = "35000"; // NOI18N + static final String SQL_INVAL_COND_NUM = "35000"; // // SQL92 "37000" Syntax error or access rule violation // in dynamic SQL statement. // - static final String SQL_SYNTAX_DYNAMIC = "37000"; // NOI18N + static final String SQL_SYNTAX_DYNAMIC = "37000"; // // SQL92 "3C000" Ambiguous cursor name. // - static final String SQL_AMBIG_CURSOR = "3C000"; // NOI18N + static final String SQL_AMBIG_CURSOR = "3C000"; // // SQL92 "3D000" Invalid catalog name. // - static final String SQL_INVAL_CATALOG = "3D000"; // NOI18N + static final String SQL_INVAL_CATALOG = "3D000"; // // SQL92 "3F000" Invalid schema name. // - static final String SQL_INVAL_SCHEMA_NAME = "3F000"; // NOI18N + static final String SQL_INVAL_SCHEMA_NAME = "3F000"; // // SQL92 "40000" Transaction rollback. // - static final String SQL_TRANS_ROLLBACK = "40000"; // NOI18N + static final String SQL_TRANS_ROLLBACK = "40000"; // // SQL92 "40001" Transaction rollback; serialization // failure. // - static final String SQL_TRANS_SERIAL_FAIL = "40001"; // NOI18N + static final String SQL_TRANS_SERIAL_FAIL = "40001"; // // SQL92 "40002" Transaction rollback; integrity // constraint violation. // - static final String SQL_TRANS_INTEG = "40002"; // NOI18N + static final String SQL_TRANS_INTEG = "40002"; // // SQL92 "40003" Transaction rollback; statement // completion unknown. // - static final String SQL_TRANS_COMP_UNK = "40003"; // NOI18N + static final String SQL_TRANS_COMP_UNK = "40003"; // // SQL92 "42000" Syntax error or access rule violation. // - static final String SQL_SYNTAX = "42000"; // NOI18N + static final String SQL_SYNTAX = "42000"; // // SQL92 "44000" With check option violation. // - static final String SQL_CHECK_OPT = "44000"; // NOI18N + static final String SQL_CHECK_OPT = "44000"; // // SQL92 "HZ " Remote Database Access. // - static final String SQL_RMT_DB_ACCESS = "HZ "; // NOI18N + static final String SQL_RMT_DB_ACCESS = "HZ "; /** @@ -1097,7 +1098,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N + "connection.connectionmanager.isdown") ), SQL_NO_CONN ); @@ -1133,7 +1134,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.maxpool") // NOI18N + "connection.connectionmanager.maxpool") ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1155,7 +1156,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.badvalue") // NOI18N + "connection.connectionmanager.badvalue") ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1163,10 +1164,10 @@ public synchronized Connection getConnection() throws SQLException { } conn.setPooled(true); conn.checkXact(); - this.busyList.insertAtTail((Linkable) conn); + this.busyList.insertAtTail(conn); } conn.setFreePending(false); - return ((Connection) conn); + return (conn); } /** @@ -1183,8 +1184,6 @@ public synchronized Connection getConnection() throws SQLException { String userName, char[] password ) throws SQLException { - boolean debug = logger.isLoggable(Logger.FINEST); - if (this.shutDownPending == true) { SQLException se = new SQLException @@ -1192,7 +1191,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N + "connection.connectionmanager.isdown") ), SQL_CONN_FAIL ); @@ -1204,9 +1203,7 @@ public synchronized Connection getConnection() throws SQLException { if (conn == null) { if (freeConn != null) { // We have one available - use it - if (debug) { - logger.finest("sqlstore.connection.conncectiomgr.found",freeConn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connection.conncectiomgr.found",freeConn); conn = freeConn; freeConn = null; } else { @@ -1225,9 +1222,7 @@ public synchronized Connection getConnection() throws SQLException { this.expandAttribute(userName), this ); - if (debug) { - logger.finest("sqlstore.connection.conncectiomgr.getnewconn",conn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connection.conncectiomgr.getnewconn",conn); } catch (SQLException se) { throw se; } @@ -1240,7 +1235,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.getconnection.mismatch") // NOI18N + "connection.connectionmanager.getconnection.mismatch") ), SQL_NO_CONN // 08003 ); @@ -1249,8 +1244,8 @@ public synchronized Connection getConnection() throws SQLException { } conn.setFreePending(false); conn.setPooled(false); - this.busyList.insertAtTail((Linkable) conn); - return ((Connection) conn); + this.busyList.insertAtTail(conn); + return (conn); } /** @@ -1269,7 +1264,6 @@ public synchronized Connection getConnection() throws SQLException { String userName, String password ) throws SQLException { - boolean debug = logger.isLoggable(Logger.FINEST); if (this.shutDownPending == true) { SQLException se = new SQLException @@ -1277,7 +1271,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N + "connection.connectionmanager.isdown") ), SQL_CONN_FAIL ); @@ -1289,9 +1283,7 @@ public synchronized Connection getConnection() throws SQLException { if (conn == null) { if (freeConn != null) { // We have one available - use it - if (debug) { - logger.finest("sqlstore.connection.conncectiomgr.found",freeConn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connection.conncectiomgr.found",freeConn); conn = freeConn; freeConn = null; } else { @@ -1310,9 +1302,7 @@ public synchronized Connection getConnection() throws SQLException { this.expandAttribute(userName), this ); - if (debug) { - logger.finest("sqlstore.connection.conncectiomgr.getnewconn",conn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connection.conncectiomgr.getnewconn",conn); } catch (SQLException se) { throw se; } @@ -1326,7 +1316,7 @@ public synchronized Connection getConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.getconnection.mismatch") // NOI18N + "connection.connectionmanager.getconnection.mismatch") ), SQL_NO_CONN // 08003 ); @@ -1335,8 +1325,8 @@ public synchronized Connection getConnection() throws SQLException { } conn.setFreePending(false); conn.setPooled(false); - this.busyList.insertAtTail((Linkable) conn); - return ((Connection) conn); + this.busyList.insertAtTail(conn); + return (conn); } /** @@ -1347,25 +1337,7 @@ public synchronized Connection getConnection() throws SQLException { * the current thread; null otherwise. */ private synchronized ConnectionImpl checkXact() { - Transaction tran = null; - - /* RESOLVE: Need to reimplement this??? - try - { - // Is this ForteJDBCConnet participating in a transaction? - tran = ThreadContext.transactionContext().getTransaction(); - } - catch (SystemException ex) - { - // There is no transaction. - return null; - } - */ - - // Return Connection associated with this transaction - maybe null? - if (tran == null) - return null; - return (ConnectionImpl) this.xactConnections.get(tran); + return null; } /** @@ -1379,10 +1351,12 @@ private synchronized ConnectionImpl checkXact() { * @exception SQLException if a SQL error is encountered. */ public void startUp() throws ClassNotFoundException, SQLException { - if (this.initialized == true) return; + if (this.initialized == true) { + return; + } this.busyList = new DoubleLinkedList(); - this.xactConnections = new Hashtable(); + this.xactConnections = new Hashtable<>(); this.expandedDriverName = this.expandAttribute(this.driverName); if (this.expandedDriverName == null) { SQLException se = new SQLException @@ -1390,7 +1364,7 @@ public void startUp() throws ClassNotFoundException, SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.nulldriver") // NOI18N + "connection.connectionmanager.nulldriver") ), SQL_INVALID_VALUE // 21000 ); @@ -1403,7 +1377,7 @@ public void startUp() throws ClassNotFoundException, SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.nullurl") // NOI18N + "connection.connectionmanager.nullurl") ), SQL_INVALID_VALUE // 21000 ); @@ -1411,11 +1385,11 @@ public void startUp() throws ClassNotFoundException, SQLException { } this.expandedUserName = this.expandAttribute(this.userName); if (this.expandedUserName == null) { - this.expandedUserName = ""; // Allow null username. // NOI18N + this.expandedUserName = ""; // Allow null username. } this.expandedPassword = this.expandAttribute(new String(this.password)); if (this.expandedPassword == null) { - this.expandedPassword = ""; // Allow null password. // NOI18N + this.expandedPassword = ""; // Allow null password. } try { Class.forName(this.expandedDriverName); @@ -1486,6 +1460,7 @@ public synchronized void shutDown() throws SQLException { * or rolledback. * */ + @Override protected void finalize() { try { shutDown(); @@ -1519,7 +1494,7 @@ public synchronized void setDriverName(String driverName) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.nulldriver") // NOI18N + "connection.connectionmanager.nulldriver") ), SQL_INVALID_VALUE // 21000 ); @@ -1560,7 +1535,7 @@ public synchronized void setURL(String url) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.nullurl") // NOI18N + "connection.connectionmanager.nullurl") ), SQL_INVALID_VALUE // 21000 ); @@ -1663,7 +1638,7 @@ public synchronized void setMinPool(int minPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N + "connection.connectionmanager.isdown") ), SQL_CONN_FAIL // 08006 ); @@ -1676,7 +1651,7 @@ public synchronized void setMinPool(int minPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.zero") // NOI18N + "connection.connectionmanager.zero") ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1688,7 +1663,7 @@ public synchronized void setMinPool(int minPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.badnew"), // NOI18N + "connection.connectionmanager.badnew"), Integer.toString(minPool), Integer.toString(minPool) ), @@ -1703,7 +1678,7 @@ public synchronized void setMinPool(int minPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.poolsize") // NOI18N + "connection.connectionmanager.poolsize") ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1760,7 +1735,7 @@ public synchronized void setMaxPool(int maxPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N + "connection.connectionmanager.isdown") ), SQL_CONN_FAIL // 08006 ); @@ -1772,7 +1747,7 @@ public synchronized void setMaxPool(int maxPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.zero"), // NOI18N + "connection.connectionmanager.zero"), Integer.toString(maxPool) ), SQL_INVAL_PARAM_VALUE // 22023 @@ -1786,7 +1761,7 @@ public synchronized void setMaxPool(int maxPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.badnew"), // NOI18N + "connection.connectionmanager.badnew"), Integer.toString(maxPool), Integer.toString(maxPool) ), @@ -1802,7 +1777,7 @@ public synchronized void setMaxPool(int maxPool) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.poolsize") // NOI18N + "connection.connectionmanager.poolsize") ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1863,7 +1838,7 @@ public synchronized void setMsWait(int msWait) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.badvalue"), // NOI18N + "connection.connectionmanager.badvalue"), Integer.toString(msWait) ), SQL_INVAL_PARAM_VALUE // 22023 @@ -1928,9 +1903,9 @@ public synchronized void setMsInterval(int msInterval) throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.badnew"), // NOI18N - "MsInterval", // NOI18N - "MsWait" // NOI18N + "connection.connectionmanager.badnew"), + "MsInterval", + "MsWait" ), SQL_INVAL_PARAM_VALUE // 22023 ); @@ -1946,6 +1921,7 @@ public synchronized void setMsInterval(int msInterval) throws SQLException { * @return A String decribing the contents of the current * ConnectionManager object. */ + @Override public synchronized String toString() { /* TraceLogger lgr = ThreadContext.lgr(); @@ -1957,43 +1933,43 @@ public synchronized String toString() { SPLogFlags.CFG_DIFFABLE_EXCEPTS, 1 ); - String buf = "ConnectManager@\n"; // NOI18N + String buf = "ConnectManager@\n"; if (dif == false) { - buf = buf + " busyList = " + this.busyList + "\n"; // NOI18N + buf = buf + " busyList = " + this.busyList + "\n"; } if (this.busyList != null) { - buf = buf + " busyList Object = " + this.busyList.toString(); // NOI18N + buf = buf + " busyList Object = " + this.busyList.toString(); } - buf = buf + " connectionBlocking = " + this.connectionBlocking + "\n"; // NOI18N - buf = buf + " driverName = " + this.driverName + "\n"; // NOI18N + buf = buf + " connectionBlocking = " + this.connectionBlocking + "\n"; + buf = buf + " driverName = " + this.driverName + "\n"; if (dif == false) { - buf = buf + " expandedDriverName = " + this.expandedDriverName + "\n"; // NOI18N - buf = buf + " expandedPassword = " + this.expandedPassword + "\n"; // NOI18N - buf = buf + " expandedUrl = " + this.expandedUrl + "\n"; // NOI18N - buf = buf + " expandedUserName = " + this.expandedUserName + "\n"; // NOI18N - buf = buf + " freeList = " + this.freeList + "\n"; // NOI18N + buf = buf + " expandedDriverName = " + this.expandedDriverName + "\n"; + buf = buf + " expandedPassword = " + this.expandedPassword + "\n"; + buf = buf + " expandedUrl = " + this.expandedUrl + "\n"; + buf = buf + " expandedUserName = " + this.expandedUserName + "\n"; + buf = buf + " freeList = " + this.freeList + "\n"; } if (this.freeList != null) { - buf = buf + " freeList Object = " + this.freeList.toString(); // NOI18N + buf = buf + " freeList Object = " + this.freeList.toString(); } if (dif == false) { - buf = buf + " hashCode = " + this.hashCode() + "\n"; // NOI18N + buf = buf + " hashCode = " + this.hashCode() + "\n"; } - buf = buf + " maxPool = " + this.maxPool + "\n"; // NOI18N - buf = buf + " minPool = " + this.minPool + "\n"; // NOI18N - buf = buf + " msInterval = " + this.msInterval + "\n"; // NOI18N - buf = buf + " msWait = " + this.msWait + "\n"; // NOI18N - buf = buf + " password = " + this.password + "\n"; // NOI18N - buf = buf + " pooling = " + this.pooling + "\n"; // NOI18N - buf = buf + " poolSize = " + this.poolSize + "\n"; // NOI18N - buf = buf + " shutDownPending = " + this.shutDownPending + "\n"; // NOI18N - buf = buf + " url = " + this.url + "\n"; // NOI18N - buf = buf + " userName = " + this.userName + "\n"; // NOI18N + buf = buf + " maxPool = " + this.maxPool + "\n"; + buf = buf + " minPool = " + this.minPool + "\n"; + buf = buf + " msInterval = " + this.msInterval + "\n"; + buf = buf + " msWait = " + this.msWait + "\n"; + buf = buf + " password = " + this.password + "\n"; + buf = buf + " pooling = " + this.pooling + "\n"; + buf = buf + " poolSize = " + this.poolSize + "\n"; + buf = buf + " shutDownPending = " + this.shutDownPending + "\n"; + buf = buf + " url = " + this.url + "\n"; + buf = buf + " userName = " + this.userName + "\n"; return buf; */ @@ -2010,8 +1986,9 @@ public synchronized String toString() { * @param conn The Connection. */ synchronized void associateXact(Transaction tran, ConnectionImpl conn) { - if (tran != null) - this.xactConnections.put((Object) tran, (Object) conn); + if (tran != null) { + this.xactConnections.put(tran, conn); + } } /** @@ -2030,13 +2007,14 @@ synchronized void associateXact(Transaction tran, ConnectionImpl conn) { ) throws SQLException { ConnectionImpl xactConn = null; - if (tran != null) - xactConn = (ConnectionImpl) this.xactConnections.remove((Object) tran); + if (tran != null) { + xactConn = this.xactConnections.remove(tran); + } - if (tran == null || xactConn.equals((Object) conn)) { + if (tran == null || xactConn.equals(conn)) { if (free == true) { if (conn.connectionManager.shutDownPending == false) { - this.freeList.insertAtTail((Linkable) conn); + this.freeList.insertAtTail(conn); } else { conn.close(); } @@ -2047,7 +2025,7 @@ synchronized void associateXact(Transaction tran, ConnectionImpl conn) { StringScanner.createParamString ( //MsgCat.getStr(DbmsMsgCat.DB_ERR_XACT_MISMATCH) - "Internal Error: transaction mismatch" // NOI18N + "Internal Error: transaction mismatch" ), SQL_TRANS_UNK // 08007 ); @@ -2063,55 +2041,30 @@ synchronized void associateXact(Transaction tran, ConnectionImpl conn) { * @ForteInternal */ private synchronized void expandPool(int connections) throws SQLException { - ConnectionImpl conn = null; if (this.shutDownPending == true) { - SQLException se = new SQLException - ( - StringScanner.createParamString - ( - I18NHelper.getMessage(messages, - "connection.connectionmanager.isdown") // NOI18N - ), - SQL_CONN_FAIL - ); + SQLException se = new SQLException( + StringScanner.createParamString(I18NHelper.getMessage(messages, "connection.connectionmanager.isdown")), + SQL_CONN_FAIL); throw se; } for (int i = 0; i < connections; i++) { if (this.poolSize >= this.maxPool) { // There is no room for a new connection. - SQLException se = new SQLException - ( - StringScanner.createParamString - ( - I18NHelper.getMessage(messages, - "connection.connectionmanager.maxpool") // NOI18N - ), - SQL_CONN_FAIL - ); + SQLException se = new SQLException(StringScanner.createParamString( + I18NHelper.getMessage(messages, "connection.connectionmanager.maxpool")), SQL_CONN_FAIL); throw se; - } else // There is room in the pool, so get a new connection. - { - try { - conn = new ConnectionImpl - ( - DriverManager.getConnection - ( - this.expandedUrl, - this.expandedUserName, - this.expandedPassword - ), - this.expandedUrl, - this.expandedUserName, - this - ); - conn.setPooled(true); - this.freeList.insertAtTail((Linkable) conn); - this.poolSize++; - } catch (SQLException e) { - throw e; - } + } + try { + ConnectionImpl conn = new ConnectionImpl( + DriverManager.getConnection(this.expandedUrl, this.expandedUserName, this.expandedPassword), + this.expandedUrl, this.expandedUserName, this); + conn.setPooled(true); + this.freeList.insertAtTail(conn); + this.poolSize++; + } catch (SQLException e) { + throw e; } } } @@ -2125,32 +2078,7 @@ private synchronized void expandPool(int connections) throws SQLException { * @exceptions SQLException We should come up with a better one. */ private String expandAttribute(String envname) throws SQLException { - String attribute = null; - /*RESOLVE: - try - { - attribute = ForteProperties.expandVars(envname); - } - catch (EnvVariableException e) - { - SQLException se = new SQLException - ( - StringScanner.createParamString - ( - I18NHelper.getMessage(messages, - "connection.connectionmanager.badvalue"), // NOI18N - envname - ), - SQL_INVAL_PARAM_VALUE - ); - throw se; - } - */ - if (attribute != null) { - return attribute; - } else { - return envname; - } + return envname; } /** @@ -2191,7 +2119,7 @@ private synchronized void waitForConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.conntimeout") // NOI18N + "connection.connectionmanager.conntimeout") ), SQL_CONN_FAIL ); @@ -2206,7 +2134,7 @@ private synchronized void waitForConnection() throws SQLException { StringScanner.createParamString ( I18NHelper.getMessage(messages, - "connection.connectionmanager.threaditerupted") // NOI18N + "connection.connectionmanager.threaditerupted") ), SQL_CONN_FAIL ); @@ -2235,11 +2163,7 @@ public int getLoginTimeout() * Previous free connection can be released (closed) when a new one becomes available. */ protected synchronized void replaceFreeConnection(ConnectionImpl c) { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - logger.finest("sqlstore.connection.conncectiomgr.replacefreeconn",freeConn); // NOI18N - } + LOG.log(TRACE, "sqlstore.connection.conncectiomgr.replacefreeconn",freeConn); if (freeConn != null) { // Release (close) the old connection. freeConn.release(); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/DBVendorType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/DBVendorType.java index 4d341f1eb36..39c46b95a67 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/DBVendorType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/DBVendorType.java @@ -21,11 +21,10 @@ import com.sun.jdo.api.persistence.support.JDOFatalUserException; import com.sun.jdo.api.persistence.support.JDOUserException; import com.sun.jdo.api.persistence.support.SpecialDBOperation; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.IOException; +import java.lang.System.Logger; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; @@ -36,6 +35,10 @@ import org.glassfish.persistence.common.database.DBVendorTypeHelper; import org.glassfish.persistence.common.database.PropertyHelper; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.INFO; +import static java.lang.System.Logger.Level.TRACE; + /** @@ -44,7 +47,7 @@ public class DBVendorType { /** * Map from property name to property value. */ - private HashMap dbMap; + private HashMap dbMap; /** * Instance of specialDBOperation for this vendor type. Please look at @@ -61,35 +64,26 @@ public class DBVendorType { */ private String vendorType; - /** - * VendorType as returned from {@link DBVendorTypeHelper#getEnumDBType(java.lang.String)} - */ - private int enumVendorType; - - /** - * The logger - */ - private final static Logger logger; - /** * I18N message handler */ - private final static ResourceBundle messages; + private final static ResourceBundle messages = I18NHelper + .loadBundle("com.sun.jdo.spi.persistence.support.sqlstore.Bundle", DBVendorType.class.getClassLoader()); /** * Default properties */ private static Properties defaultProperties; - private final static String EXT = ".properties"; // NOI18N - private final static String SPACE = " "; // NOI18N - private final static String NONE = ""; // NOI18N + private final static String EXT = ".properties"; + private final static String SPACE = " "; + private final static String NONE = ""; - private final static String PATH = "com/sun/jdo/spi/persistence/support/sqlstore/database/"; // NOI18N - private final static String PROPERTY_OVERRIDE_FILE = ".tpersistence.properties"; // NOI18N + private final static String PATH = "com/sun/jdo/spi/persistence/support/sqlstore/database/"; + private final static String PROPERTY_OVERRIDE_FILE = ".tpersistence.properties"; - private final static String FOR_UPDATE = "FOR_UPDATE"; // NOI18N + private final static String FOR_UPDATE = "FOR_UPDATE"; private final static String HOLDLOCK = "HOLDLOCK"; //NOI18N private final static String SUPPORTS_UPDATE_LOCK = "SUPPORTS_UPDATE_LOCK"; //NOI18N private final static String SUPPORTS_LOCK_COLUMN_LIST = "SUPPORTS_LOCK_COLUMN_LIST"; //NOI18N @@ -148,17 +142,14 @@ public class DBVendorType { CONCAT_CAST, PARAMETER_CAST, INLINE_NUMERIC, NOT_EQUAL }; + /** * Initialize static fields. */ static { - logger = LogHelperSQLStore.getLogger(); - messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N - DBVendorType.class.getClassLoader()); - defaultProperties = initializeDefaultProperties(); } + private static final Logger LOG = System.getLogger(DBVendorType.class.getName(), messages); /** * @param databaseMetaData Instance of DatabaseMetaData @@ -171,27 +162,29 @@ public DBVendorType(DatabaseMetaData databaseMetaData, String identifier) String vendorName = databaseMetaData.getDatabaseProductName(); String vendorType = DBVendorTypeHelper.getDBType(vendorName); - if (logger.isLoggable()) { - Object[] items = new Object[] {vendorName,vendorType}; - logger.fine("sqlstore.database.dbvendor.vendorname", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.vendorname", vendorName, vendorType); this.vendorType = vendorType; - enumVendorType = DBVendorTypeHelper.getEnumDBType(vendorType); + DBVendorTypeHelper.getEnumDBType(vendorType); dbMap = getDBPropertiesMap(vendorType,vendorName); - specialDBOperation = newSpecialDBOperationInstance((String)dbMap.get(SPECIAL_DB_OPERATION), + specialDBOperation = newSpecialDBOperationInstance(dbMap.get(SPECIAL_DB_OPERATION), databaseMetaData, identifier); } /** * get properties map for given vendorType and vendorName */ - private static HashMap getDBPropertiesMap(String vendorType, String vendorName) { + private static HashMap getDBPropertiesMap(String vendorType, String vendorName) { //Initialize returned map to default - HashMap dbHashMap = new HashMap(defaultProperties); - Properties dbProperties = loadDBProperties(vendorType, vendorName); - dbHashMap.putAll(dbProperties); + HashMap dbHashMap = new HashMap<>(defaultProperties.size()); + for (String name : defaultProperties.stringPropertyNames()) { + dbHashMap.put(name, defaultProperties.getProperty(name)); + } + Properties dbProperties = loadDBProperties(vendorType, vendorName); + for (String name : dbProperties.stringPropertyNames()) { + dbHashMap.put(name, dbProperties.getProperty(name)); + } return dbHashMap; } @@ -207,7 +200,7 @@ private static Properties initializeDefaultProperties() { loadFromResource(DBVendorTypeHelper.DEFAULT_DB, defaultProperties); } catch (IOException e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.database.dbvendor.cantloadDefaultProperties"), // NOI18N + "sqlstore.database.dbvendor.cantloadDefaultProperties"), e); } } @@ -226,9 +219,7 @@ private static Properties loadDBProperties(String vendorType, String vendorName) loadFromResource(vendorType, dbProperties); } catch (IOException e) { // else ignore - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.init.default", vendorType); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.init.default", vendorType); } } overrideProperties(dbProperties, vendorName); @@ -240,15 +231,11 @@ private static Properties loadDBProperties(String vendorType, String vendorName) * by the user */ private static void overrideProperties(Properties dbProperties, String vendorName) { - boolean debug = logger.isLoggable(); - Properties overridingProperties = new Properties(); try { PropertyHelper.loadFromFile(overridingProperties, PROPERTY_OVERRIDE_FILE); } catch (Exception e) { - if (debug) { - logger.fine("sqlstore.database.dbvendor.overrideproperties"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.overrideproperties"); return; // nothing to override } @@ -256,15 +243,12 @@ private static void overrideProperties(Properties dbProperties, String vendorNam String cleanVendorName = vendorName.toLowerCase().replace(' ', '_'); cleanVendorName = cleanVendorName.replace('/', '_'); - String propertyPrefix = "database." + cleanVendorName + "."; // prefix // NOI18N + String propertyPrefix = "database." + cleanVendorName + "."; // prefix for (int i = 0; i < props.length; i++) { String o = overridingProperties.getProperty(propertyPrefix + props[i]); if (o != null) { - if (debug) { - Object[] items = new Object[] {props[i],o}; - logger.fine("sqlstore.database.dbvendor.overrideproperties.with", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.overrideproperties.with", props[i], o); dbProperties.setProperty(props[i], o); } } @@ -309,10 +293,7 @@ private SpecialDBOperation newSpecialDBOperationInstance( clz = Class.forName(specialDBOpClassName); } } catch (Exception ex) { - if (logger.isLoggable()) { - logger.log(Logger.INFO, "core.configuration.cantloadclass", - specialDBOpClassName); - } + LOG.log(INFO, "core.configuration.cantloadclass", specialDBOpClassName); return null; } @@ -323,7 +304,7 @@ private SpecialDBOperation newSpecialDBOperationInstance( } catch(Exception ex) { throw new JDOFatalUserException( I18NHelper.getMessage(messages, - "sqlstore.database.dbvendor.cantinstantiateclass", // NOI18N + "sqlstore.database.dbvendor.cantinstantiateclass", specialDBOpClassName), ex); } } @@ -336,14 +317,12 @@ private SpecialDBOperation newSpecialDBOperationInstance( * for this database */ public String getLeftJoin() { - String s = (String)dbMap.get(LEFT_JOIN); + String s = dbMap.get(LEFT_JOIN); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getleftjoin", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getleftjoin", s); return SPACE + s; } @@ -353,12 +332,10 @@ public String getLeftJoin() { * Returns true if this database supports update lock */ public boolean isUpdateLockSupported() { - String s = (String)dbMap.get(SUPPORTS_UPDATE_LOCK); + String s = dbMap.get(SUPPORTS_UPDATE_LOCK); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isupdatelocksupported", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.isupdatelocksupported", b); return b.booleanValue(); } @@ -367,12 +344,10 @@ public boolean isUpdateLockSupported() { * Returns true if this database supports update 'of column list' */ public boolean isLockColumnListSupported() { - String s = (String)dbMap.get(SUPPORTS_LOCK_COLUMN_LIST); + String s = dbMap.get(SUPPORTS_LOCK_COLUMN_LIST); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.islockcolumnlistsupported", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.islockcolumnlistsupported", b); return b.booleanValue(); } @@ -381,12 +356,10 @@ public boolean isLockColumnListSupported() { * Returns true if this database supports distinct clause with update lock */ public boolean isDistinctSupportedWithUpdateLock() { - String s = (String)dbMap.get(SUPPORTS_DISTINCT_WITH_UPDATE_LOCK); + String s = dbMap.get(SUPPORTS_DISTINCT_WITH_UPDATE_LOCK); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isdistinctupdatelocksupported", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.isdistinctupdatelocksupported", b); return b.booleanValue(); } @@ -397,14 +370,12 @@ public boolean isDistinctSupportedWithUpdateLock() { * for this database */ public String getHoldlock() { - String s = (String)dbMap.get(HOLDLOCK); + String s = dbMap.get(HOLDLOCK); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getholdlock", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getholdlock", s); return SPACE + s; } @@ -413,13 +384,9 @@ public String getHoldlock() { * Returns true if the this database needs native outer join semantics. */ public boolean isNativeOuterJoin() { - String s = (String)dbMap.get(NATIVE_OUTER_JOIN); + String s = dbMap.get(NATIVE_OUTER_JOIN); Boolean b = Boolean.valueOf(s); - - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isNativeOuterJoin", b); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.database.dbvendor.isNativeOuterJoin", b); return b.booleanValue(); } @@ -428,15 +395,12 @@ public boolean isNativeOuterJoin() { * for this database */ public String getLeftJoinPost() { - String s = (String)dbMap.get(LEFT_JOIN_APPEND); + String s = dbMap.get(LEFT_JOIN_APPEND); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getleftjoinpost", s); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.database.dbvendor.getleftjoinpost", s); return SPACE + s; } @@ -445,15 +409,11 @@ public String getLeftJoinPost() { * for this database */ public String getRightJoin() { - String s = (String)dbMap.get(RIGHT_JOIN); + String s = dbMap.get(RIGHT_JOIN); if (s == null) { s = NONE; } - - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getrightjoin", s); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.database.dbvendor.getrightjoin", s); return SPACE + s; } @@ -462,15 +422,12 @@ public String getRightJoin() { * for this database */ public String getRightJoinPre() { - String s = (String)dbMap.get(RIGHT_JOIN_PRE); + String s = dbMap.get(RIGHT_JOIN_PRE); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getrightjoinipre", s); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.database.dbvendor.getrightjoinipre", s); return SPACE + s; } @@ -479,14 +436,12 @@ public String getRightJoinPre() { * for this database */ public String getIsNull() { - String s = (String)dbMap.get(IS_NULL); + String s = dbMap.get(IS_NULL); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getisnull", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getisnull", s); return SPACE + s; } @@ -496,14 +451,12 @@ public String getIsNull() { * for this database */ public String getIsNotNull() { - String s = (String)dbMap.get(IS_NOT_NULL); + String s = dbMap.get(IS_NOT_NULL); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getisnotnull", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getisnotnull", s); return SPACE + s; } @@ -512,12 +465,10 @@ public String getIsNotNull() { * Returns true if this database need ansi style rtrim semantics. */ public boolean isAnsiTrim() { - String s = (String)dbMap.get(ANSI_TRIM); + String s = dbMap.get(ANSI_TRIM); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isAnsiTrim", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.isAnsiTrim", b); return b.booleanValue(); } @@ -527,14 +478,12 @@ public boolean isAnsiTrim() { * for this database */ public String getRtrim() { - String s = (String)dbMap.get(RTRIM); + String s = dbMap.get(RTRIM); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getrtrim", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getrtrim", s); return SPACE + s; } @@ -544,14 +493,12 @@ public String getRtrim() { * for this database */ public String getRtrimPost() { - String s = (String)dbMap.get(RTRIM_POST); + String s = dbMap.get(RTRIM_POST); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getrtrimpost", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getrtrimpost", s); return SPACE + s; } @@ -561,14 +508,12 @@ public String getRtrimPost() { * for this database */ public String getCharLength() { - String s = (String)dbMap.get(CHAR_LENGTH); + String s = dbMap.get(CHAR_LENGTH); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getcharlength", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getcharlength", s); return SPACE + s; } @@ -578,16 +523,14 @@ public String getCharLength() { * for this database */ public String getSqrt() { - String s = (String)dbMap.get(SQRT); + String s = dbMap.get(SQRT); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "Sqrt")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getsqrt", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getsqrt", s); return SPACE + s; } @@ -597,16 +540,14 @@ public String getSqrt() { * for this database */ public String getAbs() { - String s = (String)dbMap.get(ABS); + String s = dbMap.get(ABS); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "Abs")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getabs", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getabs", s); return SPACE + s; } @@ -616,14 +557,12 @@ public String getAbs() { * for this database */ public String getForUpdate() { - String s = (String)dbMap.get(FOR_UPDATE); + String s = dbMap.get(FOR_UPDATE); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getforupdate", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getforupdate", s); return SPACE + s; } @@ -633,14 +572,12 @@ public String getForUpdate() { * for this database */ public String getTableListStart() { - String s = (String)dbMap.get(TABLE_LIST_START); + String s = dbMap.get(TABLE_LIST_START); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.gettableliststart", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.gettableliststart", s); return SPACE + s; } @@ -650,14 +587,12 @@ public String getTableListStart() { * for this database */ public String getTableListEnd() { - String s = (String)dbMap.get(TABLE_LIST_END); + String s = dbMap.get(TABLE_LIST_END); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.gettablelistend", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.gettablelistend", s); return SPACE + s; } @@ -667,14 +602,12 @@ public String getTableListEnd() { * for this database */ public String getStringConcat() { - String s = (String)dbMap.get(STRING_CONCAT); + String s = dbMap.get(STRING_CONCAT); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getstringconcat", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getstringconcat", s); return SPACE + s + SPACE; } @@ -684,14 +617,12 @@ public String getStringConcat() { * an empty string, if there is none. */ public String getQuoteCharStart() { - String s = (String)dbMap.get(QUOTE_CHAR_START); + String s = dbMap.get(QUOTE_CHAR_START); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getquotecharstart", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getquotecharstart", s); return s; } @@ -701,14 +632,12 @@ public String getQuoteCharStart() { * an empty string, if there is none. */ public String getQuoteCharEnd() { - String s = (String)dbMap.get(QUOTE_CHAR_END); + String s = dbMap.get(QUOTE_CHAR_END); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getquotecharend", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getquotecharend", s); return s; } @@ -718,12 +647,10 @@ public String getQuoteCharEnd() { * for this database */ public boolean getQuoteSpecialOnly() { - String s = (String)dbMap.get(QUOTE_SPECIAL_ONLY); + String s = dbMap.get(QUOTE_SPECIAL_ONLY); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getquotespecialonly", b); // NOI18N - } + LOG.log(TRACE, QUOTE_SPECIAL_ONLY + " is set to " + b); return b.booleanValue(); } @@ -733,16 +660,14 @@ public boolean getQuoteSpecialOnly() { * for this database */ public String getSubstring() { - String s = (String)dbMap.get(SUBSTRING); + String s = dbMap.get(SUBSTRING); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "substring")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getsubstring", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getsubstring", s); return SPACE + s; } @@ -752,16 +677,14 @@ public String getSubstring() { * for this database */ public String getSubstringFrom() { - String s = (String)dbMap.get(SUBSTRING_FROM); + String s = dbMap.get(SUBSTRING_FROM); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "from part of substring")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getsubstringfrom", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getsubstringfrom", s); return SPACE + s + SPACE; } @@ -771,16 +694,14 @@ public String getSubstringFrom() { * for this database */ public String getSubstringFor() { - String s = (String)dbMap.get(SUBSTRING_FOR); + String s = dbMap.get(SUBSTRING_FOR); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "for part of substring")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getsubstringfor", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getsubstringfor", s); return SPACE + s + SPACE; } @@ -790,16 +711,14 @@ public String getSubstringFor() { * for this database */ public String getPosition() { - String s = (String)dbMap.get(POSITION); + String s = dbMap.get(POSITION); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "position")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getposition", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getposition", s); return SPACE + s; } @@ -809,16 +728,14 @@ public String getPosition() { * for this database */ public String getPositionSep() { - String s = (String)dbMap.get(POSITION_SEP); + String s = dbMap.get(POSITION_SEP); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", "in part of position")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getpositionin", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getpositionin", s); return SPACE + s; } @@ -828,12 +745,10 @@ public String getPositionSep() { * argument is Source String for this database */ public boolean isPositionSearchSource() { - String s = (String)dbMap.get(POSITION_SEARCH_SOURCE); + String s = dbMap.get(POSITION_SEARCH_SOURCE); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getpositionsrchsrc", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getpositionsrchsrc", b); return b.booleanValue(); } @@ -842,12 +757,10 @@ public boolean isPositionSearchSource() { * Returns true if position has three argument for this database */ public boolean isPositionThreeArgs() { - String s = (String)dbMap.get(POSITION_THREE_ARGS); + String s = dbMap.get(POSITION_THREE_ARGS); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getposition3args", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getposition3args", b); return b.booleanValue(); } @@ -856,12 +769,10 @@ public boolean isPositionThreeArgs() { * Returns true if this database maps empty Strings to NULL */ public boolean mapEmptyStringToNull() { - String s = (String)dbMap.get(MAP_EMPTY_STRING_TO_NULL); + String s = dbMap.get(MAP_EMPTY_STRING_TO_NULL); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.mapemptystrtonull", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.mapemptystrtonull", b); return b.booleanValue(); } @@ -870,12 +781,10 @@ public boolean mapEmptyStringToNull() { * Returns true if this database supports "LIKE ESCAPE" clause */ public boolean supportsLikeEscape() { - String s = (String)dbMap.get(SUPPORTS_LIKE_ESCAPE); + String s = dbMap.get(SUPPORTS_LIKE_ESCAPE); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.supportslikeescape", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.supportslikeescape", b); return b.booleanValue(); } @@ -885,14 +794,12 @@ public boolean supportsLikeEscape() { * for this database */ public String getLeftLikeEscape() { - String s = (String)dbMap.get(LEFT_LIKE_ESCAPE); + String s = dbMap.get(LEFT_LIKE_ESCAPE); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getleftlikeescape", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getleftlikeescape", s); return SPACE + s; } @@ -902,14 +809,12 @@ public String getLeftLikeEscape() { * for this database */ public String getRightLikeEscape() { - String s = (String)dbMap.get(RIGHT_LIKE_ESCAPE); + String s = dbMap.get(RIGHT_LIKE_ESCAPE); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getrightlikeescape", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getrightlikeescape", s); return SPACE + s; } @@ -918,15 +823,13 @@ public String getRightLikeEscape() { * Returns function name for comparing null value for this database */ public String getNullComparisonFunctionName() { - String s = (String)dbMap.get(NULL_COMPARISON_FUNCTION_NAME); + String s = dbMap.get(NULL_COMPARISON_FUNCTION_NAME); if (s == null) { s = NONE; } else { s = s.trim(); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getNullComparisonFunctionName", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getNullComparisonFunctionName", s); return s; } @@ -942,16 +845,14 @@ public boolean isModOperationUsingFunction() { * Returns function name for MOD. */ public String getModFunctionName() { - String s = (String)dbMap.get(MOD_FUNCTION_NAME); + String s = dbMap.get(MOD_FUNCTION_NAME); if (s == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N + "core.constraint.illegalop", " % ")); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getModFunctionName", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getModFunctionName", s); return s; } @@ -960,15 +861,13 @@ public String getModFunctionName() { * Returns cast name that surrounds concat operation. */ public String getConcatCast() { - String s = (String)dbMap.get(CONCAT_CAST); + String s = dbMap.get(CONCAT_CAST); if (s == null) { s = NONE; } else { s = s.trim(); } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getConcatCast", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getConcatCast", s); return s; } @@ -976,12 +875,10 @@ public String getConcatCast() { * Returns true if parameters need to be casted for this database */ public boolean isParameterCast() { - String s = (String)dbMap.get(PARAMETER_CAST); + String s = dbMap.get(PARAMETER_CAST); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isParameterCast", b); // NOI18N - } + LOG.log(DEBUG, "isParameterCast(): {0}.", b); return b.booleanValue(); } @@ -990,12 +887,10 @@ public boolean isParameterCast() { * Returns true if numeric parameters are inlined for this database */ public boolean isInlineNumeric() { - String s = (String)dbMap.get(INLINE_NUMERIC); + String s = dbMap.get(INLINE_NUMERIC); Boolean b = Boolean.valueOf(s); - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.isInlineNumeric", b); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.isInlineNumeric", b); return b.booleanValue(); } @@ -1007,14 +902,12 @@ public boolean isInlineNumeric() { * "<>". */ public String getNotEqual() { - String s = (String)dbMap.get(NOT_EQUAL); + String s = dbMap.get(NOT_EQUAL); if (s == null) { s = NONE; } - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getnotequal", s); // NOI18N - } + LOG.log(DEBUG, "sqlstore.database.dbvendor.getnotequal", s); return s; } @@ -1032,10 +925,7 @@ public String getName() { * Returns a SpecialDBOperation object */ public SpecialDBOperation getSpecialDBOperation() { - if (logger.isLoggable()) { - logger.fine("sqlstore.database.dbvendor.getSpecialDBOperation", specialDBOperation); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.database.dbvendor.getSpecialDBOperation", specialDBOperation); return specialDBOperation; } @@ -1046,11 +936,11 @@ public SpecialDBOperation getSpecialDBOperation() { * @return parameter marker for type. */ public String getParameterMarker(int type) { - String paramMarker = "?"; // NOI18N + String paramMarker = "?"; if (isParameterCast()) { String castType = getCastType(type); if (castType != null) { - paramMarker = "CAST (? AS " + castType + ")"; // NOI18N + paramMarker = "CAST (? AS " + castType + ")"; } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/oracle/OracleSpecialDBOperation.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/oracle/OracleSpecialDBOperation.java index ca7249101a2..bd765247b94 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/oracle/OracleSpecialDBOperation.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/database/oracle/OracleSpecialDBOperation.java @@ -53,10 +53,9 @@ package com.sun.jdo.spi.persistence.support.sqlstore.database.oracle; import com.sun.jdo.api.persistence.support.FieldMapping; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.database.BaseSpecialDBOperation; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -65,6 +64,9 @@ import java.util.Arrays; import java.util.List; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.INFO; + /** * OracleSpecialDBOperation is derived class for Oracle specific operation. * @author Shing Wai Chan @@ -74,7 +76,7 @@ public class OracleSpecialDBOperation extends BaseSpecialDBOperation { /** * The logger */ - private static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(OracleSpecialDBOperation.class.getName()); /** * Interface used to handle driver specific implementation for various @@ -142,61 +144,29 @@ public OracleSpecialDBOperation() { * characteristics of the jdbc driver used with this DataSource. */ @Override - public void initialize(DatabaseMetaData metaData, - String identifier) throws SQLException { + public void initialize(DatabaseMetaData metaData, String identifier) throws SQLException { Connection con = metaData.getConnection(); // Since the PreparedStatement obtained is directly through // con, there is no need to unwrap it. - PreparedStatement testPs = con.prepareStatement(TEST_STATEMENT); -/* - if (oracle817ClassesAvailable && - testPs instanceof oracle.jdbc.OraclePreparedStatement) { - // This DataSource uses a driver version 8.1.7 or higher. - // Oracle drivers for version 8.1.7 and higher define interface - // oracle.jdbc.OraclePreparedStatement. - // OraclePreparedStaement obtained from these drivers implement this - // interface. It is possible that in future Oracle might alter - // implementation class for OraclePreparedStatement. However, they - // should continue implementing this interface. Hence, this - // interface should be preferred to communicate with Oracle drivers. - dBDriverHandlerFactory = new OracleDriverHandlerFactory() { - public DBDriverHandler createDBDriverHandler(PreparedStatement ps) { - return new Oracle817Handler(ps); - } - }; - } else if (oracle816ClassesAvailable && - testPs instanceof oracle.jdbc.driver.OraclePreparedStatement) { - // This DataSource uses a driver version lower than 8.1.7. - // Currently all Oracle drivers return instance of - // oracle.jdbc.driver.OraclePreparedStatement for OraclePreparedStatement. - dBDriverHandlerFactory = new OracleDriverHandlerFactory() { - public DBDriverHandler createDBDriverHandler(PreparedStatement ps) { - return new Oracle816Handler(ps); - } - }; - } else */{ + try (PreparedStatement testPs = con.prepareStatement(TEST_STATEMENT)) { // This DataSource uses a non oracle driver. dBDriverHandlerFactory = new DBDriverHandlerFactory() { + @Override public DBDriverHandler createDBDriverHandler(PreparedStatement ps) { return new NonOracleHandler(ps); } + @Override public boolean supportsDefineColumnType() { return false; } }; // Warn the user Oracle specific features will be disabled. - if(logger.isLoggable(logger.CONFIG)) { - identifier = identifier == null ? - "Connection Factory" : identifier; //NOI18N - logger.log(logger.CONFIG, - "sqlstore.database.oracle.nooracleavailable", //NOI18N - identifier); - } + identifier = identifier == null ? "Connection Factory" : identifier; + LOG.log(DEBUG, "sqlstore.database.oracle.nooracleavailable", identifier); } - testPs.close(); } /** @@ -226,11 +196,7 @@ public void defineColumnTypeForResult( } } } catch (Exception ex) { - if (logger.isLoggable(Logger.INFO)) { - logger.log(Logger.INFO, - "sqlstore.database.oracle.defineCol", // NOI18N - ex); - } + LOG.log(INFO, "sqlstore.database.oracle.defineCol", ex); driverHandler.clearDefines(); } } @@ -342,10 +308,7 @@ public void bindFixedCharColumn(int index, String strVal, int length) // padding the value with spaces to the length specified in the // dbschema metadata. ps.setString(index, padSpaceChar(strVal, length) ); - if (logger.isLoggable(Logger.FINE) ) { - logger.log(Logger.FINE, "sqlstore.database.oracle.fixedcharpadded", - strVal, new Integer(length) ); - } + LOG.log(DEBUG, "sqlstore.database.oracle.fixedcharpadded", strVal, length); } private static final char SPACE_CHAR = ' '; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/CMPHelper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/CMPHelper.java index 338a015968e..26a7688a9c6 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/CMPHelper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/CMPHelper.java @@ -85,15 +85,15 @@ public synchronized static long getNextId() { * throws JDOFatalInternalException. * The info argument can be an array of Objects if necessary. * - * @see getEJBObject(Object, Object) - * @see getEJBLocalObject(Object, Object) - * @see getEJBLocalObject(Object, Object, EJBContext) - * @see removeByEJBLocalObject(EJBLocalObject, Object) - * @see removeByPK(Object, Object) * @param info Object with the request information that is application server * specific. * @return a Container instance as an Object. * @throws JDOFatalInternalException if ContainerHelper instance is not registered. + * @see #getEJBObject(Object, Object) + * @see #getEJBLocalObject(Object, Object) + * @see #getEJBLocalObject(Object, Object, EJBContext) + * @see #removeByEJBLocalObject(EJBLocalObject, Object) + * @see #removeByPK(Object, Object) */ public static Object getContainer(Object info) { return getContainerHelper().getContainer(info); @@ -103,7 +103,7 @@ public static Object getContainer(Object info) { * primary key instance and Container object. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @return a corresponding EJBObject (as an Object) to be used by @@ -117,7 +117,7 @@ public static EJBObject getEJBObject(Object pk, Object container) { * primary key instance and Container object. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @return a corresponding EJBLocalObject (as an Object) to be used by @@ -133,7 +133,7 @@ public static EJBLocalObject getEJBLocalObject(Object pk, Object container) { * that is part of a cascade-delete remove. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @param context an EJBContext of the calling bean. @@ -149,7 +149,7 @@ public static EJBLocalObject getEJBLocalObject(Object pk, Object container, * and Container instance. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param ejb the EJBLocalObject for the bean to be removed. * @param container a Container instance for the request. */ @@ -161,7 +161,7 @@ public static void removeByEJBLocalObject(EJBLocalObject ejb, Object container) * and Container instance. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key for the bean to be removed. * @param container a Container instance for the request. */ @@ -186,7 +186,7 @@ public static void setCascadeDeleteAfterSuperEJBRemove(EntityContext context) { * referenced by this Container instance as the CMP resource. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ public static PersistenceManagerFactory getPersistenceManagerFactory(Object container) { @@ -197,7 +197,7 @@ public static PersistenceManagerFactory getPersistenceManagerFactory(Object cont * is of a valid local interface type. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to validate. * @param container a Container instance for the request. */ @@ -209,7 +209,7 @@ public static void assertValidLocalObject(Object o, Object container) { * is of a valid remote interface type. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to validate. * @param container a Container instance for the request. */ @@ -221,7 +221,7 @@ public static void assertValidRemoteObject(Object o, Object container) { * ejbSelect had been called. * The Container instance is acquired via #getContainer(Object). * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ public static void preSelect(Object container) { @@ -231,7 +231,7 @@ public static void preSelect(Object container) { /** * Called in CMP environment to get NumericConverter policy referenced * by this Container instance. - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request * @return a valid NumericConverter policy type */ diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/ContainerHelper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/ContainerHelper.java index 976ca1612a8..c09e76dbbb4 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/ContainerHelper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/ContainerHelper.java @@ -57,15 +57,15 @@ public interface ContainerHelper { * should not be called and throws JDOFatalInternalException. * The info argument can be an array of Objects if necessary. * - * @see getEJBObject(Object, Object) - * @see getEJBLocalObject(Object, Object) - * @see getEJBLocalObject(Object, Object, EJBContext) - * @see removeByEJBLocalObject(EJBLocalObject, Object) - * @see removeByPK(Object, Object) * @param info Object with the request information that is application server * specific. * @throws JDOFatalInternalException. * @return a Container instance as an Object. + * @see #getEJBObject(Object, Object) + * @see #getEJBLocalObject(Object, Object) + * @see #getEJBLocalObject(Object, Object, EJBContext) + * @see #removeByEJBLocalObject(EJBLocalObject, Object) + * @see #removeByPK(Object, Object) */ Object getContainer(Object info); @@ -73,7 +73,7 @@ public interface ContainerHelper { * primary key instance and Container instance. In a non-managed environment * is not called. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @return a corresponding EJBObject instance (as an Object) to be used by @@ -84,7 +84,7 @@ public interface ContainerHelper { /** Called in a CMP-supported environment to get an EJBLocalObject reference for this * primary key instance and Container instance. In a non-managed environment * is not called. - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @return a corresponding EJBLocalObject (as an Object) instance to be used @@ -97,7 +97,7 @@ public interface ContainerHelper { * Allows the container to check if this method is called during ejbRemove * that is part of a cascade-delete remove. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @param context an EJBContext of the calling bean. @@ -110,7 +110,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP-supported environment to remove a bean for a given * EJBLocalObject and Container instance. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param ejb the EJBLocalObject for the bean to be removed. * @param containerHelper a Container instance for the request. */ @@ -119,7 +119,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP-supported environment to remove a bean for a given primary key * and Container instance. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key for the bean to be removed. * @param container a Container instance for the request. */ @@ -128,7 +128,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP-supported environment to verify that the specified object * is of a valid local interface type. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to validate. * @param container a Container instance for the request. */ @@ -137,7 +137,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP-supported environment to verify that the specified object * is of a valid remote interface type. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to validate. * @param container a Container instance for the request. */ @@ -156,7 +156,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP supported environment. Notifies the container that * ejbSelect had been called. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ void preSelect(Object container); @@ -164,7 +164,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** Called in a CMP environment to lookup PersistenceManagerFactory * referenced by this Container instance as the CMP resource. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ PersistenceManagerFactory getPersistenceManagerFactory(Object container); @@ -172,7 +172,7 @@ EJBLocalObject getEJBLocalObject(Object pk, Object container, /** * Called in CMP environment to get NumericConverter policy referenced * by this Container instance. - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request * @return a valid NumericConverter policy type */ diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/DeploymentHelper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/DeploymentHelper.java index 75e75d793a6..442064bcd4b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/DeploymentHelper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/DeploymentHelper.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,10 +19,9 @@ import com.sun.appserv.connectors.internal.api.ConnectorRuntime; import com.sun.jdo.api.persistence.support.JDOFatalUserException; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperPersistenceManager; import com.sun.jdo.spi.persistence.utility.StringHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; @@ -37,6 +36,9 @@ import org.glassfish.persistence.common.I18NHelper; import org.glassfish.persistence.common.Java2DBProcessorHelper; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.ERROR; + /** * This class is used for static method invocations to avoid unnecessary * registration requirements to use EJBHelper and/or CMPHelper from @@ -46,12 +48,10 @@ public class DeploymentHelper { /** I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", DeploymentHelper.class.getClassLoader()); - /** The logger */ - private static Logger logger = LogHelperPersistenceManager.getLogger(); - + private static final Logger LOG = System.getLogger(DeploymentHelper.class.getName()); /** * Returns name prefix for DDL files extracted from the info instance by the * Sun-specific code. @@ -74,12 +74,9 @@ public static String getDDLNamePrefix(Object info) { public static boolean isJavaToDatabase(Properties prop) { if (prop != null) { String value = prop.getProperty(DatabaseConstants.JAVA_TO_DB_FLAG); - if (! StringHelper.isEmpty(value)) { - if (logger.isLoggable(Logger.FINE)) - { - logger.fine(DatabaseConstants.JAVA_TO_DB_FLAG + " property is set."); // NOI18N - } - return Boolean.valueOf(value).booleanValue(); + if (!StringHelper.isEmpty(value)) { + LOG.log(DEBUG, DatabaseConstants.JAVA_TO_DB_FLAG + " property is set."); + return Boolean.valueOf(value).booleanValue(); } } return false; @@ -98,11 +95,7 @@ public static boolean isJavaToDatabase(Properties prop) { * @throws SQLException if can not get a Connection. */ public static Connection getConnection(SimpleJndiName name) throws SQLException { - if (logger.isLoggable(Logger.FINE)) { - logger.fine("ejb.DeploymentHelper.getconnection", name); //NOI18N - } - - // TODO - pass Habitat or ConnectorRuntime as an argument. + LOG.log(DEBUG, "getConnection(name={0})", name); ServiceLocator habitat = Globals.getDefaultHabitat(); DataSource ds = null; @@ -127,7 +120,7 @@ public static Connection getConnection(SimpleJndiName name) throws SQLException private static void handleUnexpectedInstance(String name, Object value) throws JDOFatalUserException { RuntimeException e = new JDOFatalUserException( I18NHelper.getMessage(messages, "ejb.jndi.unexpectedinstance", name, value.getClass().getName())); - logger.severe(e.toString()); + LOG.log(ERROR, e.getMessage(), e); throw e; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB11Helper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB11Helper.java index acdf91cef9c..9590fb6d764 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB11Helper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB11Helper.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 */ -/* - * JDOEJB11Helper.java - * - * Created on January 17, 2002 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.ejb; import com.sun.jdo.api.persistence.support.PersistenceManager; @@ -36,7 +31,7 @@ * to and from EJB objects of type: EJBObject, PrimaryKey, and Collections of those. * This interface is generic for CMP1.1 and CMP2.0. * - * @author Marina Vatkina + * @author Marina Vatkina 2002 */ public interface JDOEJB11Helper { @@ -66,7 +61,7 @@ public interface JDOEJB11Helper { * @param pm the associated instance of PersistenceManager. * @return Collection of EJBObjects. */ - Collection convertCollectionPCToEJBObject (Collection pcs, PersistenceManager pm); + Collection convertCollectionPCToEJBObject (Collection pcs, PersistenceManager pm); /** * Converts Collection of persistence-capable instances to a Set of @@ -75,7 +70,7 @@ public interface JDOEJB11Helper { * @param pm the associated instance of PersistenceManager. * @return Set of EJBObjects. */ - Set convertCollectionPCToEJBObjectSet (Collection pcs, PersistenceManager pm); + Set convertCollectionPCToEJBObjectSet (Collection pcs, PersistenceManager pm); /** * Converts Collection of EJBObjects to a Collection of @@ -87,7 +82,7 @@ public interface JDOEJB11Helper { * @throws IllegalArgumentException if validate is true and at least one instance does * not exist in the database or is deleted. */ - Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager pm, + Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager pm, boolean validate); /** @@ -105,7 +100,7 @@ Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager p * @param pm the associated instance of PersistenceManager. * @return Collection of the PrimaryKey Class instances. */ - Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceManager pm); + Collection convertCollectionPCToPrimaryKey (Collection pcs, PersistenceManager pm); /** * Converts Object Id of a persistence-capable instance to an instance of the @@ -129,7 +124,7 @@ Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager p * @param oids Collection of the Object Id to be converted. * @return Collection of of the PrimaryKey Class instances. */ - Collection convertCollectionObjectIdToPrimaryKey (Collection oids); + Collection convertCollectionObjectIdToPrimaryKey (Collection oids); /** * Converts Collection of PrimaryKey instances to a Collection of Object Id's @@ -137,14 +132,14 @@ Collection convertCollectionEJBObjectToPC (Collection coll, PersistenceManager p * @param key Collection of the PrimaryKey instances to be converted. * @return Collection of the Object Id's. */ - Collection convertCollectionPrimaryKeyToObjectId (Collection key); + Collection convertCollectionPrimaryKeyToObjectId (Collection key); /** * Returns the class object of the corresponding persistence-capable class * of the concrete bean class. * @return the pc class object */ - Class getPCClass (); + Class getPCClass (); /** * Serializes serializableObject into a byte array diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB20Helper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB20Helper.java index 5fc69072af8..0cd0093eeef 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB20Helper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/JDOEJB20Helper.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 */ -/* - * JDOEJB20Helper.java - * - * Created on January 17, 2002 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.ejb; import com.sun.jdo.api.persistence.support.PersistenceManager; @@ -30,12 +25,12 @@ import java.util.Collection; import java.util.Set; -/* +/** * This is the helper interface for conversion of persistence-capable instances * to and from EJB objects of type EJBLocalObject and Collections of those. * It extends generic interface JDOEJB11Helper for all other types of conversions. * - * @author Marina Vatkina + * @author Marina Vatkina 2002 */ public interface JDOEJB20Helper extends JDOEJB11Helper { @@ -77,7 +72,7 @@ Object convertEJBLocalObjectToPC(EJBLocalObject o, PersistenceManager pm, * @param pm the associated instance of PersistenceManager. * @return Collection of EJBLocalObjects. */ - Collection convertCollectionPCToEJBLocalObject (Collection pcs, PersistenceManager pm); + Collection convertCollectionPCToEJBLocalObject (Collection pcs, PersistenceManager pm); /** * Converts Collection of persistence-capable instances to a Set of @@ -86,7 +81,7 @@ Object convertEJBLocalObjectToPC(EJBLocalObject o, PersistenceManager pm, * @param pm the associated instance of PersistenceManager. * @return Set of EJBLocalObjects. */ - Set convertCollectionPCToEJBLocalObjectSet (Collection pcs, PersistenceManager pm); + Set convertCollectionPCToEJBLocalObjectSet (Collection pcs, PersistenceManager pm); /** * Converts Collection of EJBLocalObjects to a Collection of @@ -98,8 +93,7 @@ Object convertEJBLocalObjectToPC(EJBLocalObject o, PersistenceManager pm, * @throws IllegalArgumentException if validate is true and at least one instance does * not exist in the database or is deleted. */ - Collection convertCollectionEJBLocalObjectToPC (Collection coll, PersistenceManager pm, - boolean validate); + Collection convertCollectionEJBLocalObjectToPC(Collection coll, PersistenceManager pm, boolean validate); /** * Validates that this instance is of the correct implementation class diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/LoggerFactoryiAS.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/LoggerFactoryiAS.java deleted file mode 100644 index 4b18716ebdb..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/LoggerFactoryiAS.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 - * 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.spi.persistence.support.sqlstore.ejb; - -import com.sun.jdo.spi.persistence.utility.logging.LoggerFactoryJDK14; -import com.sun.jdo.spi.persistence.utility.logging.LoggerJDK14; - - -/** - * @author Craig Russell - * @version 1.0 - */ -public class LoggerFactoryiAS extends LoggerFactoryJDK14 { - - /** The top level of the logger domain for application server. - */ - protected String DOMAIN_ROOT = "jakarta.enterprise.resource.jdo."; //NOI18N - - /** Creates new LoggerFactory */ - public LoggerFactoryiAS() { - } - - - @Override - protected String getDomainRoot() { - return DOMAIN_ROOT; - } - - /** Create a new Logger. Create a logger for the named component. - * The bundle name is passed to allow the implementation - * to properly find and construct the internationalization bundle. - * - * This operation is executed as a privileged action to allow - * permission access for the following operations: - * ServerLogManager.initializeServerLogger - * - * @param absoluteLoggerName the absolute name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @return the logger - */ - @Override - protected LoggerJDK14 createLogger (final String absoluteLoggerName, - final String bundleName) { - return new LoggerJDK14(absoluteLoggerName, bundleName); - } - - /** - * This method is a no-op in the Sun ONE Application server. - */ - @Override - protected void configureFileHandler(LoggerJDK14 logger) { - } - -} - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/SunContainerHelper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/SunContainerHelper.java index 247983e5af7..6a8de5caae7 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/SunContainerHelper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/ejb/SunContainerHelper.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, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -30,10 +30,8 @@ import com.sun.jdo.api.persistence.support.JDOFatalUserException; import com.sun.jdo.api.persistence.support.PersistenceManager; import com.sun.jdo.api.persistence.support.PersistenceManagerFactory; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperPersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.impl.PersistenceManagerFactoryImpl; import com.sun.jdo.spi.persistence.support.sqlstore.utility.NumericConverter; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import jakarta.ejb.EJBContext; import jakarta.ejb.EJBException; @@ -67,14 +65,12 @@ public class SunContainerHelper extends SunTransactionHelper implements Containe "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N SunContainerHelper.class.getClassLoader()); - /** The logger */ - private static Logger logger = LogHelperPersistenceManager.getLogger(); - - /** Garantees singleton. + /** + * Guarantees singleton. * Registers itself during initial load */ static { - CMPHelper.registerContainerHelper (new SunContainerHelper()); + CMPHelper.registerContainerHelper(new SunContainerHelper()); } /** Default constructor should not be public */ @@ -86,14 +82,14 @@ public class SunContainerHelper extends SunTransactionHelper implements Containe * * The info argument is an Object array that consistes of a class to use * for the class loader and concreteImpl bean class name. - * @see getEJBObject(Object, Object) - * @see getEJBLocalObject(Object, Object) - * @see getEJBLocalObject(Object, Object, EJBObject) - * @see removeByEJBLocalObject(EJBLocalObject, Object) - * @see removeByPK(Object, Object) * @param info Object with the request information that is application server * specific. * @return a Container helper instance as an Object. + * @see #getEJBObject(Object, Object) + * @see #getEJBLocalObject(Object, Object) + * @see #getEJBLocalObject(Object, Object, EJBContext) + * @see #removeByEJBLocalObject(EJBLocalObject, Object) + * @see #removeByPK(Object, Object) */ @Override public Object getContainer(Object info) { @@ -114,7 +110,7 @@ public Object getContainer(Object info) { /** Get an EJBObject reference for this primary key and Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a Container instance for the request. * @return a corresponding EJBObject instance to be used by the client. @@ -131,7 +127,7 @@ public EJBObject getEJBObject(Object pk, Object container) { /** Get an EJBLocalObject reference for this primary key and Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a helper instance for the request. * @return a corresponding EJBLocalObject instance to be used by the client. @@ -151,7 +147,7 @@ public EJBLocalObject getEJBLocalObject(Object pk, Object container) { * that is part of a cascade-delete remove. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key instance. * @param container a helper instance for the request. * @param context an EJBContext of the calling bean. @@ -172,7 +168,7 @@ public EJBLocalObject getEJBLocalObject(Object pk, Object container, EJBContext /** Remove a bean for a given EJBLocalObject and Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param ejb the EJBLocalObject for the bean to be removed. * @param container a Container instance for the request. */ @@ -188,7 +184,7 @@ public void removeByEJBLocalObject(EJBLocalObject ejb, Object container) { /** Remove a bean for a given primary key and Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param pk the primary key for the bean to be removed. * @param container a Container instance for the request. */ @@ -205,7 +201,7 @@ public void removeByPK(Object pk, Object container) { * a given Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to be verified. * @param container a Container instance for the request. */ @@ -218,7 +214,7 @@ public void assertValidLocalObject(Object o, Object container) { * a given Container helper. * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param o the instance to be verified. * @param container a Container instance for the request. */ @@ -250,7 +246,7 @@ public void setCascadeDeleteAfterSuperEJBRemove(EntityContext context) { * * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ @Override @@ -263,7 +259,7 @@ public void preSelect(Object container) { * * This is SunContainerHelper specific code. * - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request. */ @Override @@ -287,10 +283,10 @@ public PersistenceManagerFactory getPersistenceManagerFactory(Object container) pmf = new PersistenceManagerFactoryImpl(); pmf.setConnectionFactoryName(ConnectorsUtil.getPMJndiName(name)); - Iterator it = cmpResource.getProperties(); + Iterator it = cmpResource.getProperties(); if (it != null) { while (it.hasNext()) { - NameValuePairDescriptor prop = (NameValuePairDescriptor)it.next(); + NameValuePairDescriptor prop = it.next(); String n = prop.getName(); // Any value that is not "true" is treated as "false": @@ -304,15 +300,11 @@ public PersistenceManagerFactory getPersistenceManagerFactory(Object container) RuntimeException e = new JDOFatalUserException(I18NHelper.getMessage( messages, "ejb.jndi.unexpectedinstance", //NOI18N name, rc.getClass().getName())); - logger.severe(e.toString()); - throw e; } } catch (javax.naming.NamingException ex) { RuntimeException e = new JDOFatalUserException(I18NHelper.getMessage( messages, "ejb.jndi.lookupfailed", name), ex); //NOI18N - logger.severe(e.toString()); - throw e; } @@ -323,7 +315,7 @@ public PersistenceManagerFactory getPersistenceManagerFactory(Object container) /** * Called in CMP environment to get NumericConverter policy referenced * by this Container instance. - * @see getContainer(Object) + * @see #getContainer(Object) * @param container a Container instance for the request * @return a valid NumericConverter policy type */ diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/Bundle.properties b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/Bundle.properties index 5d62f223483..c030b4585f5 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/Bundle.properties +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/Bundle.properties @@ -69,7 +69,6 @@ transaction.transactionimpl.begin.failedlocaltx=JDO77024: Cannot start a local t transaction.transactionimpl.begin.registersynchfailed=JDO77025: Cannot register Synchronization. transaction.transactionimpl.forget.connectionnotclosed=JDO77026: Connection has not been closed. transaction.transactionimpl.getconnection.nullcf=JDO77027: ConnectionFactory is NULL. -transaction.transactionimpl.syncmanager.aftercompletion=JDO77028: Problems during afterCompletion call to the SynchronizationManager:\n{0} # # @@ -85,7 +84,6 @@ jdo.versionconsistencycacheimpl.removepctype=JDO77036: VCCacheImpl.removePCType: jdo.versionconsistencycacheimpl.usinghashmap=JDO77037: VCCacheImpl: Creating HashMap with bucketSize={0} initialCapacity={1} loadFactor={2} jdo.versionconsistencycacheimpl.usinglrucache=JDO77038: VCCacheImpl: Creating LruCache with maxEntries={0} timeout={1} loadFactor={2} jdo.versionconsistencycacheimpl.trimevent=JDO77039: VCCacheImpl: got trimEvent. -jdo.versionconsistencycacheimpl.created=JDO77040: VCCacheImpl: created with: {0} # # Following messages *DO* need to be I18N'd. diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerImpl.java index 68f5480e364..cc88148a445 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerImpl.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 */ -/* - * PersistenceManagerimpl.java - * - * Created on March 6, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.impl; import com.sun.jdo.api.persistence.support.JDODataStoreException; @@ -32,7 +27,6 @@ import com.sun.jdo.api.persistence.support.Query; import com.sun.jdo.api.persistence.support.Transaction; import com.sun.jdo.spi.persistence.support.sqlstore.ExtentCollection; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperPersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceCapable; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceConfig; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager; @@ -41,6 +35,7 @@ import com.sun.jdo.spi.persistence.support.sqlstore.RetrieveDesc; import com.sun.jdo.spi.persistence.support.sqlstore.RuntimeVersion; import com.sun.jdo.spi.persistence.support.sqlstore.SCOCollection; +import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; import com.sun.jdo.spi.persistence.support.sqlstore.ValueFetcher; import com.sun.jdo.spi.persistence.support.sqlstore.VersionConsistencyCache; @@ -49,12 +44,12 @@ import com.sun.jdo.spi.persistence.utility.NullSemaphore; import com.sun.jdo.spi.persistence.utility.Semaphore; import com.sun.jdo.spi.persistence.utility.SemaphoreImpl; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import jakarta.transaction.Status; import java.io.File; import java.io.FilenameFilter; +import java.lang.System.Logger; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; @@ -72,6 +67,10 @@ import org.glassfish.persistence.common.I18NHelper; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; + public class PersistenceManagerImpl implements PersistenceManager { /** * True if this PersistenceManager is closed @@ -105,13 +104,13 @@ public class PersistenceManagerImpl implements PersistenceManager { * List of all Persistent instances used * in this Transaction not yet flushed to the datastore. */ - private List _txCache; + private List _txCache; /** * List of all Persistent instances used * in this Transaction. */ - private Set _flushedCache; + private Set _flushedCache; /** * Map of Persistent instances accessed by this PersistenceManager. Ideally it should be @@ -119,7 +118,7 @@ public class PersistenceManagerImpl implements PersistenceManager { * referenced any more. java.util.WeakHashMap is a weak-key HashMap and thus does not * solve this purpose. */ - private Map _weakCache; + private Map _weakCache; /** * Intended to be set to true if there is an exception during flush in @@ -141,7 +140,7 @@ public class PersistenceManagerImpl implements PersistenceManager { * 20. */ private static final int _txCacheInitialCapacity = Integer.getInteger( - "com.sun.jdo.api.persistence.support.PersistenceManager.dirtyCache.initialCapacity", // NOI18N + "com.sun.jdo.api.persistence.support.PersistenceManager.dirtyCache.initialCapacity", 20).intValue(); /** @@ -150,7 +149,7 @@ public class PersistenceManagerImpl implements PersistenceManager { * uses 20. */ private static final int _flushedCacheInitialCapacity = Integer.getInteger( - "com.sun.jdo.api.persistence.support.PersistenceManager.transactionalCache.initialCapacity", // NOI18N + "com.sun.jdo.api.persistence.support.PersistenceManager.transactionalCache.initialCapacity", 20).intValue(); /** @@ -166,8 +165,8 @@ public class PersistenceManagerImpl implements PersistenceManager { f = Float.valueOf( System.getProperty( - "com.sun.jdo.api.persistence.support.PersistenceManager.transactionalCache.loadFactor", // NOI18N - "0.75")).floatValue(); // NOI18N + "com.sun.jdo.api.persistence.support.PersistenceManager.transactionalCache.loadFactor", + "0.75")).floatValue(); } finally { _flushedCacheLoadFactor = f; } @@ -179,7 +178,7 @@ public class PersistenceManagerImpl implements PersistenceManager { * uses 20. */ private static final int _weakCacheInitialCapacity = Integer.getInteger( - "com.sun.jdo.api.persistence.support.PersistenceManager.globalCache.initialCapacity", // NOI18N + "com.sun.jdo.api.persistence.support.PersistenceManager.globalCache.initialCapacity", 20).intValue(); /** @@ -195,15 +194,15 @@ public class PersistenceManagerImpl implements PersistenceManager { f = Float.valueOf( System.getProperty( - "com.sun.jdo.api.persistence.support.PersistenceManager.globalCache.loadFactor", // NOI18N - "0.75")).floatValue(); // NOI18N + "com.sun.jdo.api.persistence.support.PersistenceManager.globalCache.loadFactor", + "0.75")).floatValue(); } finally { _weakCacheLoadFactor = f; } } /** Collection of Query instances created for this pm. */ - private Collection queries = new ArrayList(); + private Collection queries = new ArrayList<>(); /** * Flag for Query @@ -258,8 +257,8 @@ public class PersistenceManagerImpl implements PersistenceManager { /** * Pattern for OID class names */ - private static final String oidName_OID = "OID";// NOI18N - private static final String oidName_KEY = "KEY";// NOI18N + private static final String oidName_OID = "OID"; + private static final String oidName_KEY = "KEY"; /** * Properies object @@ -308,13 +307,13 @@ public class PersistenceManagerImpl implements PersistenceManager { /** * The logger */ - private static Logger logger = LogHelperPersistenceManager.getLogger(); + private static final Logger LOG = System.getLogger(PersistenceManagerImpl.class.getName(), RESOURCE_BUNDLE); /** * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", PersistenceManagerImpl.class.getClassLoader()); /** @@ -325,17 +324,11 @@ public class PersistenceManagerImpl implements PersistenceManager { persistenceManagerFactory = pmf; // Initialize caches as per property values. - if (logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] { new Integer(_txCacheInitialCapacity), - new Integer(_flushedCacheInitialCapacity), - new Float(_flushedCacheLoadFactor), - new Integer(_weakCacheInitialCapacity), - new Float(_weakCacheLoadFactor) }; - logger.finest("sqlstore.persistencemgr.cacheproperties", items); // NOI18N - } - _txCache = new ArrayList(_txCacheInitialCapacity); - _flushedCache = new LinkedHashSet(_flushedCacheInitialCapacity, _flushedCacheLoadFactor); - _weakCache = new HashMap(_weakCacheInitialCapacity, _weakCacheLoadFactor); + LOG.log(TRACE, "sqlstore.persistencemgr.cacheproperties", _txCacheInitialCapacity, _flushedCacheInitialCapacity, + _flushedCacheLoadFactor, _weakCacheInitialCapacity, _weakCacheLoadFactor); + _txCache = new ArrayList<>(_txCacheInitialCapacity); + _flushedCache = new LinkedHashSet<>(_flushedCacheInitialCapacity, _flushedCacheLoadFactor); + _weakCache = new HashMap<>(_weakCacheInitialCapacity, _weakCacheLoadFactor); // create new Transaction object and set defaults @@ -356,21 +349,21 @@ public class PersistenceManagerImpl implements PersistenceManager { if (_multithreaded) { _cacheLock = - new SemaphoreImpl("PersistenceManagerImpl.cacheLock"); // NOI18N + new SemaphoreImpl("PersistenceManagerImpl.cacheLock"); _fieldUpdateLock = - new SemaphoreImpl("PersistenceManagerImpl.fieldUpdateLock"); // NOI18N + new SemaphoreImpl("PersistenceManagerImpl.fieldUpdateLock"); } else { if (_jta == null) { // Non-transactional PersistenceManager can be used in a multithreaded // environment. _cacheLock = - new SemaphoreImpl("PersistenceManagerImpl.cacheLock"); // NOI18N + new SemaphoreImpl("PersistenceManagerImpl.cacheLock"); } else { _cacheLock = - new NullSemaphore("PersistenceManagerImpl.cacheLock"); // NOI18N + new NullSemaphore("PersistenceManagerImpl.cacheLock"); } _fieldUpdateLock = - new NullSemaphore("PersistenceManagerImpl.fieldUpdateLock"); // NOI18N + new NullSemaphore("PersistenceManagerImpl.fieldUpdateLock"); } } @@ -405,6 +398,7 @@ protected boolean verify(String username, char[] password) { /** * */ + @Override public boolean isClosed() { return _isClosed; } @@ -414,6 +408,7 @@ public boolean isClosed() { * TransactionImpl.afterCompletion in case of the CMT transaction * and the status value passed to the method cannot be resolved. */ + @Override public void forceClose() { // Return to pool - TBD if we use pooling of free PMs. @@ -428,9 +423,9 @@ public void forceClose() { current.close(); } - Collection c = _weakCache.values(); - for (Iterator it = c.iterator(); it.hasNext();) { - StateManager sm = (StateManager)it.next(); + Collection c = _weakCache.values(); + for (Iterator it = c.iterator(); it.hasNext();) { + StateManager sm = it.next(); // RESOLVE - do we want to release all references in SM? // 1 of two calls below should be removed. @@ -464,6 +459,7 @@ public void forceClose() { /** * close the persistence manager */ + @Override public void close() { acquireExclusiveLock(); @@ -487,7 +483,7 @@ public void close() { if (_activeTransaction || _flushedCache.size() > 0) { throw new JDOException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.close.activetransaction"));// NOI18N + "jdo.persistencemanagerimpl.close.activetransaction")); } forceClose(); @@ -502,6 +498,7 @@ public void close() { * Returns transaction associated with this persistence manager * @return transaction current transaction */ + @Override public Transaction currentTransaction() { assertIsOpen(); return _transaction; @@ -511,6 +508,7 @@ public Transaction currentTransaction() { /** Create a new Query with no elements. * @return a new Query instance with no elements. */ + @Override public Query newQuery() { assertIsOpen(); QueryImpl q = new QueryImpl(this); @@ -525,6 +523,7 @@ public Query newQuery() { * @return the new Query * @param compiled another Query from the same JDO implementation */ + @Override public Query newQuery(Object compiled) { assertIsOpen(); QueryImpl q = new QueryImpl(this, compiled); @@ -536,7 +535,8 @@ public Query newQuery(Object compiled) { * @param cls the Class of the results * @return the new Query */ - public Query newQuery(Class cls) { + @Override + public Query newQuery(Class cls) { assertIsOpen(); QueryImpl q = new QueryImpl(this, cls); registerQuery(q); @@ -549,7 +549,8 @@ public Query newQuery(Class cls) { * @param cln the Collection of candidate instances * @return the new Query */ - public Query newQuery(Class cls, Collection cln) { + @Override + public Query newQuery(Class cls, Collection cln) { assertIsOpen(); QueryImpl q = new QueryImpl(this, cls, cln); registerQuery(q); @@ -562,7 +563,8 @@ public Query newQuery(Class cls, Collection cln) { * @param filter the Filter for candidate instances * @return the new Query */ - public Query newQuery(Class cls, String filter) { + @Override + public Query newQuery(Class cls, String filter) { assertIsOpen(); QueryImpl q = new QueryImpl(this, cls, filter); registerQuery(q); @@ -576,7 +578,8 @@ public Query newQuery(Class cls, String filter) { * @param filter the Filter for candidate instances * @return the new Query */ - public Query newQuery(Class cls, Collection cln, String filter) { + @Override + public Query newQuery(Class cls, Collection cln, String filter) { assertIsOpen(); QueryImpl q = new QueryImpl(this, cls, cln, filter); registerQuery(q); @@ -592,7 +595,8 @@ public Query newQuery(Class cls, Collection cln, String filter) { * @return a Collection of instances * @see #newQuery */ - public Collection getExtent(Class persistenceCapableClass, + @Override + public Collection getExtent(Class persistenceCapableClass, boolean subclasses) { assertIsOpen(); return new ExtentCollection(this, persistenceCapableClass, subclasses); @@ -611,6 +615,7 @@ public Collection getExtent(Class persistenceCapableClass, * @return the PersistenceCapable instance with the specified * ObjectId */ + @Override public Object getObjectById(Object oid) { return getObjectById(oid, false); } @@ -636,21 +641,18 @@ public Object getObjectById(Object oid) { * @param oid an ObjectId * @param validate if the existence of the instance is to be validated */ + @Override public Object getObjectById(Object oid, boolean validate) { - boolean debug = logger.isLoggable(Logger.FINEST); - assertIsOpen(); assertActiveTransaction(true); Object rc = null; - if (debug) { - Object[] items = new Object[] {oid, this,_jta}; - logger.finest("sqlstore.persistencemgr.getbyobjid", items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.getbyobjid", oid, this,_jta); - if (oid == null) + if (oid == null) { return null; + } StateManager sm = lookupObjectById(oid, null); rc = sm.getPersistent(); @@ -676,7 +678,7 @@ public Object getObjectById(Object oid, boolean validate) { throw e; } catch (Exception e) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.fetchinstance.none"), e);// NOI18N + "jdo.persistencemanagerimpl.fetchinstance.none"), e); } } } @@ -693,7 +695,8 @@ public Object getObjectById(Object oid, boolean validate) { * @param pcClass the Class type of the PersistenceCapable instance to be associated * with this StateManager. */ - public StateManager findOrCreateStateManager(Object oid, Class pcClass) { + @Override + public StateManager findOrCreateStateManager(Object oid, Class pcClass) { return lookupObjectById(oid, pcClass); } @@ -702,14 +705,14 @@ public StateManager findOrCreateStateManager(Object oid, Class pcClass) { * @param oid an ObjectId * @param classType the Class type of the returned object or null if not known. */ - private StateManager lookupObjectById(Object oid, Class classType) { + private StateManager lookupObjectById(Object oid, Class classType) { StateManager sm = null; // Check the _weakCache for the instance try { acquireCacheLock(); - sm = (StateManager)_weakCache.get(oid); + sm = _weakCache.get(oid); if (sm == null) { boolean external = false; // Do NOT look in DB, but create a Hollow instance: @@ -719,7 +722,7 @@ private StateManager lookupObjectById(Object oid, Class classType) { if (classType == null) { // Class not found, report an error throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.getobjectbyid.nometadata"), // NOI18N + "jdo.persistencemanagerimpl.getobjectbyid.nometadata"), new Object[]{oid}); } external = true; @@ -746,7 +749,7 @@ private StateManager lookupObjectById(Object oid, Class classType) { throw e; } catch (Exception e) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.fetchinstance.none"), e);// NOI18N + "jdo.persistencemanagerimpl.fetchinstance.none"), e); } } } finally { @@ -760,7 +763,7 @@ private StateManager lookupObjectById(Object oid, Class classType) { * Create a StateManager. * @param classType Class of the PersistenceCapable. */ - private StateManager createStateManager(Class classType) { + private StateManager createStateManager(Class classType) { StateManager rc = _store.getStateManager(classType); newInstance(rc); @@ -775,25 +778,17 @@ private StateManager createStateManager(Class classType) { * @param pc the PersistenceCapable instance * @return the ObjectId of the instance */ + @Override public Object getObjectId(Object pc) { - boolean debug = logger.isLoggable(Logger.FINEST); - assertIsOpen(); assertActiveTransaction(true); - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),pc, this, _jta}; - logger.finest("sqlstore.persistencemgr.getobjid",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.getobjid", Thread.currentThread(), pc, this, _jta); try { assertPersistenceCapable(pc); } catch (Exception e) { - if (debug) { - Object[] items = new Object[] {pc, this}; - logger.finest("sqlstore.persistencemgr.getobjid.notpc",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.getobjid.notpc", pc, this); return null; } @@ -803,11 +798,7 @@ public Object getObjectId(Object pc) { return null; } else if (sm.getPersistenceManagerInternal() != this) { - if (debug) { - Object[] items = new Object[] {pc, this, _jta}; - logger.finest("sqlstore.persistencemgr.getobjid.notpm",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.getobjid.notpm", pc, this, _jta); return null; } @@ -821,6 +812,7 @@ public Object getObjectId(Object pc) { * @return the PersistenceCapable instance representing the * same data store object */ + @Override public Object getTransactionalInstance(Object pc) { assertIsOpen(); assertActiveTransaction(false); @@ -850,17 +842,13 @@ public Object getTransactionalInstance(Object pc) { * @param pc a transient instance of a Class that implements * PersistenceCapable */ + @Override public void makePersistent(Object pc) { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) - { - Object[] items = new Object[] {Thread.currentThread(), pc, this, _jta}; - logger.finest("sqlstore.persistencemgr.makepersistent",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.makepersistent", Thread.currentThread(), pc, this, _jta); - if (pc == null) + if (pc == null) { return; // ignore + } acquireShareLock(); try { @@ -868,12 +856,7 @@ public void makePersistent(Object pc) { assertActiveTransaction(false); assertPersistenceCapable(pc); internalMakePersistent((PersistenceCapable) pc); - if (debug) - { - Object[] items = new Object[] {pc, this, _jta}; - logger.finest("sqlstore.persistencemgr.makepersistent.done",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.makepersistent.done", pc, this, _jta); } finally { releaseShareLock(); } @@ -883,25 +866,31 @@ public void makePersistent(Object pc) { * @param pcs an array of transient instances * @see #makePersistent(Object pc) */ + @Override public void makePersistent(Object[] pcs) { - if (pcs == null) + if (pcs == null) { return; // ignore + } for (int i = 0; i < pcs.length; i++) { makePersistent(pcs[i]); } } - public void makePersistent(Collection pcs) { - if (pcs == null) + @Override + public void makePersistent(Collection pcs) { + if (pcs == null) { return; // ignore + } makePersistent(pcs.toArray()); } + @Override public void deletePersistent(Object pc) { - if (pc == null) + if (pc == null) { return; // ignore + } acquireShareLock(); @@ -915,18 +904,22 @@ public void deletePersistent(Object pc) { } } + @Override public void deletePersistent(Object[] pcs) { - if (pcs == null) + if (pcs == null) { return; // ignore + } for (int i = 0; i < pcs.length; i++) { deletePersistent(pcs[i]); } } - public void deletePersistent(Collection pcs) { - if (pcs == null) + @Override + public void deletePersistent(Collection pcs) { + if (pcs == null) { return; // ignore + } deletePersistent(pcs.toArray()); } @@ -938,13 +931,15 @@ public void deletePersistent(Collection pcs) { * @return the PersistenceManagerFactory that created * this PersistenceManager */ + @Override public com.sun.jdo.api.persistence.support.PersistenceManagerFactory getPersistenceManagerFactory() { return persistenceManagerFactory; } void setPersistenceManagerFactory(PersistenceManagerFactory pmf) { - if (persistenceManagerFactory == null) + if (persistenceManagerFactory == null) { persistenceManagerFactory = pmf; + } } /** The application can manage the PersistenceManager instances @@ -953,6 +948,7 @@ void setPersistenceManagerFactory(PersistenceManagerFactory pmf) { * @param o the user instance to be remembered by the PersistenceManager * @see #getUserObject */ + @Override public void setUserObject(Object o) { this._userObject = o; } @@ -963,6 +959,7 @@ public void setUserObject(Object o) { * @return the user object associated with this PersistenceManager * @see #setUserObject */ + @Override public Object getUserObject() { return _userObject; } @@ -975,10 +972,11 @@ public Object getUserObject() { *
  • VersionNumber
  • * @return the Properties of this PersistenceManager */ + @Override public Properties getProperties() { if (_properties == null) { _properties = RuntimeVersion.getVendorProperties( - "/com/sun/jdo/spi/persistence/support/sqlstore/sys.properties");// NOI18N + "/com/sun/jdo/spi/persistence/support/sqlstore/sys.properties"); } return _properties; } @@ -990,6 +988,7 @@ public Properties getProperties() { * Object Id. * @return boolean supersedeDeletedInstance flag */ + @Override public boolean getSupersedeDeletedInstance () { return _supersedeDeletedInstance; } @@ -999,6 +998,7 @@ public boolean getSupersedeDeletedInstance () { * Sets the supersedeDeletedInstance flag for this PersistenceManager. * @param flag boolean supersedeDeletedInstance flag */ + @Override public void setSupersedeDeletedInstance (boolean flag) { // RESOLVE: synchronization _supersedeDeletedInstance = flag; @@ -1014,6 +1014,7 @@ public void setSupersedeDeletedInstance (boolean flag) { * @see PersistenceManager#getObjectById(Object oid) * @return boolean requireCopyObjectId flag */ + @Override public boolean getRequireCopyObjectId() { return _requireCopyObjectId; } @@ -1029,6 +1030,7 @@ public boolean getRequireCopyObjectId() { * @see PersistenceManager#getObjectById(Object oid) * @param flag boolean requireCopyObjectId flag */ + @Override public void setRequireCopyObjectId (boolean flag) { // RESOLVE: synchronization _requireCopyObjectId = flag; @@ -1043,6 +1045,7 @@ public void setRequireCopyObjectId (boolean flag) { * * @return boolean requireTrackedSCO flag */ + @Override public boolean getRequireTrackedSCO() { return _requireTrackedSCO; } @@ -1055,6 +1058,7 @@ public boolean getRequireTrackedSCO() { * * @param flag boolean requireTrackedSCO flag */ + @Override public void setRequireTrackedSCO (boolean flag) { // RESOLVE: synchronization _requireTrackedSCO = flag; @@ -1065,7 +1069,8 @@ public void setRequireTrackedSCO (boolean flag) { * @param cls the PersistenceCapable Class * @return the Class of the ObjectId of the parameter */ - public Class getObjectIdClass(Class cls) { + @Override + public Class getObjectIdClass(Class cls) { PersistenceConfig config = loadPersistenceConfig(cls); return config.getOidClass(); } @@ -1076,6 +1081,7 @@ public Class getObjectIdClass(Class cls) { * @param sm StateManager * @return new instance of the object */ + @Override public Object newInstance(StateManager sm) { Object o = null; @@ -1083,10 +1089,10 @@ public Object newInstance(StateManager sm) { if (config == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.newinstance.badsm"));// NOI18N + "jdo.persistencemanagerimpl.newinstance.badsm")); } - Constructor constr = config.getConstructor(); + Constructor constr = config.getConstructor(); try { if (constr != null) { o = constr.newInstance(new Object[]{sm}); @@ -1097,7 +1103,7 @@ public Object newInstance(StateManager sm) { } } catch (Exception e) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.assertpersistencecapable.error", // NOI18N + "jdo.persistencemanagerimpl.assertpersistencecapable.error", config.getPersistenceCapableClass().getName()), e); } @@ -1118,6 +1124,7 @@ public Object newInstance(StateManager sm) { * @return A collection of (persistent) objects unless * an aggregate query was specified. */ + @Override public Object retrieve(RetrieveDesc action, ValueFetcher parameters) { acquireShareLock(); @@ -1143,6 +1150,7 @@ public Object retrieve(RetrieveDesc action, ValueFetcher parameters) * @return A collection of (persistent) objects unless * an aggregate query was specified. */ + @Override public Object retrieve(RetrieveDesc action) { return retrieve(action, null); } @@ -1150,7 +1158,8 @@ public Object retrieve(RetrieveDesc action) { /** * Return a RetrieveDesc given a Class object. */ - public RetrieveDesc getRetrieveDesc(Class classType) { + @Override + public RetrieveDesc getRetrieveDesc(Class classType) { acquireShareLock(); try { @@ -1165,7 +1174,8 @@ public RetrieveDesc getRetrieveDesc(Class classType) { * Return a RetrieveDesc for a foreign field (relationship) given the * Class object for the parent class. */ - public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { + @Override + public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { acquireShareLock(); try { @@ -1182,18 +1192,12 @@ public RetrieveDesc getRetrieveDesc(String fieldName, Class classType) { * at the rollback if it was replaced during transaction execution with another * instance with the same object Id. */ + @Override public void registerInstance(StateManager sm, Object oid) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - { - Object[] items = new Object[] {Thread.currentThread(), oid, this, _jta}; - logger.finest("sqlstore.persistencemgr.registerinstance",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.registerinstance", Thread.currentThread(), oid, this, _jta); try { acquireCacheLock(); - if (debug) - logger.finest("sqlstore.persistencemgr.registerinstancein_wkc"); // NOI18N + LOG.log(TRACE, "sqlstore.persistencemgr.registerinstancein_wkc"); _weakCache.put(oid, sm); @@ -1208,6 +1212,7 @@ public void registerInstance(StateManager sm, Object oid) { /** * Register instance in the transactional cache */ + @Override public void registerInstance(StateManager sm, Object oid, boolean throwDuplicateException, boolean forceRegister) { @@ -1215,11 +1220,7 @@ public void registerInstance(StateManager sm, Object oid, oid = sm.getObjectId(); } - boolean debug = logger.isLoggable(); - if (debug) { - Object[] items = new Object[] {Thread.currentThread(), oid, sm, this, _jta}; - logger.finest("sqlstore.persistencemgr.registerinstance",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.registerinstance", Thread.currentThread(), oid, sm, this, _jta); // // register in all caches @@ -1230,17 +1231,14 @@ public void registerInstance(StateManager sm, Object oid, try { acquireCacheLock(); if (!_weakCache.containsKey(oid)) { - if (debug) - logger.finest("sqlstore.persistencemgr.registerinstancein_wkc"); // NOI18N - + LOG.log(TRACE, "sqlstore.persistencemgr.registerinstancein_wkc"); _weakCache.put(oid, sm); } else if (throwDuplicateException) { - StateManager old = (StateManager)_weakCache.get(oid); + StateManager old = _weakCache.get(oid); if (_supersedeDeletedInstance && old.isDeleted()) { - if (debug) - logger.finer(I18NHelper.getMessage(messages, - "sqlstore.persistencemgr.replacingdeletedinstance", oid)); // NOI18N + LOG.log(DEBUG, + I18NHelper.getMessage(messages, "sqlstore.persistencemgr.replacingdeletedinstance", oid)); old.markNotRegistered(); old.markVerifyAtDeregister(); @@ -1261,16 +1259,14 @@ public void registerInstance(StateManager sm, Object oid, } else { throw new JDODuplicateObjectIdException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.internalmakepersistent.dups"), // NOI18N + "jdo.persistencemanagerimpl.internalmakepersistent.dups"), new Object[]{sm.getPersistent()}); } } if (_activeTransaction && (sm.isTransactional() || forceRegister)) { - if (debug) { - Object[] items = new Object[] {oid,sm.getPersistent(),this, _jta}; - logger.finest("sqlstore.persistencemgr.registerinstancein_txc",items); // NOI18N - } + Object[] items = new Object[] {oid, sm.getPersistent(), this, _jta}; + LOG.log(TRACE, "sqlstore.persistencemgr.registerinstancein_txc", items); // Need to be carefull not to request registerInstance twice // for a dirty instance. @@ -1291,17 +1287,13 @@ public void registerInstance(StateManager sm, Object oid, } } + @Override public void deregisterInstance(Object oid) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {oid,this,_jta}; - logger.finest("sqlstore.persistencemgr.deregisterinstance",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.deregisterinstance", oid, this, _jta); if (oid != null) { try { acquireCacheLock(); - StateManager sm = (StateManager) _weakCache.remove(oid); + StateManager sm = _weakCache.remove(oid); removeFromCaches(sm); } finally { releaseCacheLock(); @@ -1309,21 +1301,16 @@ public void deregisterInstance(Object oid) { } } + @Override public void deregisterInstance(Object oid, StateManager sm) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {oid,this,_jta}; - logger.finest("sqlstore.persistencemgr.deregisterinstance.verify",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.deregisterinstance.verify", oid, this, _jta); try { acquireCacheLock(); Object known = _weakCache.get(oid); if (known == sm) { //deregister the instance from weak cache only if it is registered. _weakCache.remove(oid); - if (debug) - logger.finest("sqlstore.persistencemgr.deregisterinstance.verified"); // NOI18N + LOG.log(TRACE, "sqlstore.persistencemgr.deregisterinstance.verified"); } removeFromCaches(sm); @@ -1354,10 +1341,9 @@ private void removeFromCaches(StateManager sm) { * Clean instances registered for Version Consistency are verified with * the store. */ + @Override public void beforeCompletion() { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest("sqlstore.persistencemgr.beforecompletion"); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.beforecompletion"); assertIsOpen(); assertActiveTransaction(false); @@ -1391,7 +1377,7 @@ public void beforeCompletion() { */ private void prepareToUpdate() { for (int i = 0; i < _txCache.size(); i++) { - StateManager sm = (StateManager)_txCache.get(i); + StateManager sm = _txCache.get(i); // NOTE: prepareToUpdatePhaseI has the side-effect of adding more objects // to the transaction cache. @@ -1400,10 +1386,10 @@ private void prepareToUpdate() { // We only do phase 2 and 3 during commit only. if (!_insideFlush) { - HashSet phase3sms = new HashSet(); + HashSet phase3sms = new HashSet<>(); - for (Iterator iter = _flushedCache.iterator(); iter.hasNext(); ) { - StateManager sm = (StateManager)iter.next(); + for (Iterator iter = _flushedCache.iterator(); iter.hasNext(); ) { + StateManager sm = iter.next(); // NOTE: prepareToUpdatePhaseII has the side-effect of adding state managers // to the phase3sms HashSet which need to have prepareToUpdatePhaseIII() // called on them @@ -1411,14 +1397,14 @@ private void prepareToUpdate() { sm.prepareToUpdatePhaseII(phase3sms); } - Iterator iter = phase3sms.iterator(); + Iterator iter = phase3sms.iterator(); // phase3sms should contain all the non-reachable autopersistence instance. // We need to call prepareToUpdatePhaseIII on them to make sure we roll // back any changes that may have been flushed to the datastore. while (iter.hasNext()) { - StateManager sm = (StateManager) iter.next(); + StateManager sm = iter.next(); sm.prepareToUpdatePhaseIII(); } } @@ -1432,13 +1418,13 @@ private void prepareToUpdate() { * because of circular dependencies. */ private void flushTxCache() { - List err = flushToDataStore(_txCache); + List err = flushToDataStore(_txCache); // Try to resolve dependencies. if (err != null && err.size() > 0) { - Iterator iter = err.iterator(); + Iterator iter = err.iterator(); while (iter.hasNext()) { - ((StateManager) iter.next()).resolveDependencies(); + iter.next().resolveDependencies(); } // Second flush. err = flushToDataStore(err); @@ -1447,7 +1433,7 @@ private void flushTxCache() { if (err != null && err.size() > 0) { _transaction.setRollbackOnly(); throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.notprocessed"), // NOI18N + "jdo.persistencemanagerimpl.notprocessed"), toPCArray(err)); } } @@ -1463,10 +1449,10 @@ private void flushTxCache() { * from outside. */ private void verifyFlushedCache() { - Iterator iter = _flushedCache.iterator(); + Iterator iter = _flushedCache.iterator(); while (iter.hasNext()) { - StateManager sm = (StateManager)iter.next(); + StateManager sm = iter.next(); if (sm.hasVersionConsistency() && !sm.verifyPersistent()) { Object [] items = { sm.getPersistent() }; @@ -1474,7 +1460,7 @@ private void verifyFlushedCache() { // The instance failed the verification with the data store. sm.setVerificationFailed(); throw new JDODataStoreException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.verificationfailed"), items); // NOI18N + "jdo.persistencemanagerimpl.verificationfailed"), items); } } } @@ -1489,9 +1475,9 @@ private void verifyFlushedCache() { * because of unresolved dependencies, null if all * instances could be processed. */ - static private List flushToDataStore(List flushList) { + static private List flushToDataStore(List flushList) { int size = flushList.size(); - List errorList = null; + List errorList = null; // The connection initialisation is not neccessary. There // are two conditions in TransactionImpl assuring connections @@ -1502,17 +1488,16 @@ static private List flushToDataStore(List flushList) { // transactions are not released until commit // Please refer to TransactionImpl.releaseConnection for (int i = 0; i < size; i++) { - StateManager sm = (StateManager)flushList.get(i); - StateManager smNext = - (i+1 < size)? (StateManager)flushList.get(i+1) : null; + StateManager sm = flushList.get(i); + StateManager smNext = (i + 1 < size) ? flushList.get(i + 1) : null; sm.updatePersistent(smNext); } for (int i = 0; i < size; i++) { - StateManager sm = (StateManager)flushList.get(i); + StateManager sm = flushList.get(i); if (!sm.isProcessed()) { if (errorList == null) { - errorList = new ArrayList(); + errorList = new ArrayList<>(); } // Dependencies have not been resolved. @@ -1529,13 +1514,13 @@ static private List flushToDataStore(List flushList) { * @param smList List of state managers. * @return Array of persistence capable instances. */ - static private Object[] toPCArray(List smList) { + static private Object[] toPCArray(List smList) { final int size = smList.size(); if (size > 0) { - List pcList = new ArrayList(size); + List pcList = new ArrayList<>(size); for (int i = 0; i < size; i++) { - StateManager sm = (StateManager)smList.get(i); + StateManager sm = smList.get(i); pcList.add(sm.getPersistent()); } return pcList.toArray(); @@ -1548,24 +1533,20 @@ static private Object[] toPCArray(List smList) { * cleans up transactional cache * @param status jakarta.transaction.Status */ + @Override public void afterCompletion(int status) { assertIsOpen(); _insideCommit = true; boolean abort = ((status == Status.STATUS_ROLLEDBACK) || (status == Status.STATUS_ROLLING_BACK) || (status == Status.STATUS_MARKED_ROLLBACK)); - boolean debug = false; - debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.aftercompletion",new Boolean(abort)); // NOI18N + LOG.log(TRACE, "sqlstore.persistencemgr.aftercompletion", abort); boolean retainValues = _transaction.getRetainValues(); - for (Iterator iter = _flushedCache.iterator(); iter.hasNext(); ) { - StateManager sm = (StateManager)iter.next(); - if (debug) - logger.finest("sqlstore.persistencemgr.aftercompletion.process",sm.getObjectId()); // NOI18N - + for (Iterator iter = _flushedCache.iterator(); iter.hasNext(); ) { + StateManager sm = iter.next(); + LOG.log(TRACE, "sqlstore.persistencemgr.aftercompletion.process",sm.getObjectId()); if (abort) { rollback(sm, retainValues); } else { @@ -1626,7 +1607,7 @@ private StateManager addToVersionConsistencyCache(StateManager sm) { StateManager rc = null; if (null != sm && sm.hasVersionConsistency()) { - Class pcType = sm.getPersistent().getClass(); + Class pcType = sm.getPersistent().getClass(); Object oid = sm.getObjectId(); VersionConsistencyCache vcCache = persistenceManagerFactory.getVersionConsistencyCache(); @@ -1654,7 +1635,7 @@ private StateManager removeFromVersionConsistencyCache(StateManager sm) { StateManager rc = null; if (null != sm && sm.hasVersionConsistency()) { - Class pcType = sm.getPersistent().getClass(); + Class pcType = sm.getPersistent().getClass(); Object oid = sm.getObjectId(); VersionConsistencyCache vcCache = persistenceManagerFactory.getVersionConsistencyCache(); @@ -1667,9 +1648,7 @@ private StateManager removeFromVersionConsistencyCache(StateManager sm) { return rc; } - /** - * @inheritDoc - */ + @Override public boolean initializeFromVersionConsistencyCache(StateManager sm) { boolean rc = false; StateManager nonTxSM = lookupFromVersionConsistencyCache(sm); @@ -1698,7 +1677,7 @@ private StateManager lookupFromVersionConsistencyCache(StateManager sm) { StateManager rc = null; if (null != sm && sm.hasVersionConsistency()) { - Class pcType = sm.getPersistent().getClass(); + Class pcType = sm.getPersistent().getClass(); Object oid = sm.getObjectId(); VersionConsistencyCache vcCache = persistenceManagerFactory.getVersionConsistencyCache(); @@ -1708,6 +1687,7 @@ private StateManager lookupFromVersionConsistencyCache(StateManager sm) { return rc; } + @Override public void setStateManager(Object pc, StateManager sm) { if (pc instanceof PersistenceCapable) { ((PersistenceCapable) pc).jdoSetStateManager(sm); @@ -1717,6 +1697,7 @@ public void setStateManager(Object pc, StateManager sm) { } + @Override public void setFlags(Object pc, byte flags) { if (pc instanceof PersistenceCapable) { ((PersistenceCapable) pc).jdoSetFlags(flags); @@ -1725,6 +1706,7 @@ public void setFlags(Object pc, byte flags) { //RESOLVE: Otherwise, should throw an exception. } + @Override public byte getFlags(Object pc) { if (pc instanceof PersistenceCapable) { return ((PersistenceCapable) pc).jdoGetFlags(); @@ -1734,6 +1716,7 @@ public byte getFlags(Object pc) { //RESOLVE: Otherwise, should throw an exception. } + @Override public StateManager getStateManager(Object pc) { if (pc instanceof PersistenceCapable) { return ((PersistenceCapable) pc).jdoGetStateManager(); @@ -1744,6 +1727,7 @@ public StateManager getStateManager(Object pc) { } + @Override public void setField(Object o, int fieldNumber, Object value) { if (o instanceof PersistenceCapable) { PersistenceCapable pc = (PersistenceCapable) o; @@ -1753,6 +1737,7 @@ public void setField(Object o, int fieldNumber, Object value) { //RESOLVE: Otherwise, should throw an exception. } + @Override public Object getField(Object pc, int fieldNumber) { if (pc instanceof PersistenceCapable) { return ((PersistenceCapable) pc).jdoGetField(fieldNumber); @@ -1762,6 +1747,7 @@ public Object getField(Object pc, int fieldNumber) { return null; } + @Override public void clearFields(Object pc) { if (pc instanceof PersistenceCapable) { ((PersistenceCapable) pc).jdoClear(); @@ -1779,7 +1765,8 @@ public void clearFields(Object pc) { * @param fieldName the field to notify upon changes * @return the object of the class type */ - public Object newSCOInstance(Class type, Object owner, String fieldName) { + @Override + public Object newSCOInstance(Class type, Object owner, String fieldName) { Object obj = null; if (Collection.class.isAssignableFrom(type)) { @@ -1806,7 +1793,8 @@ public Object newSCOInstance(Class type, Object owner, String fieldName) { * @param fieldName the field to notify upon changes * @return the object of the class type */ - public Object newSCOInstanceInternal(Class type, Object owner, String fieldName) { + @Override + public Object newSCOInstanceInternal(Class type, Object owner, String fieldName) { Object obj = null; @@ -1828,7 +1816,7 @@ public Object newSCOInstanceInternal(Class type, Object owner, String fieldName) } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.newscoinstance.wrongclass", // NOI18N + "jdo.persistencemanagerimpl.newscoinstance.wrongclass", type.getName())); } @@ -1854,8 +1842,9 @@ public Object newSCOInstanceInternal(Class type, Object owner, String fieldName) * @param initialSize initial size of the Collection * @return the object of the class type */ - public Object newCollectionInstance(Class type, Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialSize) { + @Override + public Object newCollectionInstance(Class type, Object owner, String fieldName, + Class elementType, boolean allowNulls, int initialSize) { Object obj = newCollectionInstanceInternal(type, owner, fieldName, elementType, allowNulls, initialSize); @@ -1878,16 +1867,18 @@ public Object newCollectionInstance(Class type, Object owner, String fieldName, * @param initialSize initial size of the Collection * @return the object of the class type */ - public Object newCollectionInstanceInternal(Class type, Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialSize) { + @Override + public Object newCollectionInstanceInternal(Class type, Object owner, String fieldName, + Class elementType, boolean allowNulls, int initialSize) { Object obj = null; // Make sure that the order of type comparison will go from // narrow to wide: if (type == HashSet.class || type == com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet.class) { - if (initialSize == 0) + if (initialSize == 0) { initialSize = 101; + } obj = new com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet( owner, fieldName, elementType, allowNulls, initialSize); /* @@ -1901,28 +1892,27 @@ public Object newCollectionInstanceInternal(Class type, Object owner, String fie newType = com.sun.jdo.spi.persistence.support.sqlstore.sco.Vector.class; */ } else if (Set.class.isAssignableFrom(type)) { - if (initialSize == 0) + if (initialSize == 0) { initialSize = 101; + } obj = new com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet( owner, fieldName, elementType, allowNulls, initialSize); } else if (Collection.class.isAssignableFrom(type)) { // We choose to use HashSet as a default collection // because we do not support duplicate objects in DB - if (initialSize == 0) + if (initialSize == 0) { initialSize = 101; + } obj = new com.sun.jdo.spi.persistence.support.sqlstore.sco.HashSet( owner, fieldName, elementType, allowNulls, initialSize); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.newscoinstance.wrongclass", // NOI18N + "jdo.persistencemanagerimpl.newscoinstance.wrongclass", type.getName())); } - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.newcollection",obj.getClass()); // NOI18N - + LOG.log(TRACE, "sqlstore.persistencemgr.newcollection",obj.getClass()); return obj; } @@ -1932,6 +1922,7 @@ public Object newCollectionInstanceInternal(Class type, Object owner, String fie * flush * @see #beforeCompletion() */ + @Override public void internalFlush() { acquireExclusiveLock(); @@ -1959,7 +1950,7 @@ public void internalFlush() { //_transaction.rollback(); } else { for (int i = 0; i < _txCache.size(); i++) { - StateManager sm = (StateManager)_txCache.get(i); + StateManager sm = _txCache.get(i); sm.flushed(); } } @@ -1977,6 +1968,7 @@ public void internalFlush() { * For Transaction to notify PersistenceManager that * status is changed */ + @Override public synchronized void notifyStatusChange(boolean isActive) { _activeTransaction = isActive; } @@ -1985,6 +1977,7 @@ public synchronized void notifyStatusChange(boolean isActive) { * For Transaction to notify PersistenceManager that * optimistic flag is changed */ + @Override public synchronized void notifyOptimistic(boolean optimistic) { this._optimistic = optimistic; } @@ -1992,11 +1985,9 @@ public synchronized void notifyOptimistic(boolean optimistic) { /** * Returns true if associated transaction is optimistic */ + @Override public boolean isOptimisticTransaction() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.isoptimistic", new Boolean(_optimistic)); // NOI18N - + LOG.log(TRACE, "sqlstore.persistencemgr.isoptimistic", _optimistic); return _optimistic; } @@ -2005,6 +1996,7 @@ public boolean isOptimisticTransaction() { * For Transaction to notify PersistenceManager that * nontransactionalRead flag is changed */ + @Override public synchronized void notifyNontransactionalRead(boolean nontransactionalRead) { this._nontransactionalRead = nontransactionalRead; } @@ -2012,12 +2004,9 @@ public synchronized void notifyNontransactionalRead(boolean nontransactionalRead /** * Returns true if associated transaction is optimistic */ + @Override public boolean isNontransactionalRead() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - logger.finest("sqlstore.persistencemgr.isnontxread",new Boolean(_nontransactionalRead)); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.isnontxread", _nontransactionalRead); return _nontransactionalRead; } @@ -2025,21 +2014,16 @@ public boolean isNontransactionalRead() { /** * Returns true if associated transaction is active */ + @Override public boolean isActiveTransaction() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.isactivetx",new Boolean(_activeTransaction)); // NOI18N - + LOG.log(TRACE, "sqlstore.persistencemgr.isactivetx", _activeTransaction); return _activeTransaction; } // Returns current wrapper + @Override public PersistenceManagerWrapper getCurrentWrapper() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - logger.finest("sqlstore.persistencemgr.getcurrentwrapper",current); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.getcurrentwrapper", current); return current; } @@ -2049,23 +2033,13 @@ public PersistenceManagerWrapper getCurrentWrapper() { // Remember the current wrapper protected void pushCurrentWrapper(PersistenceManagerWrapper pmw) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {current,pmw}; - logger.finest("sqlstore.persistencemgr.pushcurrentwrapper",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.pushcurrentwrapper", current, pmw); current = pmw; } // Replace current wrapper with the previous protected void popCurrentWrapper(PersistenceManagerWrapper prev) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {current,prev}; - logger.finest("sqlstore.persistencemgr.popcurrentwrapper",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.popcurrentwrapper", current, prev); current = prev; if (!_isClosed && _jta == null && current == null) { this.close(); @@ -2080,7 +2054,7 @@ protected void setJTATransaction(jakarta.transaction.Transaction t) { if (this._jta != null) { Object[] items = new Object[] {this._jta, t}; throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.setjtatransaction.notnulljta", // NOI18N + "jdo.persistencemanagerimpl.setjtatransaction.notnulljta", items)); } this._jta = t; @@ -2104,9 +2078,9 @@ private void registerQuery(QueryImpl q) */ private void disconnectQueries() { - for (Iterator i = queries.iterator(); i.hasNext();) + for (Iterator i = queries.iterator(); i.hasNext();) { - QueryImpl q = (QueryImpl)i.next(); + QueryImpl q = i.next(); q.clearPersistenceManager(); } queries.clear(); @@ -2173,11 +2147,11 @@ private void internalMakePersistent(PersistenceCapable pc) { if (this != pc.jdoGetStateManager().getPersistenceManagerInternal()) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.another_pm"), // NOI18N + "jdo.persistencemanagerimpl.another_pm"), new Object[]{pc}); } } else { - Class classType = pc.getClass(); + Class classType = pc.getClass(); loadPersistenceConfig(classType); sm = _store.getStateManager(classType); } @@ -2192,7 +2166,7 @@ private void internalMakePersistent(PersistenceCapable pc) { private void internalDeletePersistent(PersistenceCapable pc) { if (!(pc.jdoIsPersistent())) { throw new JDOException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.internaldeletepersistent.transient"), // NOI18N + "jdo.persistencemanagerimpl.internaldeletepersistent.transient"), new Object[]{pc}); } @@ -2201,7 +2175,7 @@ private void internalDeletePersistent(PersistenceCapable pc) { if (this != pm) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.another_pm"), // NOI18N + "jdo.persistencemanagerimpl.another_pm"), new Object[]{pc}); } @@ -2218,9 +2192,9 @@ private void internalDeletePersistent(PersistenceCapable pc) { * @param oid the Oid * @return classtype for the owning Class */ - private Class loadClassForOid(Object oid) { - Class oidClass = oid.getClass(); - Class classType = _store.getClassByOidClass(oidClass); + private Class loadClassForOid(Object oid) { + Class oidClass = oid.getClass(); + Class classType = _store.getClassByOidClass(oidClass); if (classType != null) { // Found in the DataStore return classType; @@ -2258,12 +2232,8 @@ private void loadByName(String s, ClassLoader classLoader) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.loadingclass",s); // NOI18N - - - Class oidClass = null; + LOG.log(TRACE, "sqlstore.persistencemgr.loadingclass", s); + Class oidClass = null; try { // take current class loader if not specified @@ -2274,7 +2244,7 @@ private void loadByName(String s, ClassLoader classLoader) { } catch (Exception e) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.loadclassforoid.wrongoidclass"), e);// NOI18N + "jdo.persistencemanagerimpl.loadclassforoid.wrongoidclass"), e); } loadPersistenceConfig(oidClass); @@ -2285,12 +2255,9 @@ private void loadByName(String s, ClassLoader classLoader) { */ private void assertIsOpen() { if (_isClosed) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - logger.finest("sqlstore.persistencemgr.assertisopen",this); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.assertisopen", this); throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.assertclosed.closed"));// NOI18N + "jdo.persistencemanagerimpl.assertclosed.closed")); } } @@ -2298,23 +2265,15 @@ private void assertIsOpen() { * assert that the associated Transaction is active but allows to do commit processing. */ private void assertActiveTransaction(boolean insideQuery) { - boolean debug = false; - - debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - logger.finest("sqlstore.persistencemgr.assertactivetx",_transaction); // NOI18N - } - - if (_insideCommit || (insideQuery && _transaction.getNontransactionalRead())) + LOG.log(TRACE, "sqlstore.persistencemgr.assertactivetx",_transaction); + if (_insideCommit || (insideQuery && _transaction.getNontransactionalRead())) { return; + } if (!_activeTransaction) { - if (debug) { - logger.finest("sqlstore.persistencemgr.assertactivetx.closed",this); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.assertactivetx.closed", this); throw new JDOException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.assertactivetransaction.error"));// NOI18N + "jdo.persistencemanagerimpl.assertactivetransaction.error")); } } @@ -2324,7 +2283,7 @@ private void assertActiveTransaction(boolean insideQuery) { private void assertPersistenceCapable(Object pc) { if (!(pc instanceof PersistenceCapable)) { throw new JDOException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.assertpersistencecapable.error", // NOI18N + "jdo.persistencemanagerimpl.assertpersistencecapable.error", pc.getClass().getName()), new Object[]{pc}); } } @@ -2336,8 +2295,9 @@ private void assertPersistenceCapable(Object pc) { */ private void setKeyFields(StateManager sm) { Object o = sm.getPersistent(); - if (o == null) + if (o == null) { return; + } Object oid = sm.getObjectId(); try { @@ -2351,14 +2311,11 @@ private void setKeyFields(StateManager sm) { } } catch (Exception e) { - //e.printStackTrace(); - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) - logger.finest("sqlstore.persistencemgr.setkeyfields",e); // NOI18N + LOG.log(TRACE, "sqlstore.persistencemgr.setkeyfields", e); } } - private PersistenceConfig loadPersistenceConfig(Class classType) { + private PersistenceConfig loadPersistenceConfig(Class classType) { return _store.getPersistenceConfig(classType); } @@ -2369,19 +2326,18 @@ private PersistenceConfig loadPersistenceConfig(Class classType) { * @return object local copy */ private Object internalCloneOid(Object oid, StateManager sm) { - if (oid == null) + if (oid == null) { return null; + } if (!_requireCopyObjectId) { return oid; } - boolean debug = logger.isLoggable(Logger.FINEST); - Object newoid = null; try { - Class oidClass = oid.getClass(); - newoid = oidClass.newInstance(); + Class oidClass = oid.getClass(); + newoid = oidClass.getDeclaredConstructor().newInstance(); PersistenceConfig config = sm.getPersistenceConfig(); Field keyFields[] = config.getKeyFields(); @@ -2392,18 +2348,11 @@ private Object internalCloneOid(Object oid, StateManager sm) { } } catch (Exception e) { - //e.printStackTrace(); - if (debug) - logger.finest("sqlstore.persistencemgr.internalcloneoid",e); // NOI18N + LOG.log(TRACE, "sqlstore.persistencemgr.internalcloneoid",e); newoid = null; } - if (debug) - { - Object[] items = new Object[] {oid , newoid, new Boolean((oid == newoid))}; - logger.finest("sqlstore.persistencemgr.internalcloneoid.old",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.internalcloneoid.old", oid, newoid, oid == newoid); return newoid; } @@ -2412,13 +2361,12 @@ private Object internalCloneOid(Object oid, StateManager sm) { * Acquires a share lock from the persistence manager. This method will * put the calling thread to sleep if another thread is holding the exclusive lock. */ + @Override public void acquireShareLock() { if ( ! _multithreaded) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - synchronized (_readWriteLock) { // // If the current thread is already holding the exclusive lock, @@ -2439,14 +2387,11 @@ public void acquireShareLock() { _waiterCount++; try { - if (debug) { - logger.finest("sqlstore.persistencemgr.acquiresharedlock",Thread.currentThread()); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.acquiresharedlock",Thread.currentThread()); _readWriteLock.wait(); } catch (InterruptedException e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.acquiresharelock.interrupted"), e);// NOI18N + "jdo.persistencemanagerimpl.acquiresharelock.interrupted"), e); } finally { _waiterCount--; } @@ -2471,14 +2416,12 @@ public void acquireShareLock() { } _readWriteCount++; - if (debug) { - logger.finest("sqlstore.persistencemgr.acquiresharedlock.rdwrcount", // NOI18N - Thread.currentThread(),new Long(_readWriteCount)); - } + LOG.log(TRACE, "sqlstore.persistencemgr.acquiresharedlock.rdwrcount", Thread.currentThread(), + _readWriteCount); if (_readWriteCount <= 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.acquiresharelock.failed"));// NOI18N + "jdo.persistencemanagerimpl.acquiresharelock.failed")); } } } @@ -2487,14 +2430,12 @@ public void acquireShareLock() { * Releases the share lock and notify any thread waiting to get an exclusive lock. * Note that every releaseShareLock() call needs to be preceeded by an acquireShareLock() call. */ + @Override public void releaseShareLock() { if ( ! _multithreaded) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - - synchronized (_readWriteLock) { // // If the current thread is already holding the exclusive lock, @@ -2509,7 +2450,7 @@ public void releaseShareLock() { try { if (_readWriteCount == 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.releasesharelock.failed"));// NOI18N + "jdo.persistencemanagerimpl.releasesharelock.failed")); } _readWriteCount--; @@ -2523,10 +2464,7 @@ public void releaseShareLock() { _readWriteLock.notify(); } - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),new Long(_readWriteCount)}; - logger.finest("sqlstore.persistencemgr.releasesharedlock",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.releasesharedlock", Thread.currentThread(), _readWriteCount); } } } @@ -2539,13 +2477,12 @@ public void releaseShareLock() { * attempts to acquire an exclusive lock. It is up to the callers to make sure * this does not happen. */ + @Override public void acquireExclusiveLock() { if ( ! _multithreaded) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - synchronized (_readWriteLock) { Thread currentThread = Thread.currentThread(); @@ -2566,15 +2503,11 @@ public void acquireExclusiveLock() { _waiterCount++; try { - - if (debug) { - logger.finest("sqlstore.persistencemgr.acquireexclusivelock",currentThread); // NOI18N - } - + LOG.log(TRACE, "sqlstore.persistencemgr.acquireexclusivelock", currentThread); _readWriteLock.wait(); } catch (InterruptedException e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.acquireexclusivelock.interrupted"), e);// NOI18N + "jdo.persistencemanagerimpl.acquireexclusivelock.interrupted"), e); } finally { _waiterCount--; } @@ -2600,11 +2533,7 @@ public void acquireExclusiveLock() { _readWriteCount = -1; _exclusiveLockHolder = currentThread; - if (debug) { - Object[] items = new Object[] {currentThread,new Long(_readWriteCount)}; - logger.fine("sqlstore.persistencemgr.acquireexclusivelock.count",items); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.persistencemgr.acquireexclusivelock.count", currentThread, _readWriteCount); } } } @@ -2614,27 +2543,22 @@ public void acquireExclusiveLock() { * share lock. Note that every releaseShareLock() call needs to be preceeded by * an acquireExclusiveLock() call. */ + @Override public void releaseExclusiveLock() { if ( ! _multithreaded) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); - - synchronized (_readWriteLock) { try { if (_readWriteCount >= 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.releaseexclusivelock.failed"));// NOI18N + "jdo.persistencemanagerimpl.releaseexclusivelock.failed")); } _readWriteCount++; } finally { - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),new Long(_readWriteCount)}; - logger.finest("sqlstore.persistencemgr.releaseexclusivelock",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.persistencemgr.releaseexclusivelock", Thread.currentThread(), _readWriteCount); // // If _readWriteCount is 0 and _waiterCount is greater than 0, @@ -2654,6 +2578,7 @@ public void releaseExclusiveLock() { /** * Acquire lock for synchronizing field updates. */ + @Override public void acquireFieldUpdateLock() { _fieldUpdateLock.acquire(); } @@ -2661,6 +2586,7 @@ public void acquireFieldUpdateLock() { /** * Release lock for synchronizing field updates. */ + @Override public void releaseFieldUpdateLock() { _fieldUpdateLock.release(); } @@ -2668,12 +2594,14 @@ public void releaseFieldUpdateLock() { /** * Lock cache for getObjectById and result processing synchronization. */ + @Override public void acquireCacheLock() { _cacheLock.acquire(); } /** Release cache lock. */ + @Override public void releaseCacheLock() { _cacheLock.release(); } @@ -2697,6 +2625,7 @@ public ExtensionFilter(String ext) { * @param name the name of the file * @return true if the name should be included in the file list */ + @Override public boolean accept(File dir, String name) { return name.endsWith(ext); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerWrapper.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerWrapper.java index 9a38e42b70e..18decdb1725 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerWrapper.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/PersistenceManagerWrapper.java @@ -52,7 +52,7 @@ public class PersistenceManagerWrapper implements PersistenceManager { * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", PersistenceManagerWrapper.class.getClassLoader()); // Constructed by com.sun.jdo.spi.persistence.support.sqlstore.SQLPersistenceManagerFactory @@ -67,6 +67,7 @@ public class PersistenceManagerWrapper implements PersistenceManager { * @return if this PersistenceManager has been closed * @see #close() */ + @Override public boolean isClosed() { if (isValid) { return pm.isClosed(); @@ -80,6 +81,7 @@ public boolean isClosed() { *

    This method closes the PersistenceManager, which if pooled, releases it * to the pool of available PersistenceManagers. */ + @Override public void close() { if (isValid) { isValid = false; @@ -88,7 +90,7 @@ public void close() { prev = null; } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -96,24 +98,26 @@ public void close() { * @return the Transaction associated with this * PersistenceManager. */ + @Override public Transaction currentTransaction() { if (isValid) { return pm.currentTransaction(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } /** Create a new Query with no elements. * @return a new Query instance with no elements. */ + @Override public Query newQuery() { if (isValid) { return pm.newQuery(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -124,12 +128,13 @@ public Query newQuery() { * @return the new Query * @param compiled another Query from the same JDO implementation */ + @Override public Query newQuery(Object compiled) { if (isValid) { return pm.newQuery(compiled); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -137,12 +142,13 @@ public Query newQuery(Object compiled) { * @param cls the Class of the results * @return the new Query */ - public Query newQuery(Class cls) { + @Override + public Query newQuery(Class cls) { if (isValid) { return pm.newQuery(cls); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -152,12 +158,13 @@ public Query newQuery(Class cls) { * @param cln the Collection of candidate instances * @return the new Query */ - public Query newQuery(Class cls, Collection cln) { + @Override + public Query newQuery(Class cls, Collection cln) { if (isValid) { return pm.newQuery(cls, cln); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -167,12 +174,13 @@ public Query newQuery(Class cls, Collection cln) { * @param filter the Filter for candidate instances * @return the new Query */ - public Query newQuery(Class cls, String filter) { + @Override + public Query newQuery(Class cls, String filter) { if (isValid) { return pm.newQuery(cls, filter); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -183,12 +191,13 @@ public Query newQuery(Class cls, String filter) { * @param filter the Filter for candidate instances * @return the new Query */ - public Query newQuery(Class cls, Collection cln, String filter) { + @Override + public Query newQuery(Class cls, Collection cln, String filter) { if (isValid) { return pm.newQuery(cls, cln, filter); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -201,12 +210,13 @@ public Query newQuery(Class cls, Collection cln, String filter) { * @return a Collection of instances * @see Query */ - public Collection getExtent(Class persistenceCapableClass, boolean subclasses) { + @Override + public Collection getExtent(Class persistenceCapableClass, boolean subclasses) { if (isValid) { return pm.getExtent(persistenceCapableClass, subclasses); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -222,12 +232,13 @@ public Collection getExtent(Class persistenceCapableClass, boolean subclasses) { * @return the PersistenceCapable instance with the specified * ObjectId */ + @Override public Object getObjectById(Object oid) { if (isValid) { return pm.getObjectById(oid); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -256,12 +267,13 @@ public Object getObjectById(Object oid) { * @param oid an ObjectId * @param validate if the existence of the instance is to be validated */ + @Override public Object getObjectById (Object oid, boolean validate) { if (isValid) { return pm.getObjectById(oid, validate); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -272,12 +284,13 @@ public Object getObjectById (Object oid, boolean validate) { * @param pc the PersistenceCapable instance * @return the ObjectId of the instance */ + @Override public Object getObjectId(Object pc) { if (isValid) { return pm.getObjectId(pc); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -288,12 +301,13 @@ public Object getObjectId(Object pc) { * @return the PersistenceCapable instance representing the * same data store object */ + @Override public Object getTransactionalInstance(Object pc) { if (isValid) { return pm.getTransactionalInstance(pc); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -306,12 +320,13 @@ public Object getTransactionalInstance(Object pc) { * @param pc a transient instance of a Class that implements * PersistenceCapable */ + @Override public void makePersistent(Object pc) { if (isValid) { pm.makePersistent(pc); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -319,12 +334,13 @@ public void makePersistent(Object pc) { * @param pcs an array of transient instances * @see #makePersistent(Object pc) */ + @Override public void makePersistent(Object[] pcs) { if (isValid) { pm.makePersistent(pcs); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -332,12 +348,13 @@ public void makePersistent(Object[] pcs) { * @param pcs a Collection of transient instances * @see #makePersistent(Object pc) */ - public void makePersistent(Collection pcs) { + @Override + public void makePersistent(Collection pcs) { if (isValid) { pm.makePersistent(pcs); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -353,12 +370,13 @@ public void makePersistent(Collection pcs) { * * @param pc a persistent instance */ + @Override public void deletePersistent(Object pc) { if (isValid) { pm.deletePersistent(pc); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -366,12 +384,13 @@ public void deletePersistent(Object pc) { * @param pcs a Collection of persistent instances * @see #deletePersistent(Object pc) */ + @Override public void deletePersistent(Object[] pcs) { if (isValid) { pm.deletePersistent(pcs); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -379,12 +398,13 @@ public void deletePersistent(Object[] pcs) { * @param pcs a Collection of persistent instances * @see #deletePersistent(Object pc) */ - public void deletePersistent(Collection pcs) { + @Override + public void deletePersistent(Collection pcs) { if (isValid) { pm.deletePersistent(pcs); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -394,12 +414,13 @@ public void deletePersistent(Collection pcs) { * @return the PersistenceManagerFactory that created * this PersistenceManager */ + @Override public PersistenceManagerFactory getPersistenceManagerFactory() { if (isValid) { return pm.getPersistenceManagerFactory(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -409,12 +430,13 @@ public PersistenceManagerFactory getPersistenceManagerFactory() { * @param o the user instance to be remembered by the PersistenceManager * @see #getUserObject */ + @Override public void setUserObject(Object o) { if (isValid) { pm.setUserObject(o); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -424,12 +446,13 @@ public void setUserObject(Object o) { * @return the user object associated with this PersistenceManager * @see #setUserObject */ + @Override public Object getUserObject() { if (isValid) { return pm.getUserObject(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -441,12 +464,13 @@ public Object getUserObject() { *

  • VersionNumber
  • * @return the Properties of this PersistenceManager */ + @Override public Properties getProperties() { if (isValid) { return pm.getProperties(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -457,12 +481,13 @@ public Properties getProperties() { * Object Id. * @return boolean supersedeDeletedInstance flag */ + @Override public boolean getSupersedeDeletedInstance () { if (isValid) { return pm.getSupersedeDeletedInstance(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -471,12 +496,13 @@ public boolean getSupersedeDeletedInstance () { * Sets the supersedeDeletedInstance flag for this PersistenceManager. * @param flag boolean supersedeDeletedInstance flag */ + @Override public void setSupersedeDeletedInstance (boolean flag) { if (isValid) { pm.setSupersedeDeletedInstance(flag); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -490,12 +516,13 @@ public void setSupersedeDeletedInstance (boolean flag) { * @see PersistenceManager#getObjectById(Object oid) * @return boolean requireCopyObjectId flag */ + @Override public boolean getRequireCopyObjectId() { if (isValid) { return pm.getRequireCopyObjectId(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -510,12 +537,13 @@ public boolean getRequireCopyObjectId() { * @see PersistenceManager#getObjectById(Object oid) * @param flag boolean requireCopyObjectId flag */ + @Override public void setRequireCopyObjectId (boolean flag) { if (isValid) { pm.setRequireCopyObjectId(flag); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -528,12 +556,13 @@ public void setRequireCopyObjectId (boolean flag) { * * @return boolean requireTrackedSCO flag */ + @Override public boolean getRequireTrackedSCO() { if (isValid) { return pm.getRequireTrackedSCO(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -545,12 +574,13 @@ public boolean getRequireTrackedSCO() { * * @param flag boolean requireTrackedSCO flag */ + @Override public void setRequireTrackedSCO (boolean flag) { if (isValid) { pm.setRequireTrackedSCO(flag); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -560,12 +590,13 @@ public void setRequireTrackedSCO (boolean flag) { * @param cls the PersistenceCapable Class * @return the Class of the ObjectId of the parameter */ - public Class getObjectIdClass(Class cls) { + @Override + public Class getObjectIdClass(Class cls) { if (isValid) { return pm.getObjectIdClass(cls); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -581,12 +612,13 @@ public Class getObjectIdClass(Class cls) { * @param fieldName the field to notify upon changes * @return the object of the class type */ - public Object newSCOInstance(Class type, Object owner, String fieldName) { + @Override + public Object newSCOInstance(Class type, Object owner, String fieldName) { if (isValid) { return pm.newSCOInstance(type, owner, fieldName); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } @@ -607,18 +639,19 @@ public Object newSCOInstance(Class type, Object owner, String fieldName) { * @param initialSize initial size of the Collection * @return the object of the class type */ - public Object newCollectionInstance(Class type, Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialSize) { + @Override + public Object newCollectionInstance(Class type, Object owner, String fieldName, + Class elementType, boolean allowNulls, int initialSize) { if (isValid) { return pm.newCollectionInstance(type, owner, fieldName, elementType, allowNulls, initialSize); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerwrapper.invalidpm"));// NOI18N + "jdo.persistencemanagerwrapper.invalidpm")); } } public PersistenceManager getPersistenceManager() { - return (PersistenceManager) pm; + return pm; } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/SQLPersistenceManagerFactory.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/SQLPersistenceManagerFactory.java index 29f887a7714..e8c3131b18c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/SQLPersistenceManagerFactory.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/SQLPersistenceManagerFactory.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, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -24,15 +24,16 @@ import com.sun.jdo.api.persistence.support.JDOUserException; import com.sun.jdo.api.persistence.support.PersistenceManager; import com.sun.jdo.api.persistence.support.PersistenceManagerFactory; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperPersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceStore; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStoreManager; import com.sun.jdo.spi.persistence.support.sqlstore.VersionConsistencyCache; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.EJBHelper; import com.sun.jdo.spi.persistence.utility.BucketizedHashtable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; + +import jakarta.transaction.Transaction; import java.io.PrintWriter; +import java.lang.System.Logger; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; @@ -44,32 +45,25 @@ import org.glassfish.api.naming.SimpleJndiName; import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; + /** * @author Marina Vatkina 2000 */ public class SQLPersistenceManagerFactory implements com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManagerFactory { - private PersistenceStore _store; - private ConnectionFactory _connectionFactory; - private Object _dataSource; - private PersistenceManagerFactory _persistenceManagerFactory; - - /** Pooling size */ - private int minPool; - private int maxPool; - - /** - * The logger - */ - private static Logger logger = LogHelperPersistenceManager.getLogger(); - /** * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", //NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", SQLPersistenceManagerFactory.class.getClassLoader()); + /** + * The logger + */ + private static final Logger LOG = System.getLogger(SQLPersistenceManagerFactory.class.getName(), messages); /** * bucket size for Transactional cache of PersistenceManager instances @@ -83,27 +77,33 @@ public class SQLPersistenceManagerFactory static { pmCacheBucketSize = Integer.getInteger( - "com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.pmCacheBucketSize", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.pmCacheBucketSize", 11).intValue(); pmCacheInitialCapacity = Integer.getInteger( - "com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.pmCacheInitialCapacity", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.impl.SQLPersistenceManagerFactory.pmCacheInitialCapacity", 11 * pmCacheBucketSize).intValue(); - if (logger.isLoggable(Logger.FINEST)) { - logger.finest( - "sqlstore.sqlpersistencemgrfactory.pmCacheBucketSize", // NOI18N + LOG.log(TRACE, + "sqlstore.sqlpersistencemgrfactory.pmCacheBucketSize", String.valueOf(pmCacheBucketSize)); - logger.finest( - "sqlstore.sqlpersistencemgrfactory.pmCacheInitialCapacity", // NOI18N + LOG.log(TRACE, + "sqlstore.sqlpersistencemgrfactory.pmCacheInitialCapacity", String.valueOf(pmCacheInitialCapacity)); - } } /** * Transactional cache of PersistenceManager instances */ - private final Map pmCache = new BucketizedHashtable(pmCacheBucketSize, pmCacheInitialCapacity); + private final Map pmCache = new BucketizedHashtable<>(pmCacheBucketSize, pmCacheInitialCapacity); + private PersistenceStore _store; + private ConnectionFactory _connectionFactory; + private Object _dataSource; + private PersistenceManagerFactory _persistenceManagerFactory; + + /** Pooling size */ + private int minPool; + private int maxPool; /** * Cache of StateManager instances that support version consistency @@ -160,7 +160,7 @@ public SQLPersistenceManagerFactory( @Override public void setConnectionUserName(String userName) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -179,7 +179,7 @@ public String getConnectionUserName() { @Override public void setConnectionPassword(char[] password) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -189,7 +189,7 @@ public void setConnectionPassword(char[] password) { @Override public void setConnectionURL(String url) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -209,7 +209,7 @@ public String getConnectionURL() { @Override public void setConnectionDriverName(String driverName) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -229,7 +229,7 @@ public String getConnectionDriverName() { @Override public void setConnectionFactory(Object cf) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -252,7 +252,7 @@ public Object getConnectionFactory() { @Override public void setOptimistic(boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -271,7 +271,7 @@ public boolean getOptimistic() { @Override public void setRetainValues(boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -291,7 +291,7 @@ public boolean getRetainValues() { @Override public void setNontransactionalRead(boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -313,7 +313,7 @@ public boolean getNontransactionalRead() { @Override public void setIgnoreCache(boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -334,7 +334,7 @@ public boolean getIgnoreCache() { @Override public void setQueryTimeout(int timeout) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -354,7 +354,7 @@ public int getQueryTimeout() { @Override public void setConnectionMaxPool(int MaxPool) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -373,7 +373,7 @@ public int getConnectionMaxPool() { @Override public void setConnectionMinPool(int MinPool) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -393,7 +393,7 @@ public int getConnectionMinPool() { @Override public void setConnectionMsWait(int MsWait) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -416,7 +416,7 @@ public int getConnectionMsWait() { @Override public void setConnectionMsInterval(int MsInterval) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -437,7 +437,7 @@ public int getConnectionMsInterval() { @Override public void setConnectionLoginTimeout(int LoginTimeout) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -457,7 +457,7 @@ public int getConnectionLoginTimeout() { @Override public void setConnectionLogWriter(PrintWriter pw) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -480,7 +480,7 @@ public PrintWriter getConnectionLogWriter() { @Override public void setConnectionTransactionIsolation(int level) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -499,7 +499,7 @@ public int getConnectionTransactionIsolation() { @Override public void setConnectionFactoryName(SimpleJndiName connectionFactoryName) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -518,7 +518,7 @@ public SimpleJndiName getConnectionFactoryName() { @Override public void setIdentifier(String identifier) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -547,7 +547,7 @@ public int getMaxPool() { @Override public void setMaxPool(int MaxPool) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -567,7 +567,7 @@ public int getMinPool() { @Override public void setMinPool(int MinPool) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } @@ -579,7 +579,7 @@ public void setMinPool(int MinPool) { @Override public void setUpdateTimeout(int timeout) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -612,7 +612,7 @@ public boolean getSupersedeDeletedInstance () { @Override public void setSupersedeDeletedInstance (boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -643,7 +643,7 @@ public boolean getRequireCopyObjectId() { @Override public void setRequireCopyObjectId (boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -671,7 +671,7 @@ public boolean getRequireTrackedSCO() { @Override public void setRequireTrackedSCO (boolean flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.notsupported")); //NOI18N + "jdo.persistencemanagerfactoryimpl.notsupported")); } /** @@ -695,26 +695,19 @@ public PersistenceManager getPersistenceManager() { */ @Override public PersistenceManager getPersistenceManager(String username, char[] password) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (_connectionFactory == null && _dataSource == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.getpersistencemanager.notconfigured"));// NOI18N + "jdo.persistencemanagerfactoryimpl.getpersistencemanager.notconfigured")); } - if (debug) { - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr",Thread.currentThread()); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr",Thread.currentThread()); // Check if we are in managed environment and PersistenceManager is cached PersistenceManagerImpl pm = null; - jakarta.transaction.Transaction t = EJBHelper.getTransaction(); + Transaction t = EJBHelper.getTransaction(); if (t != null) { - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),t}; - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr.found",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr.found", Thread.currentThread(), t); pm = (PersistenceManagerImpl) pmCache.get(t); if (pm == null) { @@ -722,12 +715,10 @@ public PersistenceManager getPersistenceManager(String username, char[] password pm = getFromPool(t, username, password); pmCache.put(t, pm); } else if(pm.isClosed()) { - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),t}; - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr.pmclosedfor",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr.pmclosedfor", + Thread.currentThread(), t); throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.getpersistencemanager.closed", // NOI18N + "jdo.persistencemanagerfactoryimpl.getpersistencemanager.closed", t)); } @@ -737,9 +728,7 @@ public PersistenceManager getPersistenceManager(String username, char[] password com.sun.jdo.spi.persistence.support.sqlstore.Transaction tx = (com.sun.jdo.spi.persistence.support.sqlstore.Transaction) pm.currentTransaction(); - if (debug) { - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr.jdotx",tx); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr.jdotx",tx); if (!tx.isActive()) { tx.begin(t); @@ -748,22 +737,17 @@ public PersistenceManager getPersistenceManager(String username, char[] password if (!(pm.verify(username, password))) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.getpersistencemanager.error")); // NOI18N + "jdo.persistencemanagerfactoryimpl.getpersistencemanager.error")); } } else { - if (debug) { - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr.jdotx.notfound"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr.jdotx.notfound"); // We don't know if we are in the managed environment or not // If Yes, it is BMT with JDO Transaction and it will register // itself at the begin(). pm = getFromPool(null, username, password); } - if (debug) { - Object[] items = new Object[] {Thread.currentThread(),pm,t}; - logger.finest("sqlstore.sqlpersistencemgrfactory.getpersistencemgr.pmt",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getpersistencemgr.pmt", Thread.currentThread(), pm, t); // Always return a wrapper return new PersistenceManagerWrapper(pm); @@ -797,12 +781,8 @@ public void registerPersistenceManager( com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager pm, jakarta.transaction.Transaction t) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {pm,t}; - logger.finest("sqlstore.sqlpersistencemgrfactory.registerpersistencemgr.pmt",items); // NOI18N - } - PersistenceManager pm1 = (PersistenceManager) pmCache.get(t); + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.registerpersistencemgr.pmt", pm,t); + PersistenceManager pm1 = pmCache.get(t); // double-check locking has been removed if (pm1 == null) { pmCache.put(t, pm); @@ -810,13 +790,13 @@ public void registerPersistenceManager( return; } - if (pm1 != pm) { + if (pm1 == pm) { + // do nothing ??? + } else { Object[] items = new Object[] {t, pm1}; throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.registerpm.registered", // NOI18N + "jdo.persistencemanagerfactoryimpl.registerpm.registered", items)); - } else { - // do nothing ??? } } @@ -827,10 +807,7 @@ public void registerPersistenceManager( private PersistenceManagerImpl getFromPool(jakarta.transaction.Transaction tx, String username, char[] password) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - logger.finest("sqlstore.sqlpersistencemgrfactory.getfrompool"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getfrompool"); synchronized (this) { if (_store == null) { @@ -841,11 +818,7 @@ private PersistenceManagerImpl getFromPool(jakarta.transaction.Transaction tx, // create new PersistenceManager object and set its atributes PersistenceManagerImpl pm = new PersistenceManagerImpl(this, tx, username, password); pm.setStore(_store); - if (debug) { - Object[] items = new Object[] {pm,tx}; - logger.finest("sqlstore.sqlpersistencemgrfactory.getfrompool.pmt",items); // NOI18N - } - + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.getfrompool.pmt", pm, tx); return pm; } @@ -855,7 +828,7 @@ private PersistenceManagerImpl getFromPool(jakarta.transaction.Transaction tx, */ private void returnToPool(PersistenceManager pm) { // do nothing for now - logger.finest("sqlstore.sqlpersistencemgrfactory.returnToPool"); // NOI18N + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.returnToPool"); } /** Releases closed PersistenceManager that is not in use @@ -865,32 +838,27 @@ public void releasePersistenceManager(com.sun.jdo.spi.persistence.support.sqlsto jakarta.transaction.Transaction t) { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {pm,t}; - logger.finest("sqlstore.sqlpersistencemgrfactory.releasepm.pmt",items); // NOI18N - - } + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.releasepm.pmt", pm, t); - if (t != null) { + if (t == null) { + returnToPool(pm); + } else { // Managed environment // Deregister only - PersistenceManager pm1 = (PersistenceManager) pmCache.get(t); - if (pm1 == null || pm1 != pm) { + PersistenceManager pm1 = pmCache.get(t); + if (pm1 != null && pm1 == pm) { + pmCache.remove(t); + } else { Object[] items = new Object[] {t, pm1}; throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.registerpm.registered", // NOI18N + "jdo.persistencemanagerfactoryimpl.registerpm.registered", items)); - } else { - pmCache.remove(t); } - } else { - returnToPool(pm); } } private void initialize() { - logger.finest("sqlstore.sqlpersistencemgrfactory.init"); // NOI18N + LOG.log(TRACE, "sqlstore.sqlpersistencemgrfactory.init"); minPool = _persistenceManagerFactory.getMinPool(); maxPool = _persistenceManagerFactory.getMaxPool(); } @@ -905,9 +873,7 @@ private void initializeSQLStoreManager(String username, char[] password) { getIdentifier() ); } } catch(Exception e) { - if (logger.isLoggable(Logger.WARNING)) { - logger.log(Logger.WARNING, "jdo.sqlpersistencemanagerfactory.errorgettingDatabaseInfo", e); //NOI18N - } + LOG.log(WARNING, "jdo.sqlpersistencemanagerfactory.errorgettingDatabaseInfo", e); if (e instanceof JDOException) { throw (JDOException) e; @@ -982,7 +948,7 @@ public VersionConsistencyCache getVersionConsistencyCache() { if (_store == null) { // Store should be configured already. throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerfactoryimpl.getversionconsistencycache.nullstore")); // NOI18N + "jdo.persistencemanagerfactoryimpl.getversionconsistencycache.nullstore")); } vcCache = VersionConsistencyCacheImpl.create(); _store.getConfigCache().setVersionConsistencyCache(vcCache); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/TransactionImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/TransactionImpl.java index 2bca5756aa5..08ad7c7a3ac 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/TransactionImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/TransactionImpl.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 */ -/* - * TransactionImpl.java - * - * Create on March 3, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.impl; import com.sun.jdo.api.persistence.support.ConnectionFactory; @@ -28,19 +23,17 @@ import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; import com.sun.jdo.api.persistence.support.JDOUserException; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperTransaction; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManagerFactory; import com.sun.jdo.spi.persistence.support.sqlstore.connection.ConnectionImpl; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.EJBHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import jakarta.transaction.Status; import jakarta.transaction.Synchronization; import jakarta.transaction.TransactionManager; +import java.lang.System.Logger; import java.sql.Connection; -import java.util.ArrayList; import java.util.Arrays; import java.util.ResourceBundle; @@ -48,6 +41,9 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; + /** * * The Transaction interface allows operations to be performed against @@ -80,27 +76,31 @@ */ public class TransactionImpl implements com.sun.jdo.spi.persistence.support.sqlstore.Transaction { - /** - * Trace level for sh:6. - * - * This is public to this transaction package and referenced: - * if (TransactionImpl.tracing) - * This is reset by calling TransactionImpl.setTrace(). - */ - static boolean tracing; private static final int TRACE_THREADS = 0x01; private static final int TRACE_RESOURCES = 0x02; private static final int TRACE_SYNCHRONIZATIONS = 0x04; private static final int TRACE_ONE_PHASE = 0x08; + private static final int INTERNAL_ERROR = 1; + private static final int INTERNAL_OK = 0; + + + /** + * I18N message handler + */ + private final static ResourceBundle messages = I18NHelper.loadBundle(TransactionImpl.class); + + /** + * The logger + */ + private static final Logger LOG = System.getLogger(TransactionImpl.class.getName(), messages); + /** - * Package-visible lock for static attributes. - * * Note that globalLock can be a higher-level lock, in that it may be * locked before other lower-level objects are locked (i.e. the * transaction object). It may NOT be locked the other way round. */ - static String globalLock = "TranGlobalLock"; // NOI18N + private static String globalLock = "TranGlobalLock"; /** * Transaction status (from jakarta.transaction.Status). @@ -143,10 +143,6 @@ public class TransactionImpl */ private Synchronization synchronization = null; - /** - * Array of registered Resource interfaces. - */ - private ArrayList resources; private static final int RESOURCE_START = 0; private static final int RESOURCE_END = 1; @@ -225,18 +221,6 @@ public class TransactionImpl */ private int txType = -1; - /** - * The logger - */ - private static Logger logger = LogHelperTransaction.getLogger(); - - - /** - * I18N message handler - */ - private final static ResourceBundle messages = I18NHelper.loadBundle( - TransactionImpl.class); - /** * Constructor */ @@ -245,7 +229,6 @@ public TransactionImpl(PersistenceManager pm, String username, char[] password, this.timeout = seconds; this.startedCommit = false; this.onePhase = false; - this.resources = new ArrayList(); persistenceManager = pm; this.username = username; @@ -274,24 +257,28 @@ public void setPersistenceManager(PersistenceManager pm) { /** * Returns PersistenceManager associated with this transaction */ + @Override public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceManager() { return persistenceManager.getCurrentWrapper(); } + @Override public boolean isActive() { return (this.status == Status.STATUS_ACTIVE || this.status == Status.STATUS_MARKED_ROLLBACK); } + @Override public void setRetainValues(boolean flag) { // // First do a quick check to make sure the transaction is active. // This allows us to throw an exception immediately. // Cannot change flag to true inside an active pessimistic tx // - if (isActive() && !optimistic && flag) + if (isActive() && !optimistic && flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } // // Now get an exclusive lock so we can modify the retainValues flag. @@ -300,9 +287,10 @@ public void setRetainValues(boolean flag) { try { // Cannot change flag to true inside an active pessimistic tx - if (isActive() && !optimistic && flag) + if (isActive() && !optimistic && flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } this.retainValues = flag; @@ -316,19 +304,22 @@ public void setRetainValues(boolean flag) { } } + @Override public boolean getRetainValues() { return retainValues; } + @Override public void setRestoreValues(boolean flag) { // // First do a quick check to make sure the transaction is active. // This allows us to throw an exception immediately. // Cannot change flag to true inside an active tx // - if (isActive()) + if (isActive()) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } // // Now get an exclusive lock so we can modify the restoreValues flag. @@ -337,9 +328,10 @@ public void setRestoreValues(boolean flag) { try { // Cannot change flag to true inside an active tx - if (isActive()) + if (isActive()) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } this.restoreValues = flag; @@ -348,20 +340,23 @@ public void setRestoreValues(boolean flag) { } } + @Override public boolean getRestoreValues() { return restoreValues; } + @Override public void setNontransactionalRead (boolean flag) { // // First do a quick check to make sure the transaction is active. // This allows us to throw an exception immediately. // Cannot change flag to false inside an active optimistic tx // - if (isActive() && optimistic && !flag) + if (isActive() && optimistic && !flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } // // Now get an exclusive lock so we can modify the nontransactionalRead flag. @@ -370,9 +365,10 @@ public void setNontransactionalRead (boolean flag) { try { // Cannot change flag to false inside an active optimistic tx - if (isActive() && optimistic && !flag) + if (isActive() && optimistic && !flag) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); + } this.nontransactionalRead = flag; persistenceManager.notifyNontransactionalRead(flag); @@ -390,6 +386,7 @@ public void setNontransactionalRead (boolean flag) { } } + @Override public boolean getNontransactionalRead() { return nontransactionalRead; } @@ -399,6 +396,7 @@ public boolean getNontransactionalRead() { * to execute in the datastore associated with this Transaction instance * @param timeout new timout value in seconds; zero means unlimited */ + @Override public void setQueryTimeout(int timeout) { queryTimeout = timeout; } @@ -408,6 +406,7 @@ public void setQueryTimeout(int timeout) { * to execute in the datastore associated with this Transaction instance * @return timout value in seconds; zero means unlimited */ + @Override public int getQueryTimeout() { return queryTimeout; } @@ -417,6 +416,7 @@ public int getQueryTimeout() { * to execute in the datastore associated with this Transaction instance * @param timeout new timout value in seconds; zero means unlimited */ + @Override public void setUpdateTimeout(int timeout) { updateTimeout = timeout; } @@ -426,10 +426,12 @@ public void setUpdateTimeout(int timeout) { * to execute in the datastore associated with this Transaction instance * @return timout value in seconds; zero means unlimited */ + @Override public int getUpdateTimeout() { return updateTimeout; } + @Override public void setOptimistic(boolean flag) { // // First do a quick check to make sure the transaction is active. @@ -437,7 +439,7 @@ public void setOptimistic(boolean flag) { // if (!isTerminated()) { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); } // @@ -456,7 +458,7 @@ public void setOptimistic(boolean flag) { } } else { throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.setoptimistic.notallowed")); // NOI18N + "transaction.transactionimpl.setoptimistic.notallowed")); } // Notify PM about Tx type change @@ -466,29 +468,24 @@ public void setOptimistic(boolean flag) { } } + @Override public boolean getOptimistic() { return optimistic; } + @Override public void setSynchronization(Synchronization sync) { - if (this.tracing) - this.traceCall("setSynchronization"); // NOI18N - + traceCall("setSynchronization"); persistenceManager.acquireExclusiveLock(); - try { synchronization = sync; - - if (this.tracing) { - this.traceCallInfo("setSynchronization", // NOI18N - TRACE_SYNCHRONIZATIONS, null); - } - + traceCallInfo("setSynchronization", TRACE_SYNCHRONIZATIONS, null); } finally { persistenceManager.releaseExclusiveLock(); } } + @Override public Synchronization getSynchronization() { persistenceManager.acquireShareLock(); @@ -527,6 +524,7 @@ public boolean verify(String username, char[] password) /** * Begin a transaction. */ + @Override public void begin() { persistenceManager.acquireExclusiveLock(); @@ -552,7 +550,7 @@ public void begin() { } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage( - messages, "transaction.transactionimpl.begin.failedlocaltx"), e); // NOI18N + messages, "transaction.transactionimpl.begin.failedlocaltx"), e); } } else { txType = NON_MGD; @@ -566,16 +564,12 @@ public void begin() { * Status change and validation */ private void beginInternal() { - this.setTrace(); - - if (this.tracing) - this.traceCall("begin"); // NOI18N - + traceCall("begin"); // RESOLVE: need to reset to NO_TX if (this.isActive()) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.begin.notnew", // NOI18N - this.statusString(this.status))); + "transaction.transactionimpl.begin.notnew", + statusString(this.status))); } this.setStatus(Status.STATUS_ACTIVE); @@ -585,6 +579,7 @@ private void beginInternal() { /** * Begin a transaction in managed environment */ + @Override public void begin(jakarta.transaction.Transaction t) { persistenceManager.acquireExclusiveLock(); @@ -596,7 +591,7 @@ public void begin(jakarta.transaction.Transaction t) { EJBHelper.registerSynchronization(jta, this); } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage( - messages, "transaction.transactionimpl.begin.registersynchfailed"), e); // NOI18N + messages, "transaction.transactionimpl.begin.registersynchfailed"), e); } txType = CMT; @@ -609,6 +604,7 @@ public void begin(jakarta.transaction.Transaction t) { * Commit the transaction represented by this Transaction object * */ + @Override public void commit() { persistenceManager.acquireExclusiveLock(); @@ -617,26 +613,22 @@ public void commit() { if (txType == CMT || txType == BMT_UT) { // Error - should not be called throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.mgd", "commit")); //NOI18N + "transaction.transactionimpl.mgd", "commit")); } else if (txType == BMT_JDO) { // Send request to the container: try { EJBHelper.getLocalTransactionManager().commit(); return; } catch (Exception e) { - throw new JDOException("", e); // NOI18N + throw new JDOException("", e); } } - this.setTrace(); - - if (this.tracing) - this.traceCall("commit"); // NOI18N - - this.commitBefore(); - this.commitPrepare(); - this.commitComplete(); - this.notifyAfterCompletion(); + traceCall("commit"); + commitBefore(); + commitPrepare(); + commitComplete(); + notifyAfterCompletion(); } finally { persistenceManager.releaseExclusiveLock(); } @@ -645,12 +637,13 @@ public void commit() { /** * Called in the managed environment only for transaction completion */ + @Override public void beforeCompletion() { if (txType == NON_MGD) { // Error - should not be called throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.nonmgd", "beforeCompletion")); //NOI18N + "transaction.transactionimpl.nonmgd", "beforeCompletion")); } Object o = null; @@ -669,18 +662,16 @@ public void beforeCompletion() { /** * Called in the managed environment only for transaction completion */ + @Override public void afterCompletion(int st) { if (txType == NON_MGD) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.nonmgd", "afterCompletion")); //NOI18N + "transaction.transactionimpl.nonmgd", "afterCompletion")); } st = EJBHelper.translateStatus(st); // translate Status - if (this.tracing) { - this.traceCallInfo("afterCompletion", TRACE_SYNCHRONIZATIONS, //NOI18N - this.statusString(st)); - } + traceCallInfo("afterCompletion", TRACE_SYNCHRONIZATIONS, st); if (st == Status.STATUS_ROLLEDBACK) { this.setStatus(Status.STATUS_ROLLING_BACK); @@ -693,10 +684,7 @@ public void afterCompletion(int st) { try { synchronization.afterCompletion(st); } catch (Exception ex) { - logger.log(Logger.WARNING, I18NHelper.getMessage( - messages, - "transaction.transactionimpl.syncmanager.aftercompletion", // NOI18N - ex.getMessage())); + LOG.log(WARNING, "Problems during afterCompletion call to the SynchronizationManager.", ex); } } @@ -704,9 +692,8 @@ public void afterCompletion(int st) { persistenceManager.forceClose(); throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitprepare.wrongstatus", // NOI18N - "afterCompletion", this.statusString(this.status), // NOI18N - this.statusString(st))); + "transaction.transactionimpl.commitprepare.wrongstatus", + "afterCompletion", statusString(this.status), statusString(st))); } this.notifyAfterCompletion(); @@ -728,36 +715,32 @@ public void afterCompletion(int st) { * For exceptions see commit() method. */ private void commitBefore() { - boolean rollbackOnly = false; //marked for rollback - boolean notified = false; + boolean rollbackOnly = false; // marked for rollback + boolean notified = false; - if (this.tracing) - this.traceCall("commitBefore"); // NOI18N - // - // Validate transaction state before we commit - // + traceCall("commitBefore"); if ((this.status == Status.STATUS_ROLLING_BACK) || (this.status == Status.STATUS_ROLLEDBACK)) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.rolledback", // NOI18N - "commit", // NOI18N - this.statusString(this.status))); + "transaction.transactionimpl.rolledback", + "commit", + statusString(this.status))); } if (this.status == Status.STATUS_MARKED_ROLLBACK) { rollbackOnly = true; } else if (this.status != Status.STATUS_ACTIVE) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commit_rollback.notactive", // NOI18N - "commit", // NOI18N - this.statusString(this.status))); + "transaction.transactionimpl.commit_rollback.notactive", + "commit", + statusString(this.status))); } if (this.startedCommit) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitbefore.incommit", // NOI18N - "commit")); // NOI18N + "transaction.transactionimpl.commitbefore.incommit", + "commit")); } this.startedCommit = true; @@ -775,7 +758,7 @@ private void commitBefore() { rollbackOnly = true; } else { // Must have been concurrently rolled back throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitbefore.rolledback")); // NOI18N + "transaction.transactionimpl.commitbefore.rolledback")); } } if (rollbackOnly && txType == NON_MGD) { @@ -783,8 +766,8 @@ private void commitBefore() { throw new JDOUserException(I18NHelper.getMessage(messages, notified ? - "transaction.transactionimpl.commitbefore.rollbackonly_insync" : // NOI18N - "transaction.transactionimpl.commitbefore.rollbackonly")); // NOI18N + "transaction.transactionimpl.commitbefore.rollbackonly_insync" : + "transaction.transactionimpl.commitbefore.rollbackonly")); } } @@ -800,8 +783,7 @@ private void commitBefore() { * For exceptions see commit() method. */ private void commitPrepare() { - if (this.tracing) - this.traceCall("commitPrepare"); // NOI18N + this.traceCall("commitPrepare"); // // Once we've reached the Status.STATUS_PREPARING state we do not need // to check for concurrent state changes. All user-level methods @@ -814,35 +796,11 @@ private void commitPrepare() { // if (this.status != Status.STATUS_PREPARING) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitprepare.wrongstatus", // NOI18N - "commitPrepare", // NOI18N - "STATUS_PREPARING", // NOI18N - this.statusString(this.status))); - } - - // - // If there is at most one resource then we can do this in 1-phase. - // - if (this.resources.size() <= 1) - this.onePhase = true; - - /* - // - // Prepare resources if not one-phase - // - if (!this.onePhase) { - int error = this.prepareResources(); - if (error != XAResource.XA_OK) { - this.forceRollback(); - - throw (RollbackException)ErrorManager.createFormatAdd( - RollbackException.class, - ErrorManager.USER, - TransactionMsgCat.SH_ERR_TX_TR_CMT_RB_IN_PREP_XA, - this.XAErrorString(error)); - } + "transaction.transactionimpl.commitprepare.wrongstatus", + "commitPrepare", + "STATUS_PREPARING", + statusString(this.status))); } - */ this.setStatus(Status.STATUS_PREPARED); } @@ -860,8 +818,7 @@ private void commitPrepare() { * For exceptions see commit() method. */ private void commitComplete() { - if (this.tracing) - this.traceCallInfo("commitComplete", TRACE_ONE_PHASE, null); // NOI18N + traceCallInfo("commitComplete", TRACE_ONE_PHASE, null); // // Validate initial state @@ -874,9 +831,9 @@ private void commitComplete() { internalCommit(); } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitprepare.wrongstatus", // NOI18N - "commitComplete", // NOI18N - "STATUS_PREPARED", // NOI18N + "transaction.transactionimpl.commitprepare.wrongstatus", + "commitComplete", + "STATUS_PREPARED", this.statusString(this.status))); } } @@ -909,8 +866,8 @@ private void internalCommit() { if (error != INTERNAL_OK) { this.forceRollback(); throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitcomplete.error", // NOI18N - "Connection Error")); // NOI18N + "transaction.transactionimpl.commitcomplete.error", + "Connection Error")); } this.closeConnection(); } @@ -921,6 +878,7 @@ private void internalCommit() { * Rollback the transaction represented by this transaction object. * */ + @Override public void rollback() { persistenceManager.acquireExclusiveLock(); @@ -929,13 +887,10 @@ public void rollback() { if (txType == CMT || txType == BMT_UT) { // Error - should not be called throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.mgd", "rollback")); //NOI18N + "transaction.transactionimpl.mgd", "rollback")); } - this.setTrace(); - - if (this.tracing) - this.traceCall("rollback"); // NOI18N + traceCall("rollback"); if ((this.status != Status.STATUS_ACTIVE) && (this.status != Status.STATUS_MARKED_ROLLBACK)) { @@ -947,8 +902,8 @@ public void rollback() { // throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commit_rollback.notactive", // NOI18N - "rollback", // NOI18N + "transaction.transactionimpl.commit_rollback.notactive", + "rollback", this.statusString(this.status))); } @@ -962,7 +917,7 @@ public void rollback() { try { EJBHelper.getLocalTransactionManager().rollback(); } catch (Exception e) { - throw new JDOException("", e); // NOI18N + throw new JDOException("", e); } } else { //NON_MGD //This has effect of rolling back changes also @@ -985,8 +940,7 @@ public void rollback() { * */ private void internalRollback() { - if (this.tracing) - this.traceCall("internalRollback"); // NOI18N + traceCall("internalRollback"); if (this.status == Status.STATUS_ROLLEDBACK) { return; @@ -994,10 +948,10 @@ private void internalRollback() { if (this.status != Status.STATUS_ROLLING_BACK) { throw new JDOUserException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.commitprepare.wrongstatus", // NOI18N - "internalRollback", // NOI18N - "STATUS_ROLLING_BACK", // NOI18N - this.statusString(this.status))); + "transaction.transactionimpl.commitprepare.wrongstatus", + "internalRollback", + "STATUS_ROLLING_BACK", + statusString(this.status))); } if (txType == NON_MGD) { @@ -1021,8 +975,7 @@ private void internalRollback() { * See internalRollback() for exceptions */ int forceRollback() { - if (this.tracing) - this.traceCall("forceRollback"); // NOI18N + traceCall("forceRollback"); if ((this.status == Status.STATUS_ROLLING_BACK) // Already || (this.status == Status.STATUS_ROLLEDBACK) // Done @@ -1042,9 +995,9 @@ int forceRollback() { * the transaction is to roll back. * */ + @Override public void setRollbackOnly() { - if (this.tracing) - this.traceCall("setRollbackOnly"); // NOI18N + traceCall("setRollbackOnly"); if ((this.status == Status.STATUS_ROLLING_BACK) || (this.status == Status.STATUS_ROLLEDBACK) @@ -1059,7 +1012,7 @@ public void setRollbackOnly() { try { jta.setRollbackOnly(); } catch (Exception e) { - throw new JDOException("", e); // NOI18N + throw new JDOException("", e); } } else { this.setStatus(Status.STATUS_MARKED_ROLLBACK); @@ -1079,7 +1032,7 @@ public int getStatus() { // (i.e. beforeCompletion, xaRes.prepare) the lock is released, and // that other threads can access this object. See note at top of file. // - synchronized (this.globalLock) { + synchronized (globalLock) { return this.status; } } @@ -1095,7 +1048,7 @@ public int getStatus() { * @return True if transaction is completed. */ boolean isTerminated() { - synchronized (this.globalLock) { + synchronized (globalLock) { return ((this.status == Status.STATUS_COMMITTED) || (this.status == Status.STATUS_ROLLEDBACK) || (this.status == Status.STATUS_NO_TRANSACTION)); @@ -1142,11 +1095,8 @@ private void notifyAfterCompletion() { if (synchronization != null) { try { synchronization.afterCompletion(this.status); - } catch (Exception ex) { - logger.log(Logger.WARNING, I18NHelper.getMessage( - messages, - "transaction.transactionimpl.syncmanager.aftercompletion", // NOI18N - ex.getMessage())); + } catch (Exception e) { + LOG.log(WARNING, "The afterCompletion failed.", e); } } } @@ -1165,12 +1115,9 @@ private void notifyAfterCompletion() { // created (ncg) // private void setStatus(int status) { - synchronized(this.globalLock) { - if (this.tracing) { - Object[] items= new Object[] {Thread.currentThread(),this.toString(), - this.statusString(this.status), this.statusString(status), persistenceManager}; - logger.finest("sqlstore.transactionimpl.status",items); // NOI18N - } + synchronized(globalLock) { + LOG.log(TRACE, "{0} Tx[ {1} ].setStatus: {2} => {3} for {4}.", Thread.currentThread(), this, + statusString(this.status), statusString(status), persistenceManager); this.status = status; persistenceManager.notifyStatusChange(isActive()); } @@ -1180,8 +1127,7 @@ private void setStatus(int status) { * Forget this transaction */ private void forget() { - if (this.tracing) - this.traceCall("forget"); // NOI18N + traceCall("forget"); // // Do not clear: @@ -1201,7 +1147,7 @@ private void forget() { closeConnection(); throw new JDOFatalInternalException(I18NHelper.getMessage( messages, - "transaction.transactionimpl.forget.connectionnotclosed")); // NOI18N + "transaction.transactionimpl.forget.connectionnotclosed")); } } catch (Exception e) { } @@ -1209,38 +1155,20 @@ private void forget() { } _connectionReferenceCount = 0; - // - // Do we need to invoke forget on the resource? - // - this.resources.clear(); - if (txType != NON_MGD) { + if (txType != NON_MGD) { persistenceManager.close(); } jta = null; txType = NON_MGD; // Restore the flag - - this.setTrace(); - } - - // - // ----- Debugging utilities ----- - // - - /** - * Set the global transaction tracing. - */ - static void setTrace() { - TransactionImpl.tracing = logger.isLoggable(Logger.FINEST); } /** * Trace method call. */ private void traceCall(String call) { - Object[] items = new Object[]{Thread.currentThread(),this.toString(),call, - this.statusString(this.status),txTypeString(), persistenceManager}; - logger.finest("sqlstore.transactionimpl.call",items); // NOI18N + LOG.log(TRACE, "{0} Tx[ {1} ].{2}:status = {3}, txType: {4} for {5}.", Thread.currentThread(), this, call, + statusString(status), txTypeString(), persistenceManager); } /** @@ -1251,34 +1179,37 @@ private void traceCall(String call) { // 11-jan-1999 // created (ncg) // - private void traceCallInfo(String call, int info, String s) { - - //TODO : Optimize this when converting to resource budles - StringBuffer logMessage = new StringBuffer(); - logMessage.append("Thread.currentThread()").append("Tran[") // NOI18N - .append(this.toString()).append("].").append(call) // NOI18N - .append(": status = ").append(this.statusString(this.status)); // NOI18N - - if ((info & TRACE_THREADS) != 0) - logMessage.append(", threads = " + this.threads); // NOI18N - if ((info & TRACE_SYNCHRONIZATIONS) != 0) - logMessage.append(", sync = " + this.synchronization); // NOI18N - if ((info & TRACE_RESOURCES) != 0) - logMessage.append(", resources = " + this.resources.size()); // NOI18N - if ((info & TRACE_ONE_PHASE) != 0 && this.onePhase) - logMessage.append(", onePhase = true"); // NOI18N - if (s != null) - logMessage.append(", " + s + " for " + persistenceManager); // NOI18N - - logger.finest("sqlstore.transactionimpl.general",logMessage.toString()); // NOI18N + private void traceCallInfo(String call, int info, Integer txStatus) { + if (!LOG.isLoggable(TRACE) ) { + return; + } + StringBuilder logMessage = new StringBuilder(); + logMessage.append("Thread.currentThread()").append("Tx[") + .append(this).append("].").append(call) + .append(": status = ").append(statusString(this.status)); + + if ((info & TRACE_THREADS) != 0) { + logMessage.append(", threads = " + this.threads); + } + if ((info & TRACE_SYNCHRONIZATIONS) != 0) { + logMessage.append(", sync = " + this.synchronization); + } + if ((info & TRACE_ONE_PHASE) != 0 && this.onePhase) { + logMessage.append(", onePhase = true"); + } + if (txStatus != null) { + logMessage.append(", " + statusString(txStatus) + " for " + persistenceManager); + } + + LOG.log(TRACE, logMessage.toString()); } /** * Trace method call with extra string. */ private void traceCallString(String call, String info) { - Object[] items = new Object[] {Thread.currentThread(),this.toString(),call,info,persistenceManager}; - logger.finest("sqlstore.transactionimpl.call.info",items); // NOI18N + LOG.log(TRACE, "{0} Tx[ {1} ].{2}: {3} for {4}.", Thread.currentThread(), this, call, info, + persistenceManager); } /** @@ -1288,13 +1219,13 @@ private void traceCallString(String call, String info) { */ private String txTypeString() { switch (txType) { - case NON_MGD: return "NON_MGD"; // NOI18N - case CMT: return "CMT"; // NOI18N - case BMT_UT: return "BMT_UT"; // NOI18N - case BMT_JDO: return "BMT_JDO"; // NOI18N + case NON_MGD: return "NON_MGD"; + case CMT: return "CMT"; + case BMT_UT: return "BMT_UT"; + case BMT_JDO: return "BMT_JDO"; default: break; } - return "UNKNOWN"; // NOI18N + return "UNKNOWN"; } /** @@ -1305,33 +1236,32 @@ private String txTypeString() { */ public static String statusString(int status) { switch (status) { - case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; // NOI18N - case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; // NOI18N - case Status.STATUS_PREPARED: return "STATUS_PREPARED"; // NOI18N - case Status.STATUS_COMMITTED: return "STATUS_COMMITTED"; // NOI18N - case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; // NOI18N - case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; // NOI18N - case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; // NOI18N - case Status.STATUS_PREPARING: return "STATUS_PREPARING"; // NOI18N - case Status.STATUS_COMMITTING: return "STATUS_COMMITTING"; // NOI18N - case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; // NOI18N + case Status.STATUS_ACTIVE: return "STATUS_ACTIVE"; + case Status.STATUS_MARKED_ROLLBACK: return "STATUS_MARKED_ROLLBACK"; + case Status.STATUS_PREPARED: return "STATUS_PREPARED"; + case Status.STATUS_COMMITTED: return "STATUS_COMMITTED"; + case Status.STATUS_ROLLEDBACK: return "STATUS_ROLLEDBACK"; + case Status.STATUS_UNKNOWN: return "STATUS_UNKNOWN"; + case Status.STATUS_NO_TRANSACTION: return "STATUS_NO_TRANSACTION"; + case Status.STATUS_PREPARING: return "STATUS_PREPARING"; + case Status.STATUS_COMMITTING: return "STATUS_COMMITTING"; + case Status.STATUS_ROLLING_BACK: return "STATUS_ROLLING_BACK"; default: break; } - return "STATUS_Invalid[" + status + "]"; // NOI18N + return "STATUS_Invalid[" + status + "]"; } /** * Returns a Connection. If there is no existing one, asks * ConnectionFactory for a new Connection */ + @Override public synchronized Connection getConnection() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (_connection == null) { // find a new connection if (connectionFactory == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "transaction.transactionimpl.getconnection.nullcf")); // NOI18N + "transaction.transactionimpl.getconnection.nullcf")); } _connection = this.getConnectionInternal(); @@ -1339,11 +1269,8 @@ public synchronized Connection getConnection() { _connectionReferenceCount++; - if (debug) { - Object[] items = new Object[] {_connection, Boolean.valueOf(optimistic), - new Integer(_connectionReferenceCount) , persistenceManager}; - logger.finest("sqlstore.transactionimpl.getconnection",items); // NOI18N - } + LOG.log(TRACE, "getConnection(): {0} TX optimistic: {1} referenceCount = {2} for {3}.", _connection, optimistic, + _connectionReferenceCount, persistenceManager); // We cannot depend on NON_MGD flag here as this method can be called // outside of an active transaction. @@ -1364,7 +1291,7 @@ public synchronized Connection getConnection() { _connection.setAutoCommit(true); } } catch (java.sql.SQLException e) { - logger.log(Logger.WARNING,"sqlstore.exception.log",e); // NOI18N + LOG.log(WARNING, "Cannot work with autocommit!", e); } } @@ -1375,6 +1302,7 @@ public synchronized Connection getConnection() { * Replace a connection. Used in a managed environment only. * In a J2EE RI Connection need to be replaced at the beforeCompletion. */ + @Override public void replaceConnection() { if (EJBHelper.isManaged()) { this.releaseConnection(); @@ -1388,19 +1316,14 @@ public void replaceConnection() { * Connection cannot be closed if it is part of the commit/rollback * operation or inside a pessimistic transaction */ + @Override public synchronized void releaseConnection() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (_connectionReferenceCount > 0) { _connectionReferenceCount--; } - if (debug) { - Object[] items = new Object[] {Boolean.valueOf(optimistic), - Boolean.valueOf(startedCommit), - new Integer(_connectionReferenceCount) , persistenceManager}; - logger.finest("sqlstore.transactionimpl.releaseconnection",items); // NOI18N - } + LOG.log(TRACE, "releaseConnection(): TX optimistic: {0} Inside Commit: {1} referenceCount: {2} for {3}.", + optimistic, startedCommit, _connectionReferenceCount, persistenceManager); // Fix for bug 4479807: Do not keep connection in the managed environment. if ( (!EJBHelper.isManaged() && optimistic == false) || startedCommit ) { @@ -1418,42 +1341,32 @@ public synchronized void releaseConnection() { } private Connection getConnectionInternal() { - if (isDataSource) { - try { - if (EJBHelper.isManaged()) { - // Delegate to the EJBHelper for details. - if (isActive()) { - return EJBHelper.getConnection(connectionFactory, - username, password); - } else { - return EJBHelper.getNonTransactionalConnection( - connectionFactory, username, password); - } - } else if (username != null) { - return ((DataSource)connectionFactory).getConnection( - username, new String(password)); - } else { - return ((DataSource)connectionFactory).getConnection(); + if (!isDataSource) { + return ((ConnectionFactory) connectionFactory).getConnection(); + } + try { + if (EJBHelper.isManaged()) { + // Delegate to the EJBHelper for details. + if (isActive()) { + return EJBHelper.getConnection(connectionFactory, username, password); } + return EJBHelper.getNonTransactionalConnection(connectionFactory, username, password); + } else if (username != null) { + return ((DataSource) connectionFactory).getConnection(username, new String(password)); + } else { + return ((DataSource) connectionFactory).getConnection(); + } - } catch (java.sql.SQLException e) { - String sqlState = e.getSQLState(); - int errorCode = e.getErrorCode(); - - if (sqlState == null) { - throw new JDODataStoreException( - I18NHelper.getMessage(messages, - "connectionefactoryimpl.sqlexception", // NOI18N - "null", "" + errorCode), e); // NOI18N - } else { - throw new JDODataStoreException( - I18NHelper.getMessage(messages, - "connectionefactoryimpl.sqlexception", // NOI18N - sqlState, "" + errorCode), e); // NOI18N - } + } catch (java.sql.SQLException e) { + String sqlState = e.getSQLState(); + int errorCode = e.getErrorCode(); + + if (sqlState == null) { + throw new JDODataStoreException( + I18NHelper.getMessage(messages, "connectionefactoryimpl.sqlexception", "null", "" + errorCode), e); } - } else { - return ((ConnectionFactory)connectionFactory).getConnection(); + throw new JDODataStoreException( + I18NHelper.getMessage(messages, "connectionefactoryimpl.sqlexception", sqlState, "" + errorCode), e); } } @@ -1461,11 +1374,7 @@ private Connection getConnectionInternal() { * Always Close a connection */ private void closeConnection() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {_connection , persistenceManager}; - logger.finest("sqlstore.transactionimpl.closeconnection",items); // NOI18N - } + LOG.log(TRACE, "Closing connection {0} for {1}", _connection, persistenceManager); try { if (_connection != null) { _connection.close(); @@ -1480,24 +1389,19 @@ private void closeConnection() { * replaces rollbackResources() in ForteTran */ private void rollbackConnection() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (debug) { - Object[] items = new Object[] {_connection , persistenceManager}; - logger.finest("sqlstore.transactionimpl.rollbackconnection",items); // NOI18N - } + LOG.log(TRACE, "rollbackConnection(): {0} for {1}.", _connection, persistenceManager); if (_connection != null) { try { - if (isDataSource) + if (isDataSource) { _connection.rollback(); - else + } else { ((ConnectionImpl)_connection).internalRollback(); + } } catch (Exception e) { //Recover? } } } - private int INTERNAL_ERROR = 1; - private int INTERNAL_OK = 0; /** * replaces commitResources() in ForteTran @@ -1505,10 +1409,11 @@ private void rollbackConnection() { private int commitConnection() { if (_connection != null) { try { - if (isDataSource) + if (isDataSource) { _connection.commit(); - else + } else { ((ConnectionImpl)_connection).internalCommit(); + } } catch (Exception e) { return INTERNAL_ERROR; } @@ -1522,36 +1427,24 @@ private int commitConnection() { * * @return String describing contents of this Transaction object. */ + @Override public String toString() { - String s = " Transaction: \n status = " + this.statusString(this.status)+ "\n" // NOI18N - + " Transaction Object = Transaction@" + this.hashCode() + "\n" // NOI18N - + " threads = " + this.threads + "\n"; // NOI18N + String s = " Transaction: \n status = " + this.statusString(this.status)+ "\n" + + " Transaction Object = Transaction@" + this.hashCode() + "\n" + + " threads = " + this.threads + "\n"; - if (this.timeout != 0) - s = s + " timeout = " + this.timeout + "\n"; // NOI18N - if (this.startedCommit) - s = s + " startedCommit = true\n"; // NOI18N - if (this.onePhase) - s = s + " onePhase = true\n"; // NOI18N + if (this.timeout != 0) { + s = s + " timeout = " + this.timeout + "\n"; + } + if (this.startedCommit) { + s = s + " startedCommit = true\n"; + } + if (this.onePhase) { + s = s + " onePhase = true\n"; + } if (synchronization != null) { - s = s + "sync: " + synchronization + "\n"; // NOI18N - } - if (!this.resources.isEmpty()) { - s = s + " # resources = " + this.resources.size() + "\n"; // NOI18N - /* - for (i = 0; i < this.resources.size(); i++) { - XAResource res = (XAResource)this.resources.get(i); - // - // Make be null if vote readonly during commit processing - // Bug 48325: avoid recursive toString() calls - // - if (res != null) { - s = s + " [" + i + "] " + // NOI18N - res.getClass().getName() + "\n"; // NOI18N - } - } - */ + s = s + "sync: " + synchronization + "\n"; } return s; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/VersionConsistencyCacheImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/VersionConsistencyCacheImpl.java index 360aefc6ebd..046f262aace 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/VersionConsistencyCacheImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/impl/VersionConsistencyCacheImpl.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 @@ -19,12 +20,11 @@ import com.sun.appserv.util.cache.Cache; import com.sun.appserv.util.cache.CacheListener; import com.sun.appserv.util.cache.LruCache; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperPersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; import com.sun.jdo.spi.persistence.support.sqlstore.VersionConsistencyCache; import com.sun.jdo.spi.persistence.utility.BucketizedHashtable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -34,6 +34,10 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; + /** * A 2-level cache of StateManager instances (i.e., a map of maps). The inner @@ -44,37 +48,29 @@ */ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** The outermost map of the two-level cache. */ - private final Map pcTypeMap = new HashMap(); + private final Map, VCCache> pcTypeMap = new HashMap<>(); /** Used to create different kinds of caches. */ // Not final, so that we can create different kinds of caches for testing. private static CacheFactory cacheFactory; - private final static ResourceBundle messages = - I18NHelper.loadBundle(VersionConsistencyCacheImpl.class); + private final static ResourceBundle messages = I18NHelper.loadBundle(VersionConsistencyCacheImpl.class); /** Use the PersistenceManager's logger. */ - private static Logger logger = LogHelperPersistenceManager.getLogger(); + private static final Logger LOG = System.getLogger(VersionConsistencyCacheImpl.class.getName(), messages); /** Name of implementation class of LRU cache. */ - private static final String LRU_CACHE_CLASSNAME = - "com.sun.appserv.util.cache.LruCache"; // NOI18aN - + private static final String LRU_CACHE_CLASSNAME = "com.sun.appserv.util.cache.LruCache"; // // Cache configuration controls // /** Prefix of each property name of configuration item. */ - private static final String PROPERTY_PREFIX = - "com.sun.jdo.spi.persistence.support.sqlstore.impl.VersionConsistency."; // NOI18N - - - /** Determines whether to use LruCache or the default. */ - private static boolean lruCache = false; + private static final String PROPERTY_PREFIX = "com.sun.jdo.spi.persistence.support.sqlstore.impl.VersionConsistency."; /** Name of property to choose LRU or basic cache. */ - private static final String LRU_CACHE_PROPERTY = PROPERTY_PREFIX + "LruCache"; // NOI18N + private static final String LRU_CACHE_PROPERTY = PROPERTY_PREFIX + "LruCache"; /** For both LruCache and BucketizedHashtable. */ @@ -82,7 +78,7 @@ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** Name of property for specifying loadFactor. */ private static final String LOAD_FACTOR_PROPERTY = - PROPERTY_PREFIX + "loadFactor"; // NOI18N + PROPERTY_PREFIX + "loadFactor"; /** For BucketizedHashtable only. */ @@ -90,7 +86,7 @@ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** Name of property for specifying bucketSize. */ private static final String BUCKET_SIZE_PROPERTY = - PROPERTY_PREFIX + "bucketSize"; // NOI18N + PROPERTY_PREFIX + "bucketSize"; /** For BucketizedHashtable only. */ @@ -98,7 +94,7 @@ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** Name of property for specifying initialCapacity. */ private static final String INITIAL_CAPACITY_PROPERTY = - PROPERTY_PREFIX + "initialCapacity"; // NOI18N + PROPERTY_PREFIX + "initialCapacity"; /** For LruCache only. */ @@ -106,7 +102,7 @@ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** Name of property for specifying maxEntries. */ private static final String MAX_ENTRIES_PROPERTY = - PROPERTY_PREFIX + "maxEntries"; // NOI18N + PROPERTY_PREFIX + "maxEntries"; /** LruCache only, 10 minute timeout */ @@ -114,7 +110,7 @@ public class VersionConsistencyCacheImpl implements VersionConsistencyCache { /** Name of property for specifying timeout. */ private static final String TIMEOUT_PROPERTY = - PROPERTY_PREFIX + "timeout"; // NOI18N + PROPERTY_PREFIX + "timeout"; // Create the cache factory static { @@ -185,10 +181,7 @@ static CacheFactory createCacheFactory() { try { Class.forName(LRU_CACHE_CLASSNAME); } catch (Exception ex) { - logger.warning( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.lrucachenotfound")); // NOI18N + LOG.log(WARNING, "jdo.versionconsistencycacheimpl.lrucachenotfound"); lruCache = false; } } @@ -207,10 +200,7 @@ static CacheFactory createCacheFactory() { // This probably should not happen, but fallback to the // default cache just in case. lruCache = false; - logger.warning( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.unexpectedduringcreate", ex));// NOI18N + LOG.log(WARNING, "jdo.versionconsistencycacheimpl.unexpectedduringcreate", ex); } if (lruCache) { @@ -219,20 +209,11 @@ static CacheFactory createCacheFactory() { rc = new BasicCacheFactory(); } - if (logger.isLoggable(Logger.FINER)) { - String values = - "\nloadFactor= " + loadFactor // NOI18N - + "\nbucketSize= " + bucketSize // NOI18N - + "\ninitialCapacity=" + initialCapacity // NOI18N - + "\nmaxEntries=" + maxEntries // NOI18N - + "\ntimeout=" + timeout // NOI18N - + "\nlruCache=" + lruCache; // NOI18N - logger.finer( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.created", - values)); // NOI18N - } + boolean cache = lruCache; + LOG.log(DEBUG, + () -> "created with: " + "\nloadFactor= " + loadFactor + "\nbucketSize= " + bucketSize + + "\ninitialCapacity=" + initialCapacity + "\nmaxEntries=" + maxEntries + "\ntimeout=" + timeout + + "\nlruCache=" + cache); return rc; } @@ -306,31 +287,20 @@ private static long getLongValue(String propName, long defaultVal) { * @param valString Value of property as a String. */ private static void logBadConfigValue(String propName, String valString) { - logger.warning( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.badconfigvalue", // NOI18N - propName, valString)); + LOG.log(WARNING, "jdo.versionconsistencycacheimpl.badconfigvalue", propName, valString); } /** * @see VersionConsistencyCache#put */ - public StateManager put(Class pcType, Object oid, StateManager sm) { - boolean logAtFinest = logger.isLoggable(Logger.FINEST); - - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.put.entering", // NOI18N - new Object[] {pcType, oid, sm})); - } + @Override + public StateManager put(Class pcType, Object oid, StateManager sm) { + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.put.entering", pcType, oid, sm); StateManager rc = null; VCCache oid2sm = null; synchronized (pcTypeMap) { - oid2sm = (VCCache) pcTypeMap.get(pcType); + oid2sm = pcTypeMap.get(pcType); if (null == oid2sm) { oid2sm = cacheFactory.create(); @@ -340,48 +310,28 @@ public StateManager put(Class pcType, Object oid, StateManager sm) { rc = oid2sm.put(oid, sm); - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.put.returning", // NOI18N - rc)); - } - + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.put.returning", rc); return rc; } /** * @see VersionConsistencyCache#get */ - public StateManager get(Class pcType, Object oid) { - boolean logAtFinest = logger.isLoggable(Logger.FINEST); - - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.get.entering", // NOI18N - new Object[] {pcType, oid})); - } + @Override + public StateManager get(Class pcType, Object oid) { + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.get.entering", pcType, oid); StateManager rc = null; VCCache oid2sm = null; synchronized (pcTypeMap) { - oid2sm = (VCCache) pcTypeMap.get(pcType); + oid2sm = pcTypeMap.get(pcType); } if (null != oid2sm) { rc = oid2sm.get(oid); } - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.get.returning", // NOI18N - rc)); - } + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.get.returning", rc); return rc; } @@ -389,36 +339,23 @@ public StateManager get(Class pcType, Object oid) { /** * @see VersionConsistencyCache#remove */ - public StateManager remove(Class pcType, Object oid) { - boolean logAtFinest = logger.isLoggable(Logger.FINEST); - - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.remove.entering", // NOI18N - new Object[] {pcType, oid})); - } + @Override + public StateManager remove(Class pcType, Object oid) { + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.remove.entering", pcType, oid); StateManager rc = null; synchronized (pcTypeMap) { - VCCache oid2sm = (VCCache) pcTypeMap.get(pcType); + VCCache oid2sm = pcTypeMap.get(pcType); if (null != oid2sm) { - rc = (StateManager) oid2sm.remove(oid); + rc = oid2sm.remove(oid); if (oid2sm.isEmpty()) { pcTypeMap.remove(pcType); } } } - if (logAtFinest) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.remove.returning", // NOI18N - rc)); - } + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.remove.returning", rc); return rc; } @@ -426,31 +363,21 @@ public StateManager remove(Class pcType, Object oid) { * This implementation does nothing. Instead, we create buckets for each * pcType as-needed; see {@link #put} */ - public void addPCType(Class pcType) { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.addpctype", // NOI18N - pcType)); - } + @Override + public void addPCType(Class pcType) { + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.addpctype", pcType); // Intentionally empty } /** * @see VersionConsistencyCache#removePCType */ - public void removePCType(Class pcType) { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.removepctype", // NOI18N - pcType)); - } + @Override + public void removePCType(Class pcType) { + LOG.log(TRACE, "jdo.versionconsistencycacheimpl.removepctype", pcType); synchronized (pcTypeMap) { - VCCache oid2sm = (VCCache) pcTypeMap.get(pcType); + VCCache oid2sm = pcTypeMap.get(pcType); if (null != oid2sm) { oid2sm.clear(); @@ -465,8 +392,8 @@ public void removePCType(Class pcType) { public int size() { int rc = 0; synchronized (pcTypeMap) { - for (Iterator i = pcTypeMap.keySet().iterator(); i.hasNext();) { - VCCache oid2sm = (VCCache) pcTypeMap.get(i.next()); + for (Iterator> i = pcTypeMap.keySet().iterator(); i.hasNext();) { + VCCache oid2sm = pcTypeMap.get(i.next()); rc += oid2sm.size(); } } @@ -487,22 +414,22 @@ public boolean isHighPerf() { /** Provides cache operations of put, get, and remove. */ interface VCCache { /** @see Map#put */ - public StateManager put(Object key, StateManager value); + StateManager put(Object key, StateManager value); /** @see Map#get */ - public StateManager get(Object key); + StateManager get(Object key); /** @see Map#remove */ - public StateManager remove(Object key); + StateManager remove(Object key); /** @see Map#clear */ - public void clear(); + void clear(); /** @see Map#isEmpty */ - public boolean isEmpty(); + boolean isEmpty(); /** @see Map#size */ - public int size(); + int size(); } /** @@ -510,51 +437,45 @@ interface VCCache { * the underlying implemention issynchronized. */ static class BasicVCCache implements VCCache { - private final Map cache; + private final Map cache; BasicVCCache() { - if (logger.isLoggable(Logger.FINER)) { - logger.finer( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.usinghashmap", // NOI18N - new Object[] { - new Integer(bucketSize), - new Long(initialCapacity), - new Float(loadFactor)})); - } - - cache = Collections.synchronizedMap( - new BucketizedHashtable( - bucketSize, initialCapacity, loadFactor)); + LOG.log(DEBUG, "jdo.versionconsistencycacheimpl.usinghashmap", bucketSize, initialCapacity, loadFactor); + cache = Collections.synchronizedMap(new BucketizedHashtable<>(bucketSize, initialCapacity, loadFactor)); } /** @see Map#put */ + @Override public StateManager put(Object key, StateManager value) { - return (StateManager) cache.put(key, value); + return cache.put(key, value); } /** @see Map#get */ + @Override public StateManager get(Object key) { - return (StateManager) cache.get(key); + return cache.get(key); } /** @see Map#remove */ + @Override public StateManager remove(Object key) { - return (StateManager) cache.remove(key); + return cache.remove(key); } /** @see Map#clear */ + @Override public void clear() { cache.clear(); } /** @see Map#isEmpty */ + @Override public boolean isEmpty() { return cache.isEmpty(); } /** @see Map#size */ + @Override public int size() { return cache.size(); } @@ -569,7 +490,7 @@ static class LruVCCache implements VCCache { * We can't use the interface type Cache because we need to be able to * clear out the cache, which is only supported by the implementation. */ - private final Cache cache; + private final Cache cache; /** * @param maxEntries maximum number of entries expected in the cache @@ -577,60 +498,53 @@ static class LruVCCache implements VCCache { * @param timeout to be used to trim the expired entries */ LruVCCache(int maxEntries, long timeout, float loadFactor) { - if (logger.isLoggable(Logger.FINER)) { - logger.finer( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.usinglrucache", // NOI18N - new Object[] { - new Integer(maxEntries), - new Long(timeout), - new Float(loadFactor)})); - } + LOG.log(DEBUG, "jdo.versionconsistencycacheimpl.usinglrucache", maxEntries, timeout, loadFactor); - LruCache c = new LruCache(); + LruCache c = new LruCache<>(); c.init(maxEntries, timeout, loadFactor, (Properties) null); - c.addCacheListener( - new CacheListener() { - public void trimEvent(Object key, Object value) { - cache.remove(key); - if (logger.isLoggable(Logger.FINER)) { - logger.finer( - I18NHelper.getMessage( - messages, - "jdo.versionconsistencycacheimpl.trimevent")); // NOI18N - } - } - }); + c.addCacheListener(new CacheListener() { + + @Override + public void trimEvent(Object key, Object value) { + cache.remove(key); + LOG.log(DEBUG, "jdo.versionconsistencycacheimpl.trimevent"); + } + }); cache = c; } /** @see Map#put */ + @Override public StateManager put(Object key, StateManager value) { - return (StateManager) cache.put(key, value); + return cache.put(key, value); } /** @see Map#get */ + @Override public StateManager get(Object key) { - return (StateManager) cache.get(key); + return cache.get(key); } /** @see Map#remove */ + @Override public StateManager remove(Object key) { - return (StateManager) cache.remove(key); + return cache.remove(key); } /** @see Map#clear */ + @Override public void clear() { cache.clear(); } /** @see Map#isEmpty */ + @Override public boolean isEmpty() { return cache.isEmpty(); } /** @see Map#size */ + @Override public int size() { return cache.getEntryCount(); } @@ -650,6 +564,7 @@ interface CacheFactory { static class BasicCacheFactory implements CacheFactory { /** @return an instance of a BasicVCCache. */ + @Override public VCCache create() { return new BasicVCCache(); } @@ -659,6 +574,7 @@ public VCCache create() { static class LruCacheFactory implements CacheFactory { /** @return an instance of a LruVCCache. */ + @Override public VCCache create() { return new LruVCCache(maxEntries, timeout, loadFactor); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ClassDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ClassDesc.java index 6a2717022a6..8dd8d0c362b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ClassDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ClassDesc.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 */ -/* - * ClassDesc.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.model; import com.sun.jdo.api.persistence.model.Model; @@ -30,19 +24,20 @@ 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.MappingFieldElement; +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.MappingTableElement; 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.MappingReferenceKeyElementImpl; import com.sun.jdo.api.persistence.model.mapping.impl.MappingRelationshipElementImpl; import com.sun.jdo.api.persistence.model.mapping.impl.MappingTableElementImpl; +import com.sun.jdo.api.persistence.model.util.ModelValidationException; import com.sun.jdo.api.persistence.support.JDOException; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.api.persistence.support.JDOFatalUserException; import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; import com.sun.jdo.spi.persistence.support.sqlstore.ActionDesc; import com.sun.jdo.spi.persistence.support.sqlstore.ConfigCache; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceStore; import com.sun.jdo.spi.persistence.support.sqlstore.RetrieveDesc; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; @@ -57,8 +52,8 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.concurrency.ConcurrencyOptVerify; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateQueryPlan; 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.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; @@ -73,15 +68,21 @@ import org.glassfish.persistence.common.I18NHelper; import org.netbeans.modules.dbschema.ColumnElement; import org.netbeans.modules.dbschema.ColumnPairElement; +import org.netbeans.modules.dbschema.DBMemberElement; import org.netbeans.modules.dbschema.TableElement; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; + /** * */ public class ClassDesc implements com.sun.jdo.spi.persistence.support.sqlstore.PersistenceConfig { - private ArrayList fetchGroups; + private List> fetchGroups; private int maxHierarchicalGroupID; @@ -92,22 +93,22 @@ public class ClassDesc private boolean hasLocalNonDFGField; /** Contains all local and foreign fields. */ - public ArrayList fields; + public List fields; /** Contains all hidden fields. */ - public ArrayList hiddenFields; + public List hiddenFields; /** Contains all relationship fields. */ - public ArrayList foreignFields; + public List foreignFields; /** Contains the fields used for version consistency validation. */ private LocalFieldDesc[] versionFields; - private ArrayList tables; + private ArrayList tables; - private Class pcClass; + private Class pcClass; - private Class oidClass; + private Class oidClass; public int maxFields; @@ -127,7 +128,7 @@ public class ClassDesc private ClassLoader classLoader; - private Constructor constructor; + private Constructor constructor; private PersistenceClassElement pcElement; @@ -138,24 +139,24 @@ public class ClassDesc private LocalFieldDesc[] keyFieldDescs; /** The logger. */ - private static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(ClassDesc.class.getName(), RESOURCE_BUNDLE); /** RetrieveDescriptor cache for navigation and reloading. */ - private final Map retrieveDescCache = new HashMap(); + private final Map retrieveDescCache = new HashMap<>(); /** * RetrieveDescriptor cache for navigation queries. This cache * holds foreign RetrieveDescriptors constrained by the relationship * key values. */ - private final Map foreignRetrieveDescCache = new HashMap(); + private final Map foreignRetrieveDescCache = new HashMap<>(); /** Retrieve descriptor for version consistency verification. */ private RetrieveDesc retrieveDescForVerification; private Object retrieveDescForVerificationSynchObj = new Object(); /** UpdateQueryPlan cache. */ - private final Map updateQueryPlanCache = new HashMap(); + private final Map updateQueryPlanCache = new HashMap<>(); /** UpdateQueryPlan for insert. */ private UpdateQueryPlan updateQueryPlanForInsert; @@ -167,13 +168,13 @@ public class ClassDesc /** I18N message handler. */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", ClassDesc.class.getClassLoader()); /** PC Constructor signature. */ - private static final Class[] sigSM = new Class[]{StateManager.class}; + private static final Class[] sigSM = new Class[]{StateManager.class}; - public ClassDesc(MappingClassElement mdConfig, Class pcClass) { + public ClassDesc(MappingClassElement mdConfig, Class pcClass) { this.mdConfig = (MappingClassElementImpl) mdConfig; pcElement = this.mdConfig.getPersistenceElement(); @@ -185,16 +186,17 @@ public ClassDesc(MappingClassElement mdConfig, Class pcClass) { } catch (Exception e) { // Persistence capable classes must provide this constructor throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "jdo.persistencemanagerimpl.assertpersistencecapable.error", // NOI18N + "jdo.persistencemanagerimpl.assertpersistencecapable.error", pcClass.getName()), e); } - fields = new ArrayList(); - foreignFields = new ArrayList(); - tables = new ArrayList(); - fetchGroups = new ArrayList(); + fields = new ArrayList<>(); + foreignFields = new ArrayList<>(); + tables = new ArrayList<>(); + fetchGroups = new ArrayList<>(); } + @Override public String toString() { return getName(); } @@ -205,7 +207,7 @@ public String toString() { * @param pcClass The persistence capable class. * @return A new instance of ClassDesc. */ - static ClassDesc newInstance(Class pcClass) { + static ClassDesc newInstance(Class pcClass) { Model model = Model.RUNTIME; String className = pcClass.getName(); ClassLoader classLoader = pcClass.getClassLoader(); @@ -224,10 +226,10 @@ static ClassDesc newInstance(Class pcClass) { throw e; } catch (IllegalArgumentException e) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.loadfailed.class", className), e); // NOI18N + "core.configuration.loadfailed.class", className), e); } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.loadfailed.class", className), e); // NOI18N + "core.configuration.loadfailed.class", className), e); } return rc; @@ -248,32 +250,29 @@ static ClassDesc newInstance(Class pcClass) { static private void validateModel(Model model, String className, ClassLoader classLoader) { - Collection c = null; + Collection c = null; if (!(c = model.validate(className, classLoader, null)).isEmpty()) { - Iterator iter = c.iterator(); + Iterator iter = c.iterator(); StringBuffer validationMsgs = new StringBuffer(); while (iter.hasNext()) { - Exception ex = (Exception) iter.next(); + Exception ex = iter.next(); String validationMsg = ex.getLocalizedMessage(); - logger.fine(I18NHelper.getMessage(messages, - "core.configuration.validationproblem", // NOI18N + LOG.log(DEBUG, () -> I18NHelper.getMessage(messages, + "core.configuration.validationproblem", className, validationMsg)); - validationMsgs.append(validationMsg).append('\n'); // NOI18N + validationMsgs.append(validationMsg).append('\n'); } throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.validationfailed", // NOI18N + "core.configuration.validationfailed", className, validationMsgs.toString())); } } public void initialize(ConfigCache cache) { - boolean debug = logger.isLoggable(); - if (debug) { - logger.fine("sqlstore.model.classdesc.persistconfiginit", mdConfig); // NOI18N - } + LOG.log(DEBUG, "sqlstore.model.classdesc.persistconfiginit", mdConfig); loadOidClass(); initializeFields(); @@ -299,14 +298,14 @@ public void initialize(ConfigCache cache) { } maxFields = maxVisibleFields + maxHiddenFields; - if (debug) { - logger.fine("sqlstore.model.classdesc.persistconfiginit.exit"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.model.classdesc.persistconfiginit.exit"); } private void loadOidClass() { - if (oidClass != null) return; + if (oidClass != null) { + return; + } String keyClassName = pcElement.getKeyClass(); String suffix = keyClassName.substring(keyClassName.length() - 4); @@ -314,7 +313,7 @@ private void loadOidClass() { // First check whether the key class name ends with ".oid". // If so, we need to convert it '.' to '$' because is it // an inner class. - if (suffix.compareToIgnoreCase(".oid") == 0) { // NOI18N + if (suffix.compareToIgnoreCase(".oid") == 0) { StringBuffer buf = new StringBuffer(keyClassName); buf.setCharAt(buf.length() - 4, '$'); @@ -325,12 +324,10 @@ private void loadOidClass() { oidClass = Class.forName(keyClassName, true, classLoader); } catch (Throwable e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.cantloadclass", keyClassName)); // NOI18N + "core.configuration.cantloadclass", keyClassName)); } - if (logger.isLoggable()) { - logger.fine("sqlstore.model.classdesc.loadedclass", oidClass); // NOI18N - } + LOG.log(DEBUG, "sqlstore.model.classdesc.loadedclass", oidClass); } /** @@ -338,7 +335,7 @@ private void loadOidClass() { * the value for maxVisibleFields. */ private void initializeFields() { - ArrayList concurrencyGroups = new ArrayList(); + ArrayList concurrencyGroups = new ArrayList<>(); persistentFields = pcElement.getFields(); for (int i = 0; i < persistentFields.length; i++) { @@ -347,7 +344,7 @@ private void initializeFields() { if (mdf == null) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.fieldnotmapped", // NOI18N + "core.configuration.fieldnotmapped", pcf.getName(), pcElement.getName())); } @@ -371,7 +368,7 @@ private void initializeFields() { throw e; } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.loadfailed.field", // NOI18N + "core.configuration.loadfailed.field", pcf.getName(), pcElement.getName()), e); } @@ -379,10 +376,7 @@ private void initializeFields() { addField(f); - if (logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {f.getName(),new Integer(f.absoluteID)}; - logger.finest("sqlstore.model.classdesc.fieldinfo", items); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.fieldinfo", f.getName(),f.absoluteID); } this.maxVisibleFields = fields.size(); @@ -394,15 +388,16 @@ private void initializeFields() { * @param mdf Input MappingFieldElementImpl */ private LocalFieldDesc createLocalField(MappingFieldElementImpl mdf) { - ArrayList columnDesc = mdf.getColumnObjects(); - + List columnDesc = mdf.getColumnObjects(); // Make sure this field is properly mapped. - if ((columnDesc == null) || (columnDesc.size() == 0)) { + if (columnDesc == null || columnDesc.isEmpty()) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.fieldnotmapped", // NOI18N + "core.configuration.fieldnotmapped", mdf.getName(), pcElement.getName())); } - return new LocalFieldDesc(this, columnDesc); + List columns = new ArrayList<>(); + columns.addAll(mdf.getColumnObjects().stream().map(ColumnElement.class::cast).toList()); + return new LocalFieldDesc(this, columns); } /** @@ -414,22 +409,20 @@ private LocalFieldDesc createLocalField(MappingFieldElementImpl mdf) { * @return New instance of LocalFieldDesc */ private LocalFieldDesc createLocalHiddenField(ColumnElement column) { - ArrayList columnDesc = new ArrayList(); + List columnDesc = new ArrayList<>(); columnDesc.add(column); LocalFieldDesc lf = new LocalFieldDesc(this, columnDesc); if (hiddenFields == null) { - hiddenFields = new ArrayList(); + hiddenFields = new ArrayList<>(); } hiddenFields.add(lf); // AbsouluteID for hidden fields must be < 0. lf.absoluteID = -hiddenFields.size(); - if (logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {pcClass,lf.getName(),column.getName().getFullName()}; - logger.finest("sqlstore.model.classdesc.getlocalfielddesc", items); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.getlocalfielddesc", pcClass, lf.getName(), + column.getName().getFullName()); return lf; } @@ -458,7 +451,7 @@ private FieldDesc createForeignField(RelationshipElement fpcf, try { ff.setComponentType(Class.forName(fpcf.getElementClass(), true, classLoader)); } catch (Throwable e) { - logger.log(Logger.WARNING, "sqlstore.exception.log", e); + LOG.log(WARNING, "setComponentType failed.", e); } } @@ -466,15 +459,15 @@ private FieldDesc createForeignField(RelationshipElement fpcf, } private void initializeColumnLists(ForeignFieldDesc ff, MappingRelationshipElementImpl fmdf) { - ArrayList assocPairs = fmdf.getAssociatedColumnObjects(); - ArrayList pairs = fmdf.getColumnObjects(); - ArrayList localColumns = new ArrayList(); - ArrayList foreignColumns = new ArrayList(); + List assocPairs = fmdf.getAssociatedColumnObjects(); + List pairs = fmdf.getColumnObjects(); + List localColumns = new ArrayList<>(); + List foreignColumns = new ArrayList<>(); // We need to go through each local column and extract the foreign column. if ((assocPairs == null) || (assocPairs.size() == 0)) { for (int i = 0; i < pairs.size(); i++) { - ColumnPairElement fce = (ColumnPairElement) pairs.get(i); + ColumnPairElement fce = pairs.get(i); localColumns.add(fce.getLocalColumn()); foreignColumns.add(fce.getReferencedColumn()); } @@ -482,17 +475,17 @@ private void initializeColumnLists(ForeignFieldDesc ff, MappingRelationshipEleme ff.localColumns = localColumns; ff.foreignColumns = foreignColumns; } else { - ArrayList assocLocalColumns = new ArrayList(); - ArrayList assocForeignColumns = new ArrayList(); + List assocLocalColumns = new ArrayList<>(); + List assocForeignColumns = new ArrayList<>(); for (int i = 0; i < pairs.size(); i++) { - ColumnPairElement alc = (ColumnPairElement) pairs.get(i); + ColumnPairElement alc = pairs.get(i); localColumns.add(alc.getLocalColumn()); assocLocalColumns.add(alc.getReferencedColumn()); } for (int i = 0; i < assocPairs.size(); i++) { - ColumnPairElement afc = (ColumnPairElement) assocPairs.get(i); + ColumnPairElement afc = assocPairs.get(i); assocForeignColumns.add(afc.getLocalColumn()); foreignColumns.add(afc.getReferencedColumn()); } @@ -507,7 +500,7 @@ private void initializeColumnLists(ForeignFieldDesc ff, MappingRelationshipEleme private void initializeFetchAndConcurrencyGroup(FieldDesc f, PersistenceFieldElement pcf, MappingFieldElementImpl mdf, - ArrayList concurrencyGroups) { + List concurrencyGroups) { f.fetchGroup = mdf.getFetchGroup(); // RESOLVE: For now, we can only handle one concurrency group per field @@ -535,12 +528,12 @@ private void initializeFetchAndConcurrencyGroup(FieldDesc f, } } - private void createSecondaryTableKey(TableDesc table, MappingReferenceKeyElementImpl mappingSecondaryKey) { + private void createSecondaryTableKey(TableDesc table, MappingReferenceKeyElement mappingSecondaryKey) { - ColumnPairElement pairs[] = mappingSecondaryKey.getColumnPairs(); + ColumnPairElement[] pairs = mappingSecondaryKey.getColumnPairs(); KeyDesc referencingKey = new KeyDesc(); KeyDesc referencedKey = new KeyDesc(); - TableDesc secondaryTable = findTableDesc(((MappingTableElementImpl) mappingSecondaryKey.getTable()).getTableObject()); + TableDesc secondaryTable = findTableDesc(mappingSecondaryKey.getTable().getTableObject()); for (int i = 0; i < pairs.length; i++) { ColumnPairElement pair = pairs[i]; @@ -571,24 +564,24 @@ private void createSecondaryTableKey(TableDesc table, MappingReferenceKeyElement * This method maps all the tables. */ private void initializeTables() { - ArrayList mdTables = mdConfig.getTables(); + List mdTables = mdConfig.getTables(); createTables(mdTables); processSecondaryTables(mdTables); } - private void createTables(ArrayList mdTables) { + private void createTables(List mdTables) { for (int i = 0; i < mdTables.size(); i++) { MappingTableElementImpl mdt = (MappingTableElementImpl) mdTables.get(i); TableDesc t = new TableDesc(mdt.getTableObject()); - ArrayList keys = mdt.getKeyObjects(); + List keys = mdt.getKeyObjects(); KeyDesc key = new KeyDesc(); t.setKey(key); key.addColumns(keys); for (int j = 0; j < keys.size(); j++) { - ColumnElement c = (ColumnElement) keys.get(j); + ColumnElement c = keys.get(j); if (c != null) { key.addField(getLocalFieldDesc(c)); @@ -607,28 +600,28 @@ private void createTables(ArrayList mdTables) { * NOTE: This method assumes that the entries of mdTables * and tables are sorted in the same order. */ - private void processSecondaryTables(ArrayList mdTables) { + private void processSecondaryTables(List mdTables) { for (int i = 0; i < tables.size(); i++) { MappingTableElementImpl mdt = (MappingTableElementImpl) mdTables.get(i); - TableDesc t = (TableDesc) tables.get(i); - ArrayList secondaryKeys = mdt.getReferencingKeys(); + TableDesc t = tables.get(i); + List secondaryKeys = mdt.getReferencingKeys(); for (int j = 0; j < secondaryKeys.size(); j++) { - MappingReferenceKeyElementImpl mappingSecondaryKey = (MappingReferenceKeyElementImpl) secondaryKeys.get(j); + MappingReferenceKeyElement mappingSecondaryKey = secondaryKeys.get(j); createSecondaryTableKey(t, mappingSecondaryKey); } } } private void initializeJoinTables() { - Iterator iter = foreignFields.iterator(); + Iterator iter = foreignFields.iterator(); while (iter.hasNext()) { - ForeignFieldDesc ff = (ForeignFieldDesc) iter.next(); + ForeignFieldDesc ff = iter.next(); if (ff.useJoinTable()) { - TableElement joinTable = ((ColumnElement) ff.assocLocalColumns.get(0)).getDeclaringTable(); + TableElement joinTable = ff.assocLocalColumns.get(0).getDeclaringTable(); TableDesc joinTableDesc = findTableDesc(joinTable); if (joinTableDesc == null) { @@ -650,7 +643,7 @@ private void initializeJoinTables() { * for FieldDesc.GROUP_NONE is empty. * @see #initializeFetchGroups */ - public ArrayList getFetchGroup(int groupID) { + public List getFetchGroup(int groupID) { int index = 0; if (groupID >= FieldDesc.GROUP_NONE) { @@ -663,10 +656,10 @@ public ArrayList getFetchGroup(int groupID) { fetchGroups.add(null); } - ArrayList group = (ArrayList) fetchGroups.get(index); + List group = fetchGroups.get(index); if (group == null) { - group = new ArrayList(); + group = new ArrayList<>(); fetchGroups.set(index, group); } @@ -693,18 +686,19 @@ private void addForeignField(ForeignFieldDesc f) { private void initializeFetchGroups() { for (int i = 0; i < 2; i++) { - ArrayList theFields = null; + List theFields = null; if (i == 0) { theFields = fields; } else { // It is possible to have hidden fields in the DFG. - if ((theFields = hiddenFields) == null) + if ((theFields = hiddenFields) == null) { continue; + } } for (int j = 0; j < theFields.size(); j++) { - FieldDesc f = (FieldDesc) theFields.get(j); + FieldDesc f = theFields.get(j); // Do not add the field to the fetch group for GROUP_NONE. if (f.fetchGroup > FieldDesc.GROUP_NONE) { @@ -722,7 +716,7 @@ private void initializeFetchGroups() { this.maxHierarchicalGroupID = fetchGroups.size() - 1; for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); // Do not add the field to the fetch group for GROUP_NONE. if (f.fetchGroup < FieldDesc.GROUP_NONE) { @@ -743,33 +737,29 @@ private void initializeConcurrency() { } private void initializeKeyFields() { - boolean debug = logger.isLoggable(Logger.FINEST); - if (oidClass == null) + if (oidClass == null) { return; + } keyFields = oidClass.getFields(); keyFieldNames = new String[keyFields.length]; keyFieldDescs = new LocalFieldDesc[keyFields.length]; - if (debug) { - logger.finest("sqlstore.model.classdesc.createsqldesc", oidClass); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.createsqldesc", oidClass); for (int i = 0; i < keyFields.length; i++) { Field kf = keyFields[i]; String name = kf.getName(); keyFieldNames[i] = name; - if (name.equals("serialVersionUID")) { // NOI18N + if (name.equals("serialVersionUID")) { continue; } LocalFieldDesc f = getLocalFieldDesc(name); if (f != null) { - if (debug) { - logger.finest("sqlstore.model.classdesc.pkfield", f.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.pkfield", f.getName()); // The fetch group for pk fields should always be DFG. f.fetchGroup = FieldDesc.GROUP_DEFAULT; @@ -780,7 +770,7 @@ private void initializeKeyFields() { keyFieldDescs[i] = f; } else { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.noneexistentpkfield", // NOI18N + "core.configuration.noneexistentpkfield", name, oidClass.getName(), pcClass.getName())); } } @@ -793,17 +783,15 @@ private void initializeKeyFields() { */ private void initializeVersionFields() { int size = mdConfig.getVersionFields().size(); - Iterator versionFieldIterator = mdConfig.getVersionFields().iterator(); + Iterator versionFieldIterator = mdConfig.getVersionFields().iterator(); versionFields = new LocalFieldDesc[size]; for (int i = 0; i < size; i++) { - MappingFieldElement mdField = (MappingFieldElement) versionFieldIterator.next(); + MappingFieldElement mdField = versionFieldIterator.next(); LocalFieldDesc f = (LocalFieldDesc) getField(mdField.getName()); if (f != null) { - if (logger.isLoggable()) { - logger.finest("sqlstore.model.classdesc.vcfield", f.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.vcfield", f.getName()); versionFields[i] = f; registerVersionFieldWithTable(f); @@ -814,25 +802,25 @@ private void initializeVersionFields() { f.sqlProperties |= FieldDesc.PROP_VERSION_FIELD; } else { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.noneexistentvcfield", // NOI18N + "core.configuration.noneexistentvcfield", mdField.getName(), pcClass.getName())); } } } /** - * Registers the version field versionField with the + * Registers the version field versionField with the * corresponding table. * * @param versionField Field used in version consistency check. */ private void registerVersionFieldWithTable(LocalFieldDesc versionField) { // Version field must be mapped to exactly one column. - ColumnElement ce = (ColumnElement) versionField.getColumnElements().next(); - Iterator iter = tables.iterator(); + ColumnElement ce = versionField.getColumnElements().next(); + Iterator iter = tables.iterator(); while (iter.hasNext()) { - TableDesc table = (TableDesc) iter.next(); + TableDesc table = iter.next(); if (!table.isJoinTable()) { if (ce.getDeclaringTable() == table.getTableElement()) { @@ -853,7 +841,7 @@ private void registerVersionFieldWithTable(LocalFieldDesc versionField) { private void computeTrackedPrimitiveFields() { // Compute the list of primitive fields to track for each primitive field. for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); if (!f.isRelationshipField()) { LocalFieldDesc lf = (LocalFieldDesc) f; @@ -886,7 +874,7 @@ private void computeTrackedPrimitiveFields() { private void computeTrackedRelationshipFields() { // Compute the list of fields to track for each field. for (int i = 0; i < 2; i++) { - ArrayList theFields = null; + List theFields = null; // We first check all the visible fields and then the hidden fields. if (i == 0) { @@ -898,7 +886,7 @@ private void computeTrackedRelationshipFields() { } for (int j = 0; j < theFields.size(); j++) { - FieldDesc f = (FieldDesc) theFields.get(j); + FieldDesc f = theFields.get(j); f.computeTrackedRelationshipFields(); } @@ -911,7 +899,7 @@ private void computeTrackedRelationshipFields() { private void cleanupTrackedFields() { for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); if (f instanceof LocalFieldDesc) { ((LocalFieldDesc) f).cleanupTrackedFields(); @@ -928,8 +916,8 @@ private void cleanupTrackedFields() { private void fixupForeignReferences(ConfigCache cache) { for (int i = 0; i < foreignFields.size(); i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); - Class classType = null; + ForeignFieldDesc ff = foreignFields.get(i); + Class classType = null; if ((classType = ff.getComponentType()) == null) { classType = ff.getType(); @@ -937,7 +925,9 @@ private void fixupForeignReferences(ConfigCache cache) { ClassDesc foreignConfig = (ClassDesc) cache.getPersistenceConfig(classType); - if (foreignConfig == null) continue; + if (foreignConfig == null) { + continue; + } // Look up the inverse relationship field name if there is any. String irName = pcElement.getRelationship(ff.getName()).getInverseRelationshipName(); @@ -954,7 +944,7 @@ private void fixupForeignReferences(ConfigCache cache) { private void fixupFieldProperties() { for (int i = 0; i < foreignFields.size(); i++) { - ForeignFieldDesc ff = (ForeignFieldDesc) foreignFields.get(i); + ForeignFieldDesc ff = foreignFields.get(i); ff.fixupFieldProperties(); } } @@ -963,7 +953,7 @@ LocalFieldDesc getLocalFieldDesc(ColumnElement column) { LocalFieldDesc result; for (int i = 0; i < 2; i++) { - ArrayList theFields = null; + List theFields = null; if (i == 0) { theFields = fields; @@ -973,13 +963,13 @@ LocalFieldDesc getLocalFieldDesc(ColumnElement column) { if (theFields != null) { for (int j = 0; j < theFields.size(); j++) { - FieldDesc f = (FieldDesc) theFields.get(j); + FieldDesc f = theFields.get(j); if (f instanceof LocalFieldDesc) { result = (LocalFieldDesc) f; for (int k = 0; k < result.columnDescs.size(); k++) { - ColumnElement c = (ColumnElement) result.columnDescs.get(k); + ColumnElement c = result.columnDescs.get(k); // if (c.equals(column)) if (c.getName().getFullName().compareTo(column.getName().getFullName()) == 0) { @@ -1017,14 +1007,14 @@ public LocalFieldDesc getLocalFieldDesc(String name) { if (desc == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.unknownfield", // NOI18N + "core.generic.unknownfield", name, getName())); } if (!(desc instanceof LocalFieldDesc)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - desc.getClass().getName(), "LocalFieldDesc")); // NOI18N + "core.generic.notinstanceof", + desc.getClass().getName(), "LocalFieldDesc")); } return ((LocalFieldDesc) desc); @@ -1032,7 +1022,7 @@ public LocalFieldDesc getLocalFieldDesc(String name) { public TableDesc findTableDesc(TableElement mdTable) { for (int i = 0; i < tables.size(); i++) { - TableDesc t = (TableDesc) tables.get(i); + TableDesc t = tables.get(i); if (t.getTableElement().equals(mdTable)) { return t; @@ -1058,7 +1048,7 @@ public int getTableIndex(TableDesc tableDesc) { public FieldDesc getField(String name) { for (int i = 0; i < fields.size(); i++) { - FieldDesc f = (FieldDesc) fields.get(i); + FieldDesc f = fields.get(i); if ((f != null) && (f.getName().compareTo(name) == 0)) { return f; @@ -1067,7 +1057,7 @@ public FieldDesc getField(String name) { if (hiddenFields != null) { for (int i = 0; i < hiddenFields.size(); i++) { - FieldDesc f = (FieldDesc) hiddenFields.get(i); + FieldDesc f = hiddenFields.get(i); if (f.getName().compareTo(name) == 0) { return f; @@ -1080,21 +1070,24 @@ public FieldDesc getField(String name) { public FieldDesc getField(int index) { if (index >= 0) { - return (FieldDesc) fields.get(index); + return fields.get(index); } else { - return (FieldDesc) hiddenFields.get(-(index + 1)); + return hiddenFields.get(-(index + 1)); } } - public Constructor getConstructor() { + @Override + public Constructor getConstructor() { return constructor; } - public Class getPersistenceCapableClass() { + @Override + public Class getPersistenceCapableClass() { return pcClass; } - public Class getOidClass() { + @Override + public Class getOidClass() { return oidClass; } @@ -1102,18 +1095,19 @@ public String getName() { return pcClass.getName(); } - public Iterator getTables() { + public Iterator getTables() { return tables.iterator(); } public TableDesc getPrimaryTable() { - return (TableDesc) tables.get(0); + return tables.get(0); } public boolean isNavigable() { return mdConfig.isNavigable(); } + @Override public boolean hasVersionConsistency() { return mdConfig.getConsistencyLevel() == MappingClassElement.VERSION_CONSISTENCY; } @@ -1175,7 +1169,7 @@ public Concurrency getConcurrency(boolean optimistic) { // consistency level default : throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "core.configuration.unsupportedconsistencylevel", pcClass));// NOI18N + "core.configuration.unsupportedconsistencylevel", pcClass)); } } @@ -1202,6 +1196,7 @@ public boolean isPKField(int index) { * Return the key fields as array of java.lang.reflect.Field instances. * @return The key fields as array of java.lang.reflect.Field instances. */ + @Override public Field[] getKeyFields() { return keyFields; } @@ -1210,6 +1205,7 @@ public Field[] getKeyFields() { * Returns the key field names as array of String. * @return The key field names as array of String. */ + @Override public String[] getKeyFieldNames() { return keyFieldNames; } @@ -1259,7 +1255,7 @@ public RetrieveDesc getRetrieveDescForPKQuery(FieldDesc additionalField, Persist synchronized (retrieveDescCache) { // Cache lookup. - rd = (RetrieveDescImpl) retrieveDescCache.get(cacheKey); + rd = retrieveDescCache.get(cacheKey); // Generate a new RD if there isn't one be found in the cache. if (rd == null) { rd = (RetrieveDescImpl) store.getRetrieveDesc(pcClass); @@ -1269,8 +1265,8 @@ public RetrieveDesc getRetrieveDescForPKQuery(FieldDesc additionalField, Persist // If the additionalField is not null, we will retrieve // the field indicated by it along with the query. if (additionalField instanceof ForeignFieldDesc) { - Class additionalClass = ((ForeignFieldDesc) additionalField). - foreignConfig.getPersistenceCapableClass(); + Class additionalClass = ((ForeignFieldDesc) additionalField).foreignConfig + .getPersistenceCapableClass(); frd = store.getRetrieveDesc(additionalClass); } @@ -1320,7 +1316,7 @@ public RetrieveDesc getRetrieveDescForFKQuery(ForeignFieldDesc foreignField, Per synchronized (foreignRetrieveDescCache) { // Cache lookup. - rd = (RetrieveDescImpl) foreignRetrieveDescCache.get(cacheKey); + rd = foreignRetrieveDescCache.get(cacheKey); // Generate a new RD if there isn't one be found in the cache. if (rd == null) { rd = (RetrieveDescImpl) store.getRetrieveDesc(foreignField.foreignConfig.getPersistenceCapableClass()); @@ -1376,7 +1372,7 @@ private int addPKConstraints(RetrieveDescImpl rd) { */ private void addFKConstraints(RetrieveDescImpl rd, ForeignFieldDesc foreignField) { for (int i = 0; i < foreignField.foreignFields.size(); i++) { - LocalFieldDesc fff = (LocalFieldDesc) foreignField.foreignFields.get(i); + LocalFieldDesc fff = foreignField.foreignFields.get(i); rd.addParameterConstraint(fff, i); } } @@ -1423,6 +1419,7 @@ private String generateRDCacheKey(FieldDesc additionalField) * fetch group. * @see SQLStateManager#requiresImmediateFlush */ + @Override public boolean hasLocalNonDFGFields() { // All instances with modified DFG fields can be batched with // the same statement. If there's a primitive field outside @@ -1485,7 +1482,7 @@ private UpdateQueryPlan getUpdateQueryPlanForUpdate( String key = getSortedFieldNumbers(desc.getUpdatedFields()); UpdateQueryPlan plan; synchronized(updateQueryPlanCache) { - plan = (UpdateQueryPlan)updateQueryPlanCache.get(key); + plan = updateQueryPlanCache.get(key); if (plan == null) { plan = buildQueryPlan(store, desc); updateQueryPlanCache.put(key, plan); @@ -1496,7 +1493,7 @@ private UpdateQueryPlan getUpdateQueryPlanForUpdate( /** * Builds and initializes a new query plan based on the information - * passed with the desc parameter. The returned plan + * passed with the desc parameter. The returned plan * and its related data structures will be readonly. * * @param store Store manager @@ -1527,13 +1524,13 @@ private UpdateQueryPlan buildQueryPlan(SQLStoreManager store, * @param fields the list of FieldDescs * @return the sorted field number string */ - private String getSortedFieldNumbers(List fields) + private String getSortedFieldNumbers(List fields) { // Use the array of field numbers of the updated fields as the key int size = fields.size(); int [] fieldNos = new int[size]; for (int i = 0; i < size; i++) { - FieldDesc f = (FieldDesc)fields.get(i); + FieldDesc f = fields.get(i); fieldNos[i] = f.absoluteID; } Arrays.sort(fieldNos); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ConfigCacheImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ConfigCacheImpl.java index 5e8b8d4a16e..10a9385c41c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ConfigCacheImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ConfigCacheImpl.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 @@ -18,20 +19,22 @@ import com.sun.jdo.api.persistence.model.Model; import com.sun.jdo.spi.persistence.support.sqlstore.ConfigCache; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceConfig; import com.sun.jdo.spi.persistence.support.sqlstore.VersionConsistencyCache; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.ApplicationLifeCycleEventListener; import com.sun.jdo.spi.persistence.support.sqlstore.ejb.EJBHelper; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.TypeTable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** * Caches SQLStore config information. * @@ -43,12 +46,12 @@ public class ConfigCacheImpl /** * Map of class types to PersistenceConfig. */ - private Map classConfigs; + private Map, ClassDesc> classConfigs; /** * Map of OID classes to PersistenceCapable classes. */ - private Map oidClassToClassType; + private Map, Class> oidClassToClassType; /** * This cache should be notified every time a VC class @@ -60,15 +63,15 @@ public class ConfigCacheImpl * Map of class loaders to a list of PersistenceCapable * classes loaded by the classloader. */ - private Map classLoaderToClassType; + private Map>> classLoaderToClassType; /** The logger. */ - protected final static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(ConfigCacheImpl.class.getName(), RESOURCE_BUNDLE); public ConfigCacheImpl() { - classConfigs = new HashMap(); - classLoaderToClassType = new HashMap(); - oidClassToClassType = new HashMap(); + classConfigs = new HashMap<>(); + classLoaderToClassType = new HashMap<>(); + oidClassToClassType = new HashMap<>(); // Register for call backs on application loader events. EJBHelper.registerApplicationLifeCycleEventListener(this); @@ -82,9 +85,9 @@ public ConfigCacheImpl() { * @param pcClass The input pcClass. * @return PersistenceConfig for given pcClass. */ - public synchronized PersistenceConfig getPersistenceConfig(Class pcClass) { - ClassDesc sqlConfig = - (ClassDesc) classConfigs.get(pcClass); + @Override + public synchronized PersistenceConfig getPersistenceConfig(Class pcClass) { + ClassDesc sqlConfig = classConfigs.get(pcClass); if (sqlConfig == null) { // The order of the below operations is important. // Initialize is called after puting sqlConfig into the @@ -109,40 +112,38 @@ public synchronized PersistenceConfig getPersistenceConfig(Class pcClass) { * @param oidType The input oidType. * @return The Class instance corresponding to given oidType. */ - public Class getClassByOidClass(Class oidType) { - return (Class) oidClassToClassType.get(oidType); + @Override + public Class getClassByOidClass(Class oidType) { + return oidClassToClassType.get(oidType); } - /** - * @inheritDoc - */ + @Override public void notifyApplicationUnloaded(ClassLoader classLoader) { - boolean debug = logger.isLoggable(Logger.FINEST); + boolean debug = LOG.isLoggable(TRACE); // Clean up classConfigs and oidClassToClassType for the given // classLoader. synchronized (this) { if (debug) { Object[] items = new Object[] {"classLoaderToClassType", classLoaderToClassType.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_before",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_before",items); } - List pcClasses = (List) classLoaderToClassType.get(classLoader); + List> pcClasses = classLoaderToClassType.get(classLoader); if (pcClasses != null) { if (debug) { Object[] items = new Object[] {"classConfigs", classConfigs.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_before",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_before",items); items = new Object[] {"oidClassToClassType", oidClassToClassType.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_before",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_before",items); } - Iterator it = pcClasses.iterator(); + Iterator> it = pcClasses.iterator(); while (it.hasNext()) { - Class classType = (Class) it.next(); - ClassDesc config = - (ClassDesc) classConfigs.remove(classType); - Class oidClass = config.getOidClass(); + Class classType = it.next(); + ClassDesc config = classConfigs.remove(classType); + Class oidClass = config.getOidClass(); oidClassToClassType.remove(oidClass); if (config.hasVersionConsistency() && vcCache != null) { vcCache.removePCType(classType); @@ -150,10 +151,10 @@ public void notifyApplicationUnloaded(ClassLoader classLoader) { } if (debug) { Object[] items = new Object[] {"classConfigs", classConfigs.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_after",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_after",items); items = new Object[] {"oidClassToClassType", oidClassToClassType.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_after",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_after",items); } // Data about this classLoader is no longer needed. @@ -161,7 +162,7 @@ public void notifyApplicationUnloaded(ClassLoader classLoader) { classLoaderToClassType.remove(classLoader); if (debug) { Object[] items = new Object[] {"classLoaderToClassType", classLoaderToClassType.size()}; - logger.finest("sqlstore.model.configcacheimpl.size_after",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.configcacheimpl.size_after",items); } } @@ -179,6 +180,7 @@ public void notifyApplicationUnloaded(ClassLoader classLoader) { * * @param vcCache the VersionConsistencyCache instance. */ + @Override public synchronized void setVersionConsistencyCache( VersionConsistencyCache vcCache) { this.vcCache = vcCache; @@ -191,12 +193,12 @@ public synchronized void setVersionConsistencyCache( * * @param pcClass The pcClass to be added. */ - private void addToClassLoaderMap(Class pcClass) { + private void addToClassLoaderMap(Class pcClass) { ClassLoader classLoader = pcClass.getClassLoader(); - List classes = (List) classLoaderToClassType.get(classLoader); + List> classes = classLoaderToClassType.get(classLoader); if (classes == null) { // First entry for a given ClassLoader, initialize the ArrayList. - classes = new ArrayList(); + classes = new ArrayList<>(); classLoaderToClassType.put(classLoader, classes); } classes.add(pcClass); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/FieldDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/FieldDesc.java index 2fd74f17074..a8fc5d6dec8 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/FieldDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/FieldDesc.java @@ -27,23 +27,28 @@ import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; import com.sun.jdo.spi.persistence.support.sqlstore.sco.SqlTimestamp; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; import org.netbeans.modules.dbschema.ColumnElement; +import static java.lang.System.Logger.Level.TRACE; + /** * */ public abstract class FieldDesc implements java.io.Serializable { + private static final long serialVersionUID = -941304938453639045L; + public static final int GROUP_DEFAULT = 1; public static final int GROUP_NONE = 0; @@ -126,7 +131,7 @@ public abstract class FieldDesc implements java.io.Serializable { private Field field; - private Class fieldType; + private Class fieldType; /** * Contains a translation from the field type class to int constants. @@ -136,22 +141,22 @@ public abstract class FieldDesc implements java.io.Serializable { private String fieldName; - private Class declaringClass; + private Class declaringClass; // Should be moved to ForeignFieldDesc. - private Class componentType; + private Class componentType; - private ArrayList trackedFields; + private List trackedFields; /** Back pointer to declaring class descriptor. */ protected final ClassDesc classDesc; /** The logger. */ - protected final static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(FieldDesc.class.getName(), LogHelperSQLStore.RESOURCE_BUNDLE); /** I18N message handler. */ protected final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", FieldDesc.class.getClassLoader()); FieldDesc(ClassDesc classDesc) { @@ -167,20 +172,23 @@ public abstract class FieldDesc implements java.io.Serializable { this.classDesc = classDesc; } + @Override public String toString() { - return classDesc.getName() + "." + getName(); // NOI18N + return classDesc.getName() + "." + getName(); } - public Class getComponentType() { + public Class getComponentType() { return componentType; } - public Class getDeclaringClass() { + public Class getDeclaringClass() { return declaringClass; } - public Class getType() { - if (fieldType != null) return fieldType; + public Class getType() { + if (fieldType != null) { + return fieldType; + } return Object.class; } @@ -190,14 +198,17 @@ public int getEnumType() { } public String getName() { - if (fieldName == null) - fieldName = "hidden" + -absoluteID; // NOI18N + if (fieldName == null) { + fieldName = "hidden" + -absoluteID; + } return fieldName; } public Object getValue(StateManager sm) { - if (sm == null) return null; + if (sm == null) { + return null; + } if (absoluteID >= 0) { return ((PersistenceCapable) sm.getPersistent()).jdoGetField(absoluteID); @@ -207,9 +218,11 @@ public Object getValue(StateManager sm) { } public void setValue(StateManager sm, Object value) { - boolean debug = logger.isLoggable(Logger.FINEST); + boolean debug = LOG.isLoggable(TRACE); - if (sm == null) return; + if (sm == null) { + return; + } if (absoluteID >= 0) { if (debug) { @@ -217,10 +230,10 @@ public void setValue(StateManager sm, Object value) { ((value instanceof com.sun.jdo.api.persistence.support.PersistenceCapable) || (value instanceof java.util.Collection))) { Object[] items = new Object[] {field.getName(),value.getClass()}; - logger.finest("sqlstore.model.fielddesc.fieldname",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.fielddesc.fieldname",items); } else { Object[] items = new Object[] {field.getName(),value}; - logger.finest("sqlstore.model.fielddesc.fieldname",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.fielddesc.fieldname",items); } } @@ -258,14 +271,14 @@ public void setValue(StateManager sm, Object value) { } else { if (debug) { Object[] items = new Object[] {getName(),value}; - logger.finest("sqlstore.model.fielddesc.fieldname",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.fielddesc.fieldname",items); } sm.setHiddenValue(absoluteID, value); } } - public ArrayList getTrackedFields() { + public List getTrackedFields() { return trackedFields; } @@ -291,23 +304,25 @@ public boolean isRelationshipField() { } public Object convertValue(Object value, StateManager sm) { - boolean debug = logger.isLoggable(Logger.FINEST); + boolean debug = LOG.isLoggable(TRACE); if (value == null) { - if (debug) - logger.finest("sqlstore.model.fielddesc.convertvalue"); // NOI18N + if (debug) { + LOG.log(TRACE, "sqlstore.model.fielddesc.convertvalue"); + } return value; } if (absoluteID < 0) { // Hidden field nothing to convert - if (debug) - logger.finest("sqlstore.model.fielddesc.convertvalue.hidden",new Integer(absoluteID)); // NOI18N + if (debug) { + LOG.log(TRACE, "sqlstore.model.fielddesc.convertvalue.hidden",new Integer(absoluteID)); + } return value; } if (debug) { Object[] items = new Object[] {value,value.getClass().getName(),fieldType}; - logger.finest("sqlstore.model.fielddesc.convertvalue.from_to",items); // NOI18N + LOG.log(TRACE, "sqlstore.model.fielddesc.convertvalue.from_to",items); } // Here, we'll try our best to convert the given value to the @@ -360,35 +375,39 @@ public Object convertValue(Object value, StateManager sm) { break; case FieldTypeEnumeration.FLOAT_PRIMITIVE: case FieldTypeEnumeration.FLOAT: - if (!(value instanceof Float)) + if (!(value instanceof Float)) { value = new Float(number.floatValue()); + } break; case FieldTypeEnumeration.DOUBLE_PRIMITIVE: case FieldTypeEnumeration.DOUBLE: if (!(value instanceof Double)) { // FIX FOR CONVERT FROM FLOAT. - if (value instanceof Float) + if (value instanceof Float) { value = new Double(number.toString()); - else + } else { value = new Double(number.doubleValue()); + } } break; case FieldTypeEnumeration.BIGDECIMAL: if (!(value instanceof BigDecimal)) { - if (value instanceof Double) + if (value instanceof Double) { value = new BigDecimal(number.doubleValue()); - else if (value instanceof BigInteger) + } else if (value instanceof BigInteger) { value = new BigDecimal((java.math.BigInteger) value); - else + } else { value = new BigDecimal(number.toString()); + } } break; case FieldTypeEnumeration.BIGINTEGER: if (!(value instanceof BigInteger)) { - if (value instanceof BigDecimal) + if (value instanceof BigDecimal) { value = ((BigDecimal) value).toBigInteger(); - else + } else { value = new BigInteger(number.toString()); + } } break; } @@ -426,8 +445,9 @@ else if (value instanceof BigInteger) // using its string value. if (!(value instanceof Boolean)) { if ((value instanceof String) && - (value).equals("1")) // NOI18N - value = "true"; // NOI18N + (value).equals("1")) { + value = "true"; + } value = new Boolean(value.toString()); } @@ -589,14 +609,16 @@ private void initializeSCO(Object scoVal, Object value) { private void assertIsValid(Number number, double min_value, double max_value) { double x = number.doubleValue(); - if (x < min_value) + if (x < min_value) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.fielddesc.minvalue", // NOI18N + "core.fielddesc.minvalue", new Object[]{number, String.valueOf(min_value), fieldType.getName()})); - if (x > max_value) + } + if (x > max_value) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.fielddesc.maxvalue", // NOI18N + "core.fielddesc.maxvalue", new Object[]{number, String.valueOf(max_value), fieldType.getName()})); + } } private void assertIsValidLong(Number number) { @@ -608,13 +630,13 @@ private void assertIsValidLong(Number number) { } if (bd.compareTo(LONG_MIN_VALUE) < 0) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.fielddesc.minvalue", // NOI18N + "core.fielddesc.minvalue", new Object[]{number, String.valueOf(Long.MIN_VALUE), fieldType.getName()})); } else if (bd.compareTo(LONG_MAX_VALUE) > 0) { throw new JDOUserException(I18NHelper.getMessage(messages, - "core.fielddesc.maxvalue", // NOI18N + "core.fielddesc.maxvalue", new Object[]{number, String.valueOf(Long.MAX_VALUE), fieldType.getName()})); } @@ -624,13 +646,13 @@ private void assertIsValidLong(Number number) { // ------------ Initialisation methods ------------ // - void setupDesc(final Class classType, final String name) { + void setupDesc(final Class classType, final String name) { Field field; try { field = classType.getDeclaredField(name); } catch (NoSuchFieldException e) { throw new JDOFatalUserException(I18NHelper.getMessage(messages, - "core.configuration.loadfailed.field", // NOI18N + "core.configuration.loadfailed.field", name, classType.getName()), e); } @@ -645,40 +667,60 @@ protected void setupDesc(Field f) { fieldType = field.getType(); enumFieldType = translateToEnumType(fieldType); - if (logger.isLoggable(Logger.FINEST)) { - Object[] items= new Object[] {fieldName,fieldType}; - logger.finest("sqlstore.model.fielddesc.setupdesc",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.fielddesc.setupdesc", fieldName,fieldType); } - private static int translateToEnumType(Class fldType) { + private static int translateToEnumType(Class fldType) { int retVal = FieldTypeEnumeration.NOT_ENUMERATED; - if(fldType == Boolean.TYPE ) retVal = FieldTypeEnumeration.BOOLEAN_PRIMITIVE; - else if(fldType == Character.TYPE ) retVal = FieldTypeEnumeration.CHARACTER_PRIMITIVE; - else if(fldType == Byte.TYPE ) retVal = FieldTypeEnumeration.BYTE_PRIMITIVE; - else if(fldType == Short.TYPE ) retVal = FieldTypeEnumeration.SHORT_PRIMITIVE; - else if(fldType == Integer.TYPE ) retVal = FieldTypeEnumeration.INTEGER_PRIMITIVE; - else if(fldType == Long.TYPE ) retVal = FieldTypeEnumeration.LONG_PRIMITIVE ; - else if(fldType == Float.TYPE ) retVal = FieldTypeEnumeration.FLOAT_PRIMITIVE; - else if(fldType == Double.TYPE ) retVal = FieldTypeEnumeration.DOUBLE_PRIMITIVE; - else if(fldType == Boolean.class ) retVal = FieldTypeEnumeration.BOOLEAN; - else if(fldType == Character.class ) retVal = FieldTypeEnumeration.CHARACTER; - else if(fldType == Byte.class ) retVal = FieldTypeEnumeration.BYTE; - else if(fldType == Short.class ) retVal = FieldTypeEnumeration.SHORT; - else if(fldType == Integer.class ) retVal = FieldTypeEnumeration.INTEGER; - else if(fldType == Long.class ) retVal = FieldTypeEnumeration.LONG; - else if(fldType == Float.class ) retVal = FieldTypeEnumeration.FLOAT; - else if(fldType == Double.class ) retVal = FieldTypeEnumeration.DOUBLE; - else if(fldType == java.math.BigDecimal.class) retVal = FieldTypeEnumeration.BIGDECIMAL; - else if(fldType == java.math.BigInteger.class) retVal = FieldTypeEnumeration.BIGINTEGER; - else if(fldType == String.class ) retVal = FieldTypeEnumeration.STRING; - else if(fldType == java.util.Date.class ) retVal = FieldTypeEnumeration.UTIL_DATE; - else if(fldType == java.sql.Date.class ) retVal = FieldTypeEnumeration.SQL_DATE; - else if(fldType == java.sql.Time.class ) retVal = FieldTypeEnumeration.SQL_TIME; - else if(fldType == java.sql.Timestamp.class ) retVal = FieldTypeEnumeration.SQL_TIMESTAMP; - else if(fldType.isArray()) { + if(fldType == Boolean.TYPE ) { + retVal = FieldTypeEnumeration.BOOLEAN_PRIMITIVE; + } else if(fldType == Character.TYPE ) { + retVal = FieldTypeEnumeration.CHARACTER_PRIMITIVE; + } else if(fldType == Byte.TYPE ) { + retVal = FieldTypeEnumeration.BYTE_PRIMITIVE; + } else if(fldType == Short.TYPE ) { + retVal = FieldTypeEnumeration.SHORT_PRIMITIVE; + } else if(fldType == Integer.TYPE ) { + retVal = FieldTypeEnumeration.INTEGER_PRIMITIVE; + } else if(fldType == Long.TYPE ) { + retVal = FieldTypeEnumeration.LONG_PRIMITIVE ; + } else if(fldType == Float.TYPE ) { + retVal = FieldTypeEnumeration.FLOAT_PRIMITIVE; + } else if(fldType == Double.TYPE ) { + retVal = FieldTypeEnumeration.DOUBLE_PRIMITIVE; + } else if(fldType == Boolean.class ) { + retVal = FieldTypeEnumeration.BOOLEAN; + } else if(fldType == Character.class ) { + retVal = FieldTypeEnumeration.CHARACTER; + } else if(fldType == Byte.class ) { + retVal = FieldTypeEnumeration.BYTE; + } else if(fldType == Short.class ) { + retVal = FieldTypeEnumeration.SHORT; + } else if(fldType == Integer.class ) { + retVal = FieldTypeEnumeration.INTEGER; + } else if(fldType == Long.class ) { + retVal = FieldTypeEnumeration.LONG; + } else if(fldType == Float.class ) { + retVal = FieldTypeEnumeration.FLOAT; + } else if(fldType == Double.class ) { + retVal = FieldTypeEnumeration.DOUBLE; + } else if(fldType == java.math.BigDecimal.class) { + retVal = FieldTypeEnumeration.BIGDECIMAL; + } else if(fldType == java.math.BigInteger.class) { + retVal = FieldTypeEnumeration.BIGINTEGER; + } else if(fldType == String.class ) { + retVal = FieldTypeEnumeration.STRING; + } else if(fldType == java.util.Date.class ) { + retVal = FieldTypeEnumeration.UTIL_DATE; + } else if(fldType == java.sql.Date.class ) { + retVal = FieldTypeEnumeration.SQL_DATE; + } else if(fldType == java.sql.Time.class ) { + retVal = FieldTypeEnumeration.SQL_TIME; + } else if(fldType == java.sql.Timestamp.class ) { + retVal = FieldTypeEnumeration.SQL_TIMESTAMP; + } else if(fldType.isArray()) { if(fldType.getComponentType() == Byte.TYPE) { retVal = FieldTypeEnumeration.ARRAY_BYTE_PRIMITIVE; } @@ -687,19 +729,17 @@ else if(fldType.isArray()) { return retVal; } - void setComponentType(Class type) { + void setComponentType(Class type) { this.componentType = type; } protected void addTrackedField(FieldDesc f) { - if (trackedFields == null) - trackedFields = new ArrayList(); - - if (logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {f.getName(),getName()}; - logger.finest("sqlstore.model.fielddesc.addingfield",items); // NOI18N + if (trackedFields == null) { + trackedFields = new ArrayList<>(); } + LOG.log(TRACE, "sqlstore.model.fielddesc.addingfield", f.getName(), getName()); + trackedFields.add(f); } @@ -713,10 +753,10 @@ protected void addTrackedField(FieldDesc f) { * @return true if there is a match, false, otherwise. */ static boolean compareColumns(FieldDesc f1, FieldDesc f2) { - ArrayList columnList1 = null; - ArrayList columnList2 = null; - ArrayList columnList3 = null; - ArrayList columnList4 = null; + List columnList1 = null; + List columnList2 = null; + List columnList3 = null; + List columnList4 = null; boolean exactMatch = false; // For LocalFieldDesc, we use columnDescs for comparison. @@ -739,26 +779,25 @@ static boolean compareColumns(FieldDesc f1, FieldDesc f2) { } else { if (f2 instanceof LocalFieldDesc) { return false; + } + ForeignFieldDesc ff1 = (ForeignFieldDesc) f1; + ForeignFieldDesc ff2 = (ForeignFieldDesc) f2; + + if (ff1.useJoinTable() && ff2.useJoinTable()) { + columnList1 = ff1.assocLocalColumns; + columnList2 = ff2.assocLocalColumns; + columnList3 = ff1.assocForeignColumns; + columnList4 = ff2.assocForeignColumns; + } else if (!ff1.useJoinTable() && !ff2.useJoinTable()) { + columnList1 = ff1.localColumns; + columnList2 = ff2.localColumns; + columnList3 = ff1.foreignColumns; + columnList4 = ff2.foreignColumns; } else { - ForeignFieldDesc ff1 = (ForeignFieldDesc) f1; - ForeignFieldDesc ff2 = (ForeignFieldDesc) f2; - - if (ff1.useJoinTable() && ff2.useJoinTable()) { - columnList1 = ff1.assocLocalColumns; - columnList2 = ff2.assocLocalColumns; - columnList3 = ff1.assocForeignColumns; - columnList4 = ff2.assocForeignColumns; - } else if (!ff1.useJoinTable() && !ff2.useJoinTable()) { - columnList1 = ff1.localColumns; - columnList2 = ff2.localColumns; - columnList3 = ff1.foreignColumns; - columnList4 = ff2.foreignColumns; - } else { - return false; - } - - exactMatch = true; + return false; } + + exactMatch = true; } boolean found = false; @@ -783,11 +822,11 @@ static boolean compareColumns(FieldDesc f1, FieldDesc f2) { for (int i = 0; i < size1; i++) { found = false; - ColumnElement c1 = (ColumnElement) columnList1.get(i); + ColumnElement c1 = columnList1.get(i); // Find if any column of columnList2 matches with c1. for (int j = 0; j < size2; j++) { - ColumnElement c2 = (ColumnElement) columnList2.get(j); + ColumnElement c2 = columnList2.get(j); if (c1.getName().getFullName().equals(c2.getName().getFullName())) { found = true; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ForeignFieldDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ForeignFieldDesc.java index cb77f0867f5..c5c49aff949 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ForeignFieldDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/ForeignFieldDesc.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,27 +15,25 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * ForeignFieldDesc.java - * - * Created on March 3, 2000 - * - */ package com.sun.jdo.spi.persistence.support.sqlstore.model; import com.sun.jdo.api.persistence.model.jdo.RelationshipElement; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.lang.reflect.Field; import java.util.ArrayList; +import java.util.List; import org.glassfish.persistence.common.I18NHelper; import org.netbeans.modules.dbschema.ColumnElement; import org.netbeans.modules.dbschema.TableElement; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** * */ @@ -62,6 +61,8 @@ public class ForeignFieldDesc extends FieldDesc { /** Currently runtime code does not interprete this action. */ public static final int ACT_AGGREGATE = RelationshipElement.AGGREGATE_ACTION; + private static final Logger LOG = System.getLogger(ForeignFieldDesc.class.getName(), RESOURCE_BUNDLE); + /** Class descriptor for the class of this relationship field. */ public ClassDesc foreignConfig; @@ -73,28 +74,28 @@ public class ForeignFieldDesc extends FieldDesc { public int deleteAction; /** Array of LocalFieldDesc. */ - public ArrayList foreignFields; + public ArrayList foreignFields; /** Array of ColumnElement. */ - public ArrayList foreignColumns; + public List foreignColumns; /** Array of LocalFieldDesc. */ - public ArrayList localFields; + public ArrayList localFields; /** Array of ColumnElement. */ - public ArrayList localColumns; + public List localColumns; /** Array of LocalFieldDesc. */ - public ArrayList assocForeignFields; + public List assocForeignFields; /** Array of ColumnElement. */ - public ArrayList assocForeignColumns; + public List assocForeignColumns; /** Array of LocalFieldDesc. */ - public ArrayList assocLocalFields; + public List assocLocalFields; /** Array of ColumnElement. */ - public ArrayList assocLocalColumns; + public List assocLocalColumns; /** * If inverseRelationshipField is not null, it means this field is @@ -115,6 +116,7 @@ public class ForeignFieldDesc extends FieldDesc { /** * Returns true. */ + @Override public boolean isRelationshipField() { return true; } @@ -159,37 +161,37 @@ public boolean isMappedToPk() { return isMappedToPk; } - public ArrayList getLocalFields() { + public ArrayList getLocalFields() { if (localFields == null) { - localFields = new ArrayList(); + localFields = new ArrayList<>(); } return localFields; } - public ArrayList getForeignFields() { + public ArrayList getForeignFields() { if (foreignFields == null) { - foreignFields = new ArrayList(); + foreignFields = new ArrayList<>(); } return foreignFields; } - public ArrayList getAssocLocalFields() { + public List getAssocLocalFields() { // Only create assocLocalFields if there is a corresponding // assocLocalColumns to save space. if (assocLocalFields == null && assocLocalColumns != null) { - assocLocalFields = new ArrayList(); + assocLocalFields = new ArrayList<>(); } return assocLocalFields; } - public ArrayList getAssocForeignFields() { + public List getAssocForeignFields() { // Only create assocForeignFields if there is a corresponding // assocForeignColumns to save space. if (assocForeignFields == null && assocForeignColumns != null) { - assocForeignFields = new ArrayList(); + assocForeignFields = new ArrayList<>(); } return assocForeignFields; @@ -226,14 +228,14 @@ public Object createObjectId(SQLStateManager sm, LocalFieldDesc fieldDesc, Objec assert isMappedToPk(); - Class oidClass = foreignConfig.getOidClass(); + Class oidClass = foreignConfig.getOidClass(); Object oid = null; try { - oid = oidClass.newInstance(); + oid = oidClass.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantnewoid", oidClass.getName()), e); // NOI18N + "core.statemanager.cantnewoid", oidClass.getName()), e); } Field keyFields[] = foreignConfig.getKeyFields(); @@ -242,10 +244,10 @@ public Object createObjectId(SQLStateManager sm, LocalFieldDesc fieldDesc, Objec Field keyField = keyFields[i]; for (int j = 0; j < foreignFields.size() && oid != null; j++) { - LocalFieldDesc fa = (LocalFieldDesc) foreignFields.get(j); + LocalFieldDesc fa = foreignFields.get(j); if (fa.getName().compareTo(keyFieldNames[i]) == 0) { - LocalFieldDesc la = (LocalFieldDesc) localFields.get(j); + LocalFieldDesc la = localFields.get(j); Object keyFieldValue = null; if (la == fieldDesc) { @@ -263,7 +265,7 @@ public Object createObjectId(SQLStateManager sm, LocalFieldDesc fieldDesc, Objec keyField.set(oid, fa.convertValue(keyFieldValue, sm)); } catch (IllegalAccessException e) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.statemanager.cantsetkeyfield", keyField.getName()), e); // NOI18N + "core.statemanager.cantsetkeyfield", keyField.getName()), e); } } else { oid = null; @@ -284,6 +286,7 @@ private void setInverseRelationshipField(ForeignFieldDesc f) { inverseRelationshipField = f; } + @Override void computeTrackedRelationshipFields() { // If the field is a ForeignFieldDesc, we only need // to compare against other ForeignFieldDesc. The reason @@ -293,7 +296,7 @@ void computeTrackedRelationshipFields() { ForeignFieldDesc inverseField = getInverseRelationshipField(); for (int k = 0; k < classDesc.foreignFields.size(); k++) { - ForeignFieldDesc tf = (ForeignFieldDesc) classDesc.foreignFields.get(k); + ForeignFieldDesc tf = classDesc.foreignFields.get(k); if ((this != tf) && (getType() == tf.getType()) && (compareColumns(this, tf) == true)) { if ((inverseField != null) && @@ -336,20 +339,19 @@ void fixupForeignReference(ClassDesc foreignConfig, * @param foreignConfig Class descriptor of the foreign class. * @param inverseField The inverse relationship field. */ - private void registerForeignConfig(ClassDesc foreignConfig, - ForeignFieldDesc inverseField) { - boolean debug = logger.isLoggable(Logger.FINEST); + private void registerForeignConfig(ClassDesc foreignConfig, ForeignFieldDesc inverseField) { + boolean debug = LOG.isLoggable(TRACE); if (debug) { Object[] items = new Object[] {classDesc, this, foreignConfig}; - logger.finest("sqlstore.model.classdesc.general", items); // NOI18N + LOG.log(TRACE, "sqlstore.model.classdesc.general", items); } // Remember the class descriptor for the foreign class. this.foreignConfig = foreignConfig; if (debug && inverseField != null) { - logger.finest("sqlstore.model.classdesc.assocrelatedfield", inverseField); //NOI18N + LOG.log(TRACE, "sqlstore.model.classdesc.assocrelatedfield", inverseField); //NOI18N } setInverseRelationshipField(inverseField); @@ -362,8 +364,8 @@ private void initializeFieldLists() { ClassDesc theConfig = classDesc; for (int i = 0; i < 4; i++) { - ArrayList fields = null; - ArrayList columns = null; + List fields = null; + List columns = null; switch (i) { case 0: @@ -385,15 +387,17 @@ private void initializeFieldLists() { break; } - if (columns == null) continue; + if (columns == null) { + continue; + } for (int j = 0; j < columns.size(); j++) { - ColumnElement ce = (ColumnElement) columns.get(j); + ColumnElement ce = columns.get(j); TableElement te = ce.getDeclaringTable(); if (te == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.columnnotable")); // NOI18N + "core.configuration.columnnotable")); } fields.add(theConfig.getLocalFieldDesc(ce)); @@ -413,7 +417,7 @@ private void initializeIsMappedToPk() { foreignConfig.getKeyFields().length == count; for (int i = 0; i < count && isMappedToPk; i++) { - isMappedToPk = ((LocalFieldDesc) foreignFields.get(i)).isKeyField(); + isMappedToPk = foreignFields.get(i).isKeyField(); } } @@ -422,7 +426,7 @@ private void initializeIsMappedToPk() { */ private void addForeignKeyFieldsToDFG() { for (int i = 0; i < localFields.size(); i++) { - LocalFieldDesc lf = (LocalFieldDesc) localFields.get(i); + LocalFieldDesc lf = localFields.get(i); if (lf.absoluteID < 0 && !useJoinTable()) { classDesc.getFetchGroup(GROUP_DEFAULT).add(lf); @@ -461,7 +465,7 @@ void fixupFieldProperties() { // This side will write relationship updates to the database. // Mark the local fields as part of the foreign key. for (int i = 0; i < localFields.size(); i++) { - ((LocalFieldDesc)localFields.get(i)).sqlProperties |= FieldDesc.PROP_FOREIGN_KEY_FIELD; + localFields.get(i).sqlProperties |= FieldDesc.PROP_FOREIGN_KEY_FIELD; } } } @@ -708,13 +712,13 @@ private boolean checkDependentSide(ForeignFieldDesc inverseFieldDesc) { * referred in relationships must not be updated. Not updatable fields * have property REF_INTEGRITY_UPDATES unset. * - * @param fieldList Fields corresponding to datastore columns. + * @param list Fields corresponding to datastore columns. * The fields are either a ForeignFieldDesc's local or foreign fields. * @return True, if fieldList is a foreign key, false otherwise. */ - private static boolean checkForeignKey(ArrayList fieldList) { - for (int i = 0; i < fieldList.size(); i++) { - FieldDesc lf = (FieldDesc) fieldList.get(i); + private static boolean checkForeignKey(List list) { + for (int i = 0; i < list.size(); i++) { + FieldDesc lf = list.get(i); if ((lf.sqlProperties & FieldDesc.PROP_REF_INTEGRITY_UPDATES) > 0) { // Based on the assumption, that referred key fields @@ -770,9 +774,7 @@ private boolean chooseUpdatedSide(ForeignFieldDesc inverseFieldDesc) { * Datastore updates will be scheduled on the opposite relationship side. */ private void unsetReferentialIntegrityUpdateProperty() { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest("sqlstore.model.classdesc.unsetrefintegrityupdate", getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.unsetrefintegrityupdate", getName()); sqlProperties &= ~(FieldDesc.PROP_REF_INTEGRITY_UPDATES); } @@ -783,19 +785,17 @@ private void unsetReferentialIntegrityUpdateProperty() { */ private void unsetConcurrencyCheckProperty() { // Copy the field list temporarily. - ArrayList fieldList = (ArrayList) getLocalFields().clone(); + ArrayList fieldList = (ArrayList) getLocalFields().clone(); if (useJoinTable()) { fieldList.addAll(getAssocLocalFields()); } for (int j = 0; j < fieldList.size(); j++) { - FieldDesc lf = (FieldDesc) fieldList.get(j); + FieldDesc lf = fieldList.get(j); if (lf.absoluteID < 0) { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest("sqlstore.model.classdesc.unsetconcurrencychk", lf.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.unsetconcurrencychk", lf.getName()); lf.sqlProperties &= ~(FieldDesc.PROP_IN_CONCURRENCY_CHECK); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/KeyDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/KeyDesc.java index b06c19f74e1..b68c60bd366 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/KeyDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/KeyDesc.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,16 +15,10 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * KeyDesc.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.model; import java.util.ArrayList; +import java.util.List; import org.netbeans.modules.dbschema.ColumnElement; @@ -34,22 +29,23 @@ public class KeyDesc { /** Array of LocalFieldDesc */ - private ArrayList fields; + private List fields; /** Array of ColumnElements */ - private ArrayList columns; + private List columns; /** Initialize the columns ArrayList. */ - void addColumns(ArrayList columns) { - this.columns = columns; + void addColumns(List keys) { + this.columns = keys; } /** Add a field to the KeyDesc. * @param f - FieldDesc to be added */ void addField(FieldDesc f) { - if (fields == null) - fields = new ArrayList(); + if (fields == null) { + fields = new ArrayList<>(); + } fields.add(f); } @@ -58,8 +54,9 @@ void addField(FieldDesc f) { * @param c - ColumnElement to be added */ void addColumn(ColumnElement c) { - if (columns == null) - columns = new ArrayList(); + if (columns == null) { + columns = new ArrayList<>(); + } columns.add(c); } @@ -67,18 +64,14 @@ void addColumn(ColumnElement c) { /** Return all key columns. * @return an ArrayList of ColumnElements */ - public ArrayList getColumns() { + public List getColumns() { return columns; } /** Return all key fields. * @return an ArrayList of FieldDescs */ - public ArrayList getFields() { + public List getFields() { return fields; } } - - - - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/LocalFieldDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/LocalFieldDesc.java index c993da228e4..ce871257334 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/LocalFieldDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/LocalFieldDesc.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,36 +15,33 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * LocalFieldDesc.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.model; import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Types; -import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import org.netbeans.modules.dbschema.ColumnElement; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** * */ public class LocalFieldDesc extends FieldDesc { + private static final Logger LOG = System.getLogger(LocalFieldDesc.class.getName(), RESOURCE_BUNDLE); /** Array of ColumnElement. */ - final ArrayList columnDescs; + final List columnDescs; /** Stores this special mapping information. */ private Boolean primitiveMappedToNullableColumn; @@ -51,9 +49,9 @@ public class LocalFieldDesc extends FieldDesc { /** SQL Column type for primary column. */ private final int primaryColumnType; - LocalFieldDesc(ClassDesc config, ArrayList columnDescs) { + LocalFieldDesc(ClassDesc config, List columnDesc) { super(config); - this.columnDescs = columnDescs; + this.columnDescs = columnDesc; //Initialize primary column's type. primaryColumnType = getPrimaryColumn().getType(); @@ -65,11 +63,11 @@ public boolean isPrimitiveMappedToNullableColumn() { if (primitiveMappedToNullableColumn == null) { boolean rc = getType().isPrimitive(); - for (Iterator iter = columnDescs.iterator(); iter.hasNext() && rc; ) { - ColumnElement c = (ColumnElement) iter.next(); + for (Iterator iter = columnDescs.iterator(); iter.hasNext() && rc; ) { + ColumnElement c = iter.next(); rc = c.isNullable(); } - primitiveMappedToNullableColumn = new Boolean(rc); + primitiveMappedToNullableColumn = Boolean.valueOf(rc); } return primitiveMappedToNullableColumn.booleanValue(); @@ -125,14 +123,14 @@ public static boolean isFixedCharType(int sqlType) { * @return The ColumnElement for the primary column of this field. */ public ColumnElement getPrimaryColumn() { - return ((ColumnElement) columnDescs.get(0)); + return (columnDescs.get(0)); } /** * Returns an iterator on the mapped column elements. * @return An iterator on the mapped column elements. */ - public Iterator getColumnElements() { + public Iterator getColumnElements() { return columnDescs.iterator(); } @@ -166,6 +164,7 @@ public void incrementValue(StateManager sm) { * Calls the superclass method and disables concurrency checking * for certain field types. */ + @Override protected void setupDesc(Field f) { super.setupDesc(f); @@ -191,7 +190,7 @@ protected void setupDesc(Field f) { * The primitive type long has the highest precedence and the type * Float has the lowest. */ - private static final Class[] nonNullableNonScaledTypes = + private static final Class[] nonNullableNonScaledTypes = { Long.TYPE, Integer.TYPE, Short.TYPE, Byte.TYPE, Double.TYPE, Float.TYPE, BigInteger.class, BigDecimal.class, Long.class, @@ -204,7 +203,7 @@ protected void setupDesc(Field f) { * The type BigDecimal has the highest precedence and the primitive * type float has the lowest. */ - private static final Class[] nullableNonScaledTypes = + private static final Class[] nullableNonScaledTypes = { BigInteger.class, BigDecimal.class, Long.class, Integer.class, Short.class, Byte.class, Double.class, Float.class, Long.TYPE, Integer.TYPE, @@ -217,7 +216,7 @@ protected void setupDesc(Field f) { * The primitive type double has the highest precedence and the primitive * type byte has the lowest. */ - private static final Class[] nonNullableScaledTypes = + private static final Class[] nonNullableScaledTypes = { Double.TYPE, Float.TYPE, Long.TYPE, Integer.TYPE, Short.TYPE, Byte.TYPE, BigDecimal.class, Double.class, BigInteger.class, @@ -230,7 +229,7 @@ protected void setupDesc(Field f) { * The primitive type BigDecimal has the highest precedence and the primitive * type float has the lowest. */ - private static final Class[] nullableScaledTypes = + private static final Class[] nullableScaledTypes = { BigDecimal.class, Double.class, Float.class, BigInteger.class, Long.class, Integer.class, Short.class, Byte.class, Double.TYPE, @@ -247,7 +246,7 @@ protected void setupDesc(Field f) { * @see #nullableScaledTypes * @return an integer value indicating the precedence */ - private static int lookupTypePrecedence(Class type, Class typePrecedence[]) { + private static int lookupTypePrecedence(Class type, Class typePrecedence[]) { for (int i = 0; i < typePrecedence.length; i++) { if (type == typePrecedence[i]) { return i; @@ -263,9 +262,9 @@ private static int lookupTypePrecedence(Class type, Class typePrecedence[]) { * highest precedence and Integer.MAX_VALUE indicates lowest. */ private int computeTypePrecedence() { - ColumnElement c = (ColumnElement) columnDescs.get(0); + ColumnElement c = columnDescs.get(0); int sqlType = c.getType(); - Class type = getType(); + Class type = getType(); boolean isNullable = c.isNullable(); int precedence = Integer.MAX_VALUE; @@ -343,7 +342,7 @@ private int computeTypePrecedence() { void computeTrackedPrimitiveFields() { for (int i = 0; i < classDesc.fields.size(); i++) { - FieldDesc tf = (FieldDesc) classDesc.fields.get(i); + FieldDesc tf = classDesc.fields.get(i); if ((tf instanceof LocalFieldDesc) && (this != tf) && (compareColumns(this, tf) == true)) { addTrackedField(tf); @@ -355,13 +354,14 @@ void computeTrackedPrimitiveFields() { * Compute the primary tracked field. */ void computePrimaryTrackedPrimitiveField() { - ArrayList trackedFields = null; + List trackedFields = getTrackedFields(); // We need to skip fields that are read-only. - if (((trackedFields = getTrackedFields()) == null) || - (sqlProperties & (FieldDesc.PROP_PRIMARY_TRACKED_FIELD | - FieldDesc.PROP_SECONDARY_TRACKED_FIELD | - FieldDesc.PROP_READ_ONLY)) > 0) { + if (trackedFields == null || + (sqlProperties + & (FieldDesc.PROP_PRIMARY_TRACKED_FIELD + | FieldDesc.PROP_SECONDARY_TRACKED_FIELD + | FieldDesc.PROP_READ_ONLY)) > 0) { return; } @@ -379,7 +379,7 @@ void computePrimaryTrackedPrimitiveField() { } for (int j = 0; j < trackedFields.size(); j++) { - FieldDesc tf = (FieldDesc) trackedFields.get(j); + FieldDesc tf = trackedFields.get(j); // We don't need to assign primary or secondary status for ForeignFieldDesc // because we don't write it to the disk. @@ -403,14 +403,13 @@ void computePrimaryTrackedPrimitiveField() { primaryTrackedField = this; } - if (logger.isLoggable(Logger.FINEST)) { - logger.finest("sqlstore.model.classdesc.primarytrackedfield", primaryTrackedField.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.model.classdesc.primarytrackedfield", primaryTrackedField.getName()); primaryTrackedField.sqlProperties |= FieldDesc.PROP_PRIMARY_TRACKED_FIELD; primaryTrackedField.sqlProperties &= ~FieldDesc.PROP_SECONDARY_TRACKED_FIELD; } + @Override void computeTrackedRelationshipFields() { if (((sqlProperties & FieldDesc.PROP_REF_INTEGRITY_UPDATES) == 0) && @@ -419,7 +418,7 @@ void computeTrackedRelationshipFields() { } for (int k = 0; k < classDesc.foreignFields.size(); k++) { - ForeignFieldDesc tf = (ForeignFieldDesc) classDesc.foreignFields.get(k); + ForeignFieldDesc tf = classDesc.foreignFields.get(k); if (compareColumns(this, tf) == true) { // In the case where the relationship has cardinality LWB and UPB @@ -447,29 +446,25 @@ void computeTrackedRelationshipFields() { } void cleanupTrackedFields() { - ArrayList trackedFields = getTrackedFields(); - - if (trackedFields != null) { - for (int j = 1; ; j++) { - int index = trackedFields.size() - j; - - if (index < 0) { - break; - } - - FieldDesc tf = (FieldDesc) trackedFields.get(index); - - if (tf instanceof LocalFieldDesc) { - break; - } + List trackedFields = getTrackedFields(); + if (trackedFields == null) { + return; + } + for (int j = 1; ; j++) { + int index = trackedFields.size() - j; + if (index < 0) { + break; + } - ArrayList foreignTrackedFields = tf.getTrackedFields(); + FieldDesc tf = trackedFields.get(index); + if (tf instanceof LocalFieldDesc) { + break; + } - if (foreignTrackedFields != null) { - trackedFields.removeAll(foreignTrackedFields); - } + List foreignTrackedFields = tf.getTrackedFields(); + if (foreignTrackedFields != null) { + trackedFields.removeAll(foreignTrackedFields); } } } - } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/TableDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/TableDesc.java index 5968b1b1cc0..431257004b0 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/TableDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/model/TableDesc.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,18 +15,12 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * TableDesc.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.model; import com.sun.jdo.api.persistence.model.mapping.MappingClassElement; import java.util.ArrayList; +import java.util.List; import org.netbeans.modules.dbschema.TableElement; @@ -38,7 +33,7 @@ public class TableDesc { private KeyDesc key; /** array of ReferenceKeyDescs referencing secondary tables */ - private ArrayList secondaryTableKeys; + private List secondaryTableKeys; /** ReferenceKeyDesc referencing the primary table */ private ReferenceKeyDesc primaryTableKey; @@ -68,7 +63,7 @@ public TableDesc(TableElement tableElement) { /** Return all secondary table keys. * @return an ArrayList of ReferenceKeyDescs for secondary tables */ - public ArrayList getSecondaryTableKeys() { + public List getSecondaryTableKeys() { return secondaryTableKeys; } @@ -76,8 +71,9 @@ public ArrayList getSecondaryTableKeys() { * @param key - ReferenceKeyDesc to be added */ void addSecondaryTableKey(ReferenceKeyDesc key) { - if (secondaryTableKeys == null) - secondaryTableKeys = new ArrayList(); + if (secondaryTableKeys == null) { + secondaryTableKeys = new ArrayList<>(); + } secondaryTableKeys.add(key); } @@ -166,8 +162,3 @@ public LocalFieldDesc getVersionField() { } } - - - - - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/LogHelperQueryExecute.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/LogHelperQueryExecute.java deleted file mode 100644 index b6551d5cbc0..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/LogHelperQueryExecute.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.spi.persistence.support.sqlstore.query; - -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -/** - * - * @author Michael Bouschen - */ -public class LogHelperQueryExecute { - - /** The component name for this component - */ - protected static final String componentName = "query.execute"; // NOI18N - - /** The class loader for this component - */ - protected static final ClassLoader loader = - LogHelperQueryExecute.class.getClassLoader(); - - /** The bundle name for this component - */ - protected static final String bundleName = - "com.sun.jdo.spi.persistence.support.sqlstore.query.Bundle"; // NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - -} diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/QueryImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/QueryImpl.java index 40ece48b3e0..50a2184665a 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/QueryImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/QueryImpl.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 @@ -22,7 +23,6 @@ package com.sun.jdo.spi.persistence.support.sqlstore.query; -import com.sun.jdo.api.persistence.support.JDOException; import com.sun.jdo.api.persistence.support.JDOQueryException; import com.sun.jdo.api.persistence.support.Query; import com.sun.jdo.api.persistence.support.Transaction; @@ -30,8 +30,10 @@ import com.sun.jdo.spi.persistence.support.sqlstore.RetrieveDesc; import com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.JQLC; import com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.ParameterTable; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.lang.System.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @@ -39,18 +41,18 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.DEBUG; + /** * * @author Michael Bouschen - * @version 0.1 */ -public class QueryImpl - implements Query -{ +public class QueryImpl implements Query { + /** * */ - private Class candidateClass; + private Class candidateClass; /** * @@ -95,7 +97,7 @@ public class QueryImpl /** * */ - private transient Collection candidateCollection; + private transient Collection candidateCollection; /** * @@ -125,19 +127,16 @@ public class QueryImpl /** * I18N support */ - protected final static ResourceBundle messages = - I18NHelper.loadBundle(QueryImpl.class); + protected final static ResourceBundle messages = I18NHelper.loadBundle(QueryImpl.class); /** The logger */ - private static Logger logger = LogHelperQueryExecute.getLogger(); + private static final Logger LOG = System.getLogger(QueryImpl.class.getName(), messages); /** * Create an empty query instance with no elements. */ - public QueryImpl(PersistenceManager pm) - { - if (logger.isLoggable(Logger.FINER)) - logger.finer("LOG_CreateNewQuery", identity()); //NOI18N + public QueryImpl(PersistenceManager pm) { + LOG.log(DEBUG, "LOG_CreateNewQuery", identity()); this.pm = pm; this.paramtab = new ParameterTable(); this.ignoreCache = pm.getPersistenceManagerFactory().getIgnoreCache(); @@ -149,29 +148,21 @@ public QueryImpl(PersistenceManager pm) * in a different PersistenceManager or might have been serialized and restored. * @param compiled another Query from the same JDO implementation */ - public QueryImpl (PersistenceManager pm, Object compiled) - { - if (logger.isLoggable(Logger.FINER)) - logger.finer("LOG_CreateNewQueryFromCompiled", identity(), compiled); //NOI18N - this.pm = pm; - if (compiled == null) + public QueryImpl(PersistenceManager pm, Object compiled) { { - JDOException ex = new JDOQueryException(I18NHelper.getMessage( - messages, "query.queryimpl.init.compiledquery.isnull")); //NOI18N - logger.throwing("query.QueryImpl", "", ex); //NOI18N - throw ex; + LOG.log(DEBUG, "LOG_CreateNewQueryFromCompiled", identity(), compiled); + } + this.pm = pm; + if (compiled == null) { + throw new JDOQueryException(I18NHelper.getMessage(messages, "query.queryimpl.init.compiledquery.isnull")); } - if (!(compiled instanceof QueryImpl)) - { - JDOException ex = new JDOQueryException(I18NHelper.getMessage( - messages, "query.queryimpl.init.compiledquery.invalidtype", //NOI18N - compiled.getClass().getName())); - logger.throwing("query.QueryImpl", "", ex); //NOI18N - throw ex; + if (!(compiled instanceof QueryImpl)) { + throw new JDOQueryException(I18NHelper.getMessage(messages, + "query.queryimpl.init.compiledquery.invalidtype", compiled.getClass().getName())); } - QueryImpl other = (QueryImpl)compiled; + QueryImpl other = (QueryImpl) compiled; this.candidateClass = other.candidateClass; this.filterExpression = other.filterExpression; this.importDeclarations = other.importDeclarations; @@ -184,14 +175,11 @@ public QueryImpl (PersistenceManager pm, Object compiled) this.candidateCollection = null; // initialize paramtab, jqlc and compiled - if (other.paramtab != null) - { + if (other.paramtab != null) { this.jqlc = other.jqlc; this.paramtab = new ParameterTable(other.paramtab); this.compiled = other.compiled; - } - else - { + } else { // other.paramtab == null means deserialized query => // - parameter table // - set compiled = false @@ -205,8 +193,7 @@ public QueryImpl (PersistenceManager pm, Object compiled) * Create a query instance with the candidate class specified. * @param candidateClass the Class of the candidate instances. */ - public QueryImpl(PersistenceManager pm, Class candidateClass) - { + public QueryImpl(PersistenceManager pm, Class candidateClass) { this(pm); setClass(candidateClass); } @@ -217,8 +204,7 @@ public QueryImpl(PersistenceManager pm, Class candidateClass) * @param candidateClass the Class of the candidate instances. * @param candidateCollection the Collection of candidate instances. */ - public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candidateCollection) - { + public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candidateCollection) { this(pm); setClass(candidateClass); setCandidates(candidateCollection); @@ -230,22 +216,22 @@ public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candida * @param candidateClass the Class of the candidate instances. * @param filter the Filter for candidate instances. */ - public QueryImpl(PersistenceManager pm, Class candidateClass, String filter) - { + public QueryImpl(PersistenceManager pm, Class candidateClass, String filter) { this(pm); setClass(candidateClass); setFilter(filter); } + /** * Create a query instance with the candidate class, * the candidate collection, and filter specified. + * * @param candidateClass the Class of the candidate instances. * @param candidateCollection the Collection of candidate instances. * @param filter the Filter for candidate instances */ - public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candidateCollection, String filter) - { + public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candidateCollection, String filter) { this(pm); setClass(candidateClass); setCandidates(candidateCollection); @@ -260,10 +246,9 @@ public QueryImpl(PersistenceManager pm, Class candidateClass, Collection candida * * @param candidateClass the Class of the candidate instances. */ - public void setClass(Class candidateClass) - { - synchronized (this.paramtab) - { + @Override + public void setClass(Class candidateClass) { + synchronized (this.paramtab) { this.candidateClass = candidateClass; this.compiled = false; } @@ -274,10 +259,9 @@ public void setClass(Class candidateClass) * * @param candidateCollection the Candidate collection. */ - public void setCandidates(Collection candidateCollection) - { - synchronized (this.paramtab) - { + @Override + public void setCandidates(Collection candidateCollection) { + synchronized (this.paramtab) { this.candidateCollection = candidateCollection; // candidateCollection is not part of query compilation => // do not change compiled flag @@ -292,10 +276,9 @@ public void setCandidates(Collection candidateCollection) * * @param filter the query filter. */ - public void setFilter(String filter) - { - synchronized (this.paramtab) - { + @Override + public void setFilter(String filter) { + synchronized (this.paramtab) { this.filterExpression = filter; this.compiled = false; } @@ -313,10 +296,9 @@ public void setFilter(String filter) * * @param imports import statements separated by semicolons. */ - public void declareImports(String imports) - { - synchronized (this.paramtab) - { + @Override + public void declareImports(String imports) { + synchronized (this.paramtab) { this.importDeclarations = imports; this.compiled = false; } @@ -335,10 +317,9 @@ public void declareImports(String imports) * * @param parameters the list of parameters separated by commas. */ - public void declareParameters(String parameters) - { - synchronized (this.paramtab) - { + @Override + public void declareParameters(String parameters) { + synchronized (this.paramtab) { this.parameterDeclarations = parameters; this.compiled = false; } @@ -356,10 +337,9 @@ public void declareParameters(String parameters) * * @param variables the variables separated by semicolons. */ - public void declareVariables(String variables) - { - synchronized (this.paramtab) - { + @Override + public void declareVariables(String variables) { + synchronized (this.paramtab) { this.variableDeclarations = variables; this.compiled = false; } @@ -371,10 +351,9 @@ public void declareVariables(String variables) * The ordering specification includes a list of expressions * with the ascending/descending indicator. */ - public void setOrdering(String ordering) - { - synchronized (this.paramtab) - { + @Override + public void setOrdering(String ordering) { + synchronized (this.paramtab) { this.orderingSpecification = ordering; this.compiled = false; } @@ -389,10 +368,9 @@ public void setOrdering(String ordering) * which has the effect of returning the elements of the candidates * that match the filter. */ - public void setResult(String result) - { - synchronized (this.paramtab) - { + @Override + public void setResult(String result) { + synchronized (this.paramtab) { this.resultExpression = result; this.compiled = false; } @@ -405,10 +383,9 @@ public void setResult(String result) * entirely in the back end, instead of in the cache. * @param ignoreCache the setting of the ignoreCache option. */ - public void setIgnoreCache(boolean ignoreCache) - { - synchronized (this.paramtab) - { + @Override + public void setIgnoreCache(boolean ignoreCache) { + synchronized (this.paramtab) { this.ignoreCache = ignoreCache; } } @@ -418,8 +395,8 @@ public void setIgnoreCache(boolean ignoreCache) * @return the ignoreCache option setting. * @see #setIgnoreCache */ - public boolean getIgnoreCache() - { + @Override + public boolean getIgnoreCache() { return ignoreCache; } @@ -433,10 +410,9 @@ public boolean getIgnoreCache() * * @param prefetchEnabled the setting of the prefetchEnabled option. */ - public void setPrefetchEnabled(boolean prefetchEnabled) - { - synchronized (this.paramtab) - { + @Override + public void setPrefetchEnabled(boolean prefetchEnabled) { + synchronized (this.paramtab) { this.prefetchEnabled = prefetchEnabled; this.compiled = false; } @@ -446,30 +422,28 @@ public void setPrefetchEnabled(boolean prefetchEnabled) * Verify the elements of the query and provide a hint to the query to * prepare and optimize an execution plan. */ - public void compile() - { - synchronized (this.paramtab) - { - if (!this.compiled) - { - if (logger.isLoggable(Logger.FINER)) - logger.finer("LOG_CompileQuery", this); //NOI18N - // create new query compiler instance - jqlc = new JQLC(); - // define the query parts including syntax checks - jqlc.setClass(candidateClass); - jqlc.declareImports(importDeclarations); - jqlc.declareParameters(parameterDeclarations); - jqlc.declareVariables(variableDeclarations); - jqlc.setOrdering(orderingSpecification); - jqlc.setResult(resultExpression); - jqlc.setFilter(filterExpression); - jqlc.setPrefetchEnabled(prefetchEnabled); - - // semantic analysis - jqlc.semanticCheck(paramtab); - this.compiled = true; + @Override + public void compile() { + synchronized (this.paramtab) { + if (this.compiled) { + return; } + LOG.log(DEBUG, "LOG_CompileQuery", this); + // create new query compiler instance + jqlc = new JQLC(); + // define the query parts including syntax checks + jqlc.setClass(candidateClass); + jqlc.declareImports(importDeclarations); + jqlc.declareParameters(parameterDeclarations); + jqlc.declareVariables(variableDeclarations); + jqlc.setOrdering(orderingSpecification); + jqlc.setResult(resultExpression); + jqlc.setFilter(filterExpression); + jqlc.setPrefetchEnabled(prefetchEnabled); + + // semantic analysis + jqlc.semanticCheck(paramtab); + this.compiled = true; } } @@ -478,10 +452,9 @@ public void compile() * @return the filtered Collection. * @see #executeWithArray (Object[] parameters) */ - public Object execute() - { - synchronized (this.paramtab) - { + @Override + public Object execute() { + synchronized (this.paramtab) { compile(); ParameterTable params = new ParameterTable(paramtab); params.initValueHandling(); @@ -496,9 +469,9 @@ public Object execute() * @see #executeWithArray (Object[] parameters) * @param p1 the value of the first parameter declared. */ - public Object execute(Object p1) - { - Object [] params = new Object[1]; + @Override + public Object execute(Object p1) { + Object[] params = new Object[1]; params[0] = p1; return executeWithArray(params); } @@ -510,9 +483,9 @@ public Object execute(Object p1) * @param p1 the value of the first parameter declared. * @param p2 the value of the second parameter declared. */ - public Object execute(Object p1, Object p2) - { - Object [] params = new Object[2]; + @Override + public Object execute(Object p1, Object p2) { + Object[] params = new Object[2]; params[0] = p1; params[1] = p2; return executeWithArray(params); @@ -526,9 +499,9 @@ public Object execute(Object p1, Object p2) * @param p2 the value of the second parameter declared. * @param p3 the value of the third parameter declared. */ - public Object execute(Object p1, Object p2, Object p3) - { - Object [] params = new Object[3]; + @Override + public Object execute(Object p1, Object p2, Object p3) { + Object[] params = new Object[3]; params[0] = p1; params[1] = p2; params[2] = p3; @@ -541,10 +514,9 @@ public Object execute(Object p1, Object p2, Object p3) * @see #executeWithArray (Object[] parameters) * @param parameters the Map containing all of the parameters. */ - public Object executeWithMap (Map parameters) - { - synchronized (this.paramtab) - { + @Override + public Object executeWithMap(Map parameters) { + synchronized (this.paramtab) { compile(); ParameterTable params = new ParameterTable(paramtab); params.initValueHandling(); @@ -574,10 +546,9 @@ public Object executeWithMap (Map parameters) * @return the filtered Collection. * @param parameters the Object array with all of the parameters. */ - public Object executeWithArray (Object[] parameters) - { - synchronized (this.paramtab) - { + @Override + public Object executeWithArray(Object[] parameters) { + synchronized (this.paramtab) { compile(); ParameterTable params = new ParameterTable(paramtab); params.initValueHandling(); @@ -594,8 +565,8 @@ public Object executeWithArray (Object[] parameters) *

    If this Query has no PersistenceManager return null. * @return the PersistenceManager associated with this Query. */ - public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceManager() - { + @Override + public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceManager() { return (pm == null)? null : pm.getCurrentWrapper(); } @@ -608,8 +579,7 @@ public com.sun.jdo.api.persistence.support.PersistenceManager getPersistenceMana * This method effectively disconnects the PersistenceManager allowing it to be * garbage collected. */ - public void clearPersistenceManager() - { + public void clearPersistenceManager() { this.pm = null; this.candidateCollection = null; } @@ -621,13 +591,11 @@ public void clearPersistenceManager() * - executes the RetrieveDesc returned by the code generation * - resets the compiler */ - private Object doExecute(ParameterTable params) - { + private Object doExecute(ParameterTable params) { Object result = null; RetrieveDesc rd = null; - try - { + try { // We need to make sure that no parallel thread closes the pm => // try to get a shared lock for the pm. Today, the pm impl does // not allow to promote a shared lock into a exclusive lock. Thus @@ -640,35 +608,28 @@ private Object doExecute(ParameterTable params) // pm and then get the lock, because the pm might be closed in // parallel. Then subsequent uses of pm in doexecute would fail. pm.acquireExclusiveLock(); - } - catch (NullPointerException npe) - { + } catch (NullPointerException npe) { // NPE means pm is closed or query instance was serialized. - String key = (createdBySerialization ? - "query.queryimpl.doexecute.notboundtopm" : //NOI18N - "query.queryimpl.doexecute.pmclosed"); //NOI18N - JDOException ex = new JDOQueryException( - I18NHelper.getMessage(messages, key)); - logger.throwing("query.QueryImpl", "compile", ex); //NOI18N - throw ex; + String key = (createdBySerialization + ? "query.queryimpl.doexecute.notboundtopm" + : "query.queryimpl.doexecute.pmclosed"); + throw new JDOQueryException(I18NHelper.getMessage(messages, key)); } - try - { + try { checkCandidates(); // call the code generation rd = jqlc.codeGen(pm, params); // flush changes (inserts, updates, deletes) to the datastore flush(); - if (logger.isLoggable(Logger.FINER)) - logger.finer("LOG_ExecuteQuery", this, params.getValues()); //NOI18N + { + LOG.log(DEBUG, "LOG_ExecuteQuery", this, params.getValues()); + } // Note, the RetrieveDesc returned by the code generation is null // in the case of a query having a false filter => // do not go to the datastore, but return an emtpy collection - result = (rd != null) ? pm.retrieve(rd, params.getValueFetcher()) : new ArrayList(); - } - finally - { + result = (rd == null) ? new ArrayList<>() : pm.retrieve(rd, params.getValueFetcher()); + } finally { // Note, the following stmt needs to be replaced by // pm.releaseSharedLock, as soon as the pm supports promoting a // shared lock into an exclusive lock. @@ -681,17 +642,14 @@ private Object doExecute(ParameterTable params) /** * This method checks a valid candidates setting for this query. */ - private void checkCandidates() - { - if ((candidateCollection == null) && (candidateClass != null)) - { + private void checkCandidates() { + if ((candidateCollection == null) && (candidateClass != null)) { // Set candidateCollection to the extent of the candidate class, if // candidateCollection is not specified. Note, the JDO spec defines // subclasses=true as the default, but since this is not supported // right now, I set it to subclasses=false. candidateCollection = pm.getExtent(candidateClass, false); - } - else { + } else { jqlc.checkCandidates(candidateClass, candidateCollection); } } @@ -699,63 +657,59 @@ private void checkCandidates() /** * */ - private void flush() - { + private void flush() { Transaction tx = pm.currentTransaction(); // flush updates to the database, // - if the is a transaction active and // - if transaction is not optimistic // - if ignoreCache is false - if ((tx != null) && tx.isActive() && - !tx.getOptimistic() && !this.ignoreCache) - { + if ((tx != null) && tx.isActive() && !tx.getOptimistic() && !this.ignoreCache) { pm.internalFlush(); } } /** Returns a string representation of the object. */ - public String toString() - { + @Override + public String toString() { StringBuffer repr = new StringBuffer(); - repr.append("QueryImpl("); //NOI18N - repr.append("candidateClass: "); //NOI18N + repr.append("QueryImpl("); + repr.append("candidateClass: "); repr.append(candidateClass); if (importDeclarations != null) { - repr.append(", imports: "); //NOI18N + repr.append(", imports: "); repr.append(importDeclarations); } if (parameterDeclarations != null) { - repr.append(", parameters: "); //NOI18N + repr.append(", parameters: "); repr.append(parameterDeclarations); } if (variableDeclarations != null) { - repr.append(", variables: "); //NOI18N + repr.append(", variables: "); repr.append(variableDeclarations); } if (filterExpression != null) { - repr.append(", filter: "); //NOI18N + repr.append(", filter: "); repr.append(filterExpression); } if (orderingSpecification != null) { - repr.append(", ordering: "); //NOI18N + repr.append(", ordering: "); repr.append(orderingSpecification); } if (resultExpression != null) { - repr.append(", result: "); //NOI18N + repr.append(", result: "); repr.append(resultExpression); } - repr.append(", prefetchEnabled: "); //NOI18N + repr.append(", prefetchEnabled: "); repr.append(prefetchEnabled); - repr.append(", identity: "); //NOI18N + repr.append(", identity: "); repr.append(identity()); - repr.append(")"); //NOI18N + repr.append(")"); return repr.toString(); } /** */ - private String identity() - { - return "QueryImpl@" + System.identityHashCode(this); //NOI18N + private String identity() { + return "QueryImpl@" + System.identityHashCode(this); } @@ -763,9 +717,7 @@ private String identity() * Define readObject to initialize the transient field paramtab after deserialization. * This object is used for synchronization, thus it cannot be null. */ - private void readObject(java.io.ObjectInputStream in) - throws java.io.IOException, ClassNotFoundException - { + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.paramtab = new ParameterTable(); this.createdBySerialization = true; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java index c2dcd581d28..bf21baaac9c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ErrorMsg.java @@ -25,7 +25,6 @@ import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.api.persistence.support.JDOQueryException; import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.util.ResourceBundle; @@ -36,130 +35,100 @@ * @author Michael Bouschen * @version 0.1 */ -public class ErrorMsg -{ +public class ErrorMsg { + /** * */ protected String context = null; - /** - * I18N support - */ - protected final static ResourceBundle messages = - I18NHelper.loadBundle(ErrorMsg.class); - - /** The logger */ - private static Logger logger = LogHelperQueryCompilerJDO.getLogger(); + protected static final ResourceBundle messages = I18NHelper.loadBundle(ErrorMsg.class); /** * */ - public String getContext() - { + public String getContext() { return context; } + /** * */ - public void setContext(String name) - { + public void setContext(String name) { context = name; } + /** * Indicates an error situation. + * * @param line line number * @param col column number * @param msg error message */ - public void error(int line, int col, String msg) - throws JDOQueryException - { + public void error(int line, int col, String msg) throws JDOQueryException { JDOQueryException ex; - if (line > 1) - { + if (line > 1) { // include line and column info Object args[] = {context, new Integer(line), new Integer(col), msg}; - ex = new JDOQueryException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msglinecolumn", args)); //NOI18N - } - else if (col > 0) - { + ex = new JDOQueryException(I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msglinecolumn", args)); // NOI18N + } else if (col > 0) { // include column info Object args[] = {context, new Integer(col), msg}; - ex = new JDOQueryException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msgcolumn", args)); //NOI18N - } - else - { + ex = new JDOQueryException(I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msgcolumn", args)); // NOI18N + } else { Object args[] = {context, msg}; - ex = new JDOQueryException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msg", args)); //NOI18N + ex = new JDOQueryException(I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msg", args)); // NOI18N } - logger.throwing("jqlc.ErrorMsg", "error", ex); throw ex; } + /** * Indicates that a feature is not supported by the current release. + * * @param line line number * @param col column number * @param msg message */ - public void unsupported(int line, int col, String msg) - throws JDOUnsupportedOptionException - { + public void unsupported(int line, int col, String msg) throws JDOUnsupportedOptionException { JDOUnsupportedOptionException ex; - if (line > 1) - { + if (line > 1) { // include line and column info Object args[] = {context, new Integer(line), new Integer(col), msg}; - ex = new JDOUnsupportedOptionException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msglinecolumn", args)); //NOI18N - } - else if (col > 0) - { + ex = new JDOUnsupportedOptionException( + I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msglinecolumn", args)); // NOI18N + } else if (col > 0) { // include column info Object args[] = {context, new Integer(col), msg}; - ex = new JDOUnsupportedOptionException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msgcolumn", args)); //NOI18N + ex = new JDOUnsupportedOptionException( + I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msgcolumn", args)); // NOI18N - } - else - { + } else { Object args[] = {context, msg}; - ex = new JDOUnsupportedOptionException(I18NHelper.getMessage( - messages, "jqlc.errormsg.generic.msg", args)); //NOI18N + ex = new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, "jqlc.errormsg.generic.msg", args)); // NOI18N } - logger.throwing("jqlc.ErrorMsg", "unsupported", ex); throw ex; } + /** * Indicates a fatal situation (implementation error). + * * @param msg error message */ - public void fatal(String msg) - throws JDOFatalInternalException - { - JDOFatalInternalException ex = new JDOFatalInternalException(msg); - logger.throwing("jqlc.ErrorMsg", "fatal", ex); - throw ex; + public void fatal(String msg) throws JDOFatalInternalException { + throw new JDOFatalInternalException(msg); } + /** * Indicates a fatal situation (implementation error). + * * @param msg error message */ - public void fatal(String msg, Exception nested) - throws JDOFatalInternalException - { - JDOFatalInternalException ex = new JDOFatalInternalException(msg, nested); - logger.throwing("jqlc.ErrorMsg", "fatal", ex); - throw ex; + public void fatal(String msg, Exception nested) throws JDOFatalInternalException { + throw new JDOFatalInternalException(msg, nested); } } - - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/JQLC.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/JQLC.java index 7577e9d2eab..220913aa5c3 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/JQLC.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/JQLC.java @@ -26,14 +26,15 @@ import com.sun.jdo.api.persistence.support.JDOQueryException; import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; import com.sun.jdo.spi.persistence.support.sqlstore.ExtentCollection; +import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.RetrieveDesc; import com.sun.jdo.spi.persistence.support.sqlstore.query.util.type.TypeTable; import com.sun.jdo.spi.persistence.utility.StringHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.Reader; import java.io.StringReader; +import java.lang.System.Logger; import java.util.Collection; import java.util.HashMap; import java.util.Map; @@ -44,6 +45,9 @@ import antlr.ANTLRException; import antlr.TokenBuffer; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; + /** * * @author Michael Bouschen @@ -64,7 +68,7 @@ public class JQLC protected ErrorMsg errorMsg; /** */ - protected Class candidateClass; + protected Class candidateClass; /** */ protected JQLAST filterAST = null; @@ -96,14 +100,14 @@ public class JQLC * It's ok to use WeakHashMap from java.util, because the key is a string * which is not referenced by the RD. */ - protected Map retrieveDescCache = new HashMap(); + protected Map retrieveDescCache = new HashMap<>(); /** I18N support */ - protected final static ResourceBundle messages = - I18NHelper.loadBundle(JQLC.class); + protected final static ResourceBundle messages = I18NHelper.loadBundle(JQLC.class); /** The logger */ - private static Logger logger = LogHelperQueryCompilerJDO.getLogger(); + private static final Logger LOG = System.getLogger(JQLC.class.getName(), LogHelperSQLStore.RESOURCE_BUNDLE); + /** * @@ -116,14 +120,13 @@ public JQLC() /** * */ - public void setClass(Class candidateClass) + public void setClass(Class candidateClass) { // check valid candidate class definition if (candidateClass == null) { JDOQueryException ex = new JDOQueryException(I18NHelper.getMessage( - messages, "jqlc.jqlc.generic.nocandidateclass")); //NOI18N - logger.throwing("jqlc.JQLC", "setClass", ex); //NOI18N + messages, "jqlc.jqlc.generic.nocandidateclass")); throw ex; } this.candidateClass = candidateClass; @@ -257,7 +260,7 @@ public void setFilter(String filter) // - the filter is empty or contians whitespecace only. // Internally the filter has to be specified, // otherwise semantic analysis has problems with empty AST. - filter = "true"; //NOI18N + filter = "true"; } try @@ -285,8 +288,6 @@ public void setPrefetchEnabled(boolean prefetchEnabled) */ public void semanticCheck(ParameterTable paramtab) { - boolean finer = logger.isLoggable(Logger.FINER); - boolean finest = logger.isLoggable(Logger.FINEST); this.typetab = TypeTable.getInstance(candidateClass.getClassLoader()); paramtab.init(); Semantic semantic = new Semantic(); @@ -298,19 +299,19 @@ public void semanticCheck(ParameterTable paramtab) queryAST = semantic.createQueryAST(classAST, importsAST, paramsAST, varsAST, orderingAST, resultAST, filterAST); - if (finest) logger.finest("LOG_JQLCDumpTree", queryAST.getTreeRepr("(AST)")); //NOI18N + LOG.log(TRACE, "LOG_JQLCDumpTree", queryAST.getTreeRepr("(AST)")); // start semantic check try { - if (finer) logger.finer("LOG_JQLCStartPass", "semantic analysis"); //NOI18N + LOG.log(DEBUG, "LOG_JQLCStartPass", "semantic analysis"); semantic.query(queryAST); queryAST = (JQLAST)semantic.getAST(); - if (finest) logger.finest("LOG_JQLCDumpTree", queryAST.getTreeRepr("(typed AST)")); //NOI18N + LOG.log(TRACE, "LOG_JQLCDumpTree", queryAST.getTreeRepr("(typed AST)")); } catch (ANTLRException ex) { - errorMsg.fatal("JQLC.semanticCheck unexpected exception", ex); //NOI18N + errorMsg.fatal("JQLC.semanticCheck unexpected exception", ex); } } @@ -319,8 +320,6 @@ public void semanticCheck(ParameterTable paramtab) */ public RetrieveDesc codeGen(PersistenceManager pm, ParameterTable paramtab) { - boolean finer = logger.isLoggable(Logger.FINER); - boolean finest = logger.isLoggable(Logger.FINEST); RetrieveDesc rd = null; // check if a RetrieveDescriptor for the actual parameter constellation @@ -329,8 +328,9 @@ public RetrieveDesc codeGen(PersistenceManager pm, ParameterTable paramtab) synchronized(retrieveDescCache) { - if (key != null) - rd = (RetrieveDesc)retrieveDescCache.get(key); + if (key != null) { + rd = retrieveDescCache.get(key); + } if (rd == null) { Optimizer optimizer = new Optimizer(); @@ -349,29 +349,30 @@ public RetrieveDesc codeGen(PersistenceManager pm, ParameterTable paramtab) // so I cannot call the optimzer before the query parameter values // are known. That's why optimization is part of codeGen which is // called by Query.execute and not called by Query.compile. - if (finer) logger.finer("LOG_JQLCStartPass", "optimizer"); //NOI18N + LOG.log(DEBUG, "LOG_JQLCStartPass", "optimizer"); optimizer.query(ast); // Do not store the optimizer result in the instance variable queryAST, // it cannot be reused by the next execution of this query. The next execute // might have different query parameter values, so the optimized AST is different. ast = (JQLAST)optimizer.getAST(); - if (finest) logger.finest("LOG_JQLCDumpTree", ast.getTreeRepr("(optimized AST)")); //NOI18N + LOG.log(TRACE, "LOG_JQLCDumpTree", ast.getTreeRepr("(optimized AST)")); - if (finer) logger.finer("LOG_JQLCStartPass", "code generation"); //NOI18N + LOG.log(DEBUG, "LOG_JQLCStartPass", "code generation"); codeGen.query(ast); rd = codeGen.getRetrieveDesc(); // add the current RetrieveDescriptor to the cache, // if the key is not null - if (key != null) + if (key != null) { retrieveDescCache.put(key, rd); + } } catch (ANTLRException ex) { - errorMsg.fatal("JQLC.codeGen unexpected exception", ex); //NOI18N + errorMsg.fatal("JQLC.codeGen unexpected exception", ex); } } else { - if (finer) logger.finest("LOG_JQLCReuseRetrieveDesc"); //NOI18N + LOG.log(TRACE, "LOG_JQLCReuseRetrieveDesc"); } } @@ -381,23 +382,27 @@ public RetrieveDesc codeGen(PersistenceManager pm, ParameterTable paramtab) /** * */ - public void checkCandidates(Class candidateClass, Collection candidateCollection) + public void checkCandidates(Class candidateClass, Collection candidateCollection) { - if (candidateClass == null) + if (candidateClass == null) { throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.jqlc.generic.nocandidateclass")); //NOI18N - if (!(candidateCollection instanceof ExtentCollection)) + I18NHelper.getMessage(messages, "jqlc.jqlc.generic.nocandidateclass")); + } + if (!(candidateCollection instanceof ExtentCollection)) { throw new JDOUnsupportedOptionException( - I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.memorycollection")); //NOI18N + I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.memorycollection")); + } - Class candidatePCClass = ((ExtentCollection)candidateCollection).getPersistenceCapableClass(); - if (candidatePCClass == null) + Class candidatePCClass = ((ExtentCollection)candidateCollection).getPersistenceCapableClass(); + if (candidatePCClass == null) { throw new JDOFatalInternalException( - I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.nullpc")); //NOI18N + I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.nullpc")); + } - if (!candidateClass.getName().equals(candidatePCClass.getName())) + if (!candidateClass.getName().equals(candidatePCClass.getName())) { throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.mismatch", candidateClass.getName())); //NOI18N + I18NHelper.getMessage(messages, "jqlc.jqlc.checkcandidates.mismatch", candidateClass.getName())); + } } /** */ diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/LogHelperQueryCompilerJDO.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/LogHelperQueryCompilerJDO.java index a6b5ed71676..7e157c15505 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/LogHelperQueryCompilerJDO.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/LogHelperQueryCompilerJDO.java @@ -16,9 +16,6 @@ package com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc; -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - /** * * @author Michael Bouschen @@ -38,11 +35,4 @@ public class LogHelperQueryCompilerJDO { */ protected static final String bundleName = "com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc.Bundle"; // NOI18N - - /** Return the logger for the sqlstore component - */ - public static Logger getLogger() { - return LogHelper.getLogger (componentName, bundleName, loader); - } - } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ParameterTable.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ParameterTable.java index 41689295933..ade19f4dd7c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ParameterTable.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/ParameterTable.java @@ -35,7 +35,6 @@ import com.sun.jdo.spi.persistence.utility.ParameterInfo; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; @@ -51,28 +50,28 @@ public class ParameterTable { /** Query parameter names */ - List names = null; + List names = null; /** Query parameter types */ - List types = null; + List types = null; /** Query Parameter values */ - transient List values = null; + transient List values = null; /** null key */ - private static final String NULL_ = "null"; //NOI18N + private static final String NULL_ = "null"; /** true key */ - private static final String TRUE_ = "true"; //NOI18N + private static final String TRUE_ = "true"; /** false key */ - private static final String FALSE_ = "false"; //NOI18N + private static final String FALSE_ = "false"; /** other key */ - private static final String OTHER_ = "other"; //NOI18N + private static final String OTHER_ = "other"; /** noparams key */ - private static final String NOPARAMS_ = "noparams"; //NOI18N + private static final String NOPARAMS_ = "noparams"; /** key parameter separator */ private static final char PARAMKEY_SEPARATOR = '/'; @@ -124,8 +123,8 @@ public void add(String name, Type type) */ public void init() { - this.names = new ArrayList(); - this.types = new ArrayList(); + this.names = new ArrayList<>(); + this.types = new ArrayList<>(); } /** @@ -134,7 +133,7 @@ public void init() */ public void initValueHandling() { - values = new ArrayList(names.size()); + values = new ArrayList<>(names.size()); final int size = names.size(); for (int i = 0; i < size; i++) { values.add(unbound); @@ -169,7 +168,7 @@ public void checkUnboundParams() if (values.get(i) == unbound) { throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.parametertable.checkunboundparams.unboundparam", //NOI18N + I18NHelper.getMessage(messages, "jqlc.parametertable.checkunboundparams.unboundparam", names.get(i))); } } @@ -180,15 +179,13 @@ public void checkUnboundParams() * ValueFetcher for the inputparameters. * @param actualParams */ - public void setValues(Map actualParams) + public void setValues(Map actualParams) { if (actualParams != null) { - for (Iterator i = actualParams.entrySet().iterator(); i.hasNext();) - { - Map.Entry actualParam = (Map.Entry)i.next(); - String name = (String)actualParam.getKey(); - Object value = actualParam.getValue(); + for (Map.Entry entry : actualParams.entrySet()) { + String name = entry.getKey(); + Object value = entry.getValue(); defineValueByName(name, value); } } @@ -200,11 +197,12 @@ public void setValues(Map actualParams) public Object getValueByName(String name) { int index = names.indexOf(name); - if (index == -1) + if (index == -1) { throw new JDOFatalInternalException(I18NHelper.getMessage( messages, - "jqlc.parametertable.getvaluebyname.undefined", //NOI18N + "jqlc.parametertable.getvaluebyname.undefined", name)); + } return getValueByIndex(index); } @@ -214,17 +212,18 @@ public Object getValueByName(String name) */ public Object getValueByIndex(int index) { - if ((index < 0) || (index >= values.size())) + if ((index < 0) || (index >= values.size())) { throw new JDOFatalInternalException(I18NHelper.getMessage( messages, - "jqlc.parametertable.getvaluebyindex.wrongindex", //NOI18N + "jqlc.parametertable.getvaluebyindex.wrongindex", String.valueOf(index))); + } return values.get(index); } /** Returns the list of parameter values. */ - public List getValues() + public List getValues() { return values; } @@ -252,8 +251,9 @@ public String getKeyForRetrieveDescCache() for (int i = 0; i < size; i++) { // Do not cache RetrieveDesc if the parameter type is pc class // or java.lang.Object => return null - if (isInlineType(types.get(i))) + if (isInlineType(types.get(i))) { return null; + } Object item = values.get(i); if (item == null) { @@ -294,11 +294,17 @@ public boolean inline(String paramName) int index = names.indexOf(paramName); Object value = values.get(index); - if (isInlineType(types.get(index))) return true; + if (isInlineType(types.get(index))) { + return true; + } - if (value == null) return true; + if (value == null) { + return true; + } - if (value instanceof Boolean) return true; + if (value instanceof Boolean) { + return true; + } return false; } @@ -323,8 +329,9 @@ private boolean isInlineType(Object type) (type instanceof PrimitiveType) || (type instanceof WrapperClassType) || (type instanceof MathType) || - (type instanceof DateType)) + (type instanceof DateType)) { return false; + } return true; } @@ -332,6 +339,7 @@ private boolean isInlineType(Object type) * Returns the parameter index for the specified parameter name. * @deprecated */ + @Deprecated public Integer getIndexForParamName(String paramName) { return new Integer(names.indexOf(paramName)); @@ -360,7 +368,7 @@ public ParameterInfo getParameterInfoForParamName(String paramName, String associatedField) { int index = names.indexOf(paramName); - Type type = (Type)types.get(index); + Type type = types.get(index); return new ParameterInfo(index, type.getEnumType(), associatedField); } @@ -370,9 +378,10 @@ public ParameterInfo getParameterInfoForParamName(String paramName, private void defineValueByName(String name, Object value) { int index = names.indexOf(name); - if (index == -1) + if (index == -1) { throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyname.undefinedparam", name)); //NOI18N + I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyname.undefinedparam", name)); + } defineValueByIndex(index, value); } @@ -382,24 +391,26 @@ private void defineValueByName(String name, Object value) private void defineValueByIndex(int index, Object value) { // index < 0 => implementation error - if (index < 0) + if (index < 0) { throw new JDOFatalInternalException(I18NHelper.getMessage( messages, - "jqlc.parametertable.definevaluebyindex.wrongindex", //NOI18N + "jqlc.parametertable.definevaluebyindex.wrongindex", String.valueOf(index))); + } // index > type.size => too many actual parameters - if (index >= types.size()) + if (index >= types.size()) { throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyindex.wrongnumberofargs")); //NOI18N + I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyindex.wrongnumberofargs")); + } // check type compatibility of actual and formal parameter - Class formalType = ((Type)types.get(index)).getJavaClass(); + Class formalType = types.get(index).getJavaClass(); if (!isCompatibleValue(formalType, value)) { String actualTypeName = ((value==null) ? "" : value.getClass().getName()); throw new JDOQueryException( - I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyindex.typemismatch", //NOI18N + I18NHelper.getMessage(messages, "jqlc.parametertable.definevaluebyindex.typemismatch", actualTypeName, formalType.getName())); } @@ -415,7 +426,7 @@ private void defineValueByIndex(int index, Object value) * @return true if the type of the value is compatible with the * formal type; false otherwise. */ - private boolean isCompatibleValue(Class formalType, Object value) + private boolean isCompatibleValue(Class formalType, Object value) { boolean isCompatible = true; @@ -424,9 +435,10 @@ private boolean isCompatibleValue(Class formalType, Object value) isCompatible = !formalType.isPrimitive(); } else { - Class actualType = value.getClass(); - if (formalType.isPrimitive()) + Class actualType = value.getClass(); + if (formalType.isPrimitive()) { formalType = JavaTypeHelper.getWrapperClass(formalType); + } isCompatible = formalType.isAssignableFrom(actualType); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/VariableTable.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/VariableTable.java index 432a311c3ff..863f54f39b7 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/VariableTable.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/jqlc/VariableTable.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 */ -/* - * VariableTable.java - * - * Created on April 12, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.jqlc; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -31,6 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; @@ -39,8 +35,7 @@ /** * The variable table * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ public class VariableTable { @@ -65,7 +60,7 @@ static class VarInfo /** * Set of JQLAST nodes denoting an access of this variable. */ - Set used; + Set used; /** * Dependency for this variable. @@ -85,7 +80,7 @@ static class VarInfo VarInfo() { this.constraint = null; - this.used = new HashSet(); + this.used = new HashSet<>(); this.dependsOn = null; this.status = UNCHECKED; } @@ -93,7 +88,7 @@ static class VarInfo VarInfo(VarInfo other) { this.constraint = other.constraint; - this.used = new HashSet(other.used); + this.used = new HashSet<>(other.used); this.dependsOn = other.dependsOn; this.status = other.status; } @@ -103,10 +98,10 @@ static class VarInfo private ErrorMsg errorMsg; /** List of names of declared variables. */ - private List declaredVars; + private List declaredVars; /** Map of variable infos. */ - private Map varInfos; + private Map varInfos; /** * Create an empty variable table @@ -114,8 +109,8 @@ static class VarInfo public VariableTable(ErrorMsg errorMsg) { this.errorMsg = errorMsg; - declaredVars = new ArrayList(); - varInfos = new HashMap(); + declaredVars = new ArrayList<>(); + varInfos = new HashMap<>(); } /** @@ -126,11 +121,11 @@ public VariableTable(VariableTable other) { errorMsg = other.errorMsg; declaredVars = other.declaredVars; - varInfos = new HashMap(); - for (Iterator i = other.varInfos.entrySet().iterator(); i.hasNext();) + varInfos = new HashMap<>(); + for (Iterator> i = other.varInfos.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry)i.next(); - varInfos.put(entry.getKey(), new VarInfo((VarInfo)entry.getValue())); + Entry entry = i.next(); + varInfos.put(entry.getKey(), new VarInfo(entry.getValue())); } } @@ -152,20 +147,22 @@ public void add(String name) public void markUsed(JQLAST variable, String dependendVar) { String name = variable.getText(); - VarInfo entry = (VarInfo)varInfos.get(name); - if (entry == null) + VarInfo entry = varInfos.get(name); + if (entry == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, "jqlc.variabletable.markused.varnotfound", //NOI18N name)); + } entry.used.add(variable); if (dependendVar != null) { - VarInfo dependendVarInfo = (VarInfo)varInfos.get(dependendVar); - if (dependendVarInfo.dependsOn != null) + VarInfo dependendVarInfo = varInfos.get(dependendVar); + if (dependendVarInfo.dependsOn != null) { throw new JDOFatalInternalException(I18NHelper.getMessage( messages, "jqlc.variabletable.markused.multidep", //NOI18N dependendVar, dependendVarInfo.dependsOn, name)); + } dependendVarInfo.dependsOn = name; } } @@ -177,12 +174,13 @@ public void markUsed(JQLAST variable, String dependendVar) public void markConstraint(JQLAST variable, JQLAST expr) { String name = variable.getText(); - VarInfo entry = (VarInfo)varInfos.get(name); - if (entry == null) + VarInfo entry = varInfos.get(name); + if (entry == null) { throw new JDOFatalInternalException(I18NHelper.getMessage( messages, "jqlc.variabletable.markconstraint.varnotfound", //NOI18N name)); + } String old = (entry.constraint==null ? null : entry.constraint.getText()); if ((old != null) && !old.equals(expr.getText())) { @@ -198,11 +196,11 @@ public void markConstraint(JQLAST variable, JQLAST expr) */ public void merge(VariableTable other) { - for (Iterator i = declaredVars.iterator(); i.hasNext();) + for (Iterator i = declaredVars.iterator(); i.hasNext();) { - String name = (String)i.next(); - VarInfo info = (VarInfo)varInfos.get(name); - VarInfo otherInfo = (VarInfo)other.varInfos.get(name); + String name = i.next(); + VarInfo info = varInfos.get(name); + VarInfo otherInfo = other.varInfos.get(name); // copy other info if this info is empty if ((info.constraint == null) && (info.used.size() == 0)) @@ -250,10 +248,10 @@ public void merge(VariableTable other) public void checkConstraints() { // iterate declaredVars to check the variables in the order they are declared - for (Iterator i = declaredVars.iterator(); i.hasNext();) + for (Iterator i = declaredVars.iterator(); i.hasNext();) { - String name = (String)i.next(); - VarInfo info = (VarInfo)varInfos.get(name); + String name = i.next(); + VarInfo info = varInfos.get(name); checkConstraint(name, info); } } @@ -278,7 +276,7 @@ protected void checkConstraint(String variable, VarInfo info) if (info.dependsOn != null) { - VarInfo dependendVarInfo = (VarInfo)varInfos.get(info.dependsOn); + VarInfo dependendVarInfo = varInfos.get(info.dependsOn); checkConstraint(info.dependsOn, dependendVarInfo); } @@ -298,11 +296,12 @@ protected void checkConstraint(String variable, VarInfo info) */ protected void attachConstraintToUsedAST(VarInfo info) { - for (Iterator i = info.used.iterator(); i.hasNext();) + for (Iterator i = info.used.iterator(); i.hasNext();) { - JQLAST varNode = (JQLAST)i.next(); - if (varNode.getFirstChild() == null) + JQLAST varNode = i.next(); + if (varNode.getFirstChild() == null) { varNode.setFirstChild(JQLAST.Factory.getInstance().dupTree(info.constraint)); + } } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/Nesting.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/Nesting.java index 2b3ce49a013..3e49c83744e 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/Nesting.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/Nesting.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 */ -/* - * Nesting.java - * - * Created on March 8, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.scope; import java.util.ArrayList; @@ -31,55 +26,54 @@ * of an identifier. If an identifier is declared its old * definition is hidden and stored in the actual nesting. * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ -public class Nesting -{ +public class Nesting { + /** * List of idents with hidden definitions in the actual scope. */ - protected List idents; + protected List idents; /** * List of hidden definitions; each definition in this list * corresponds to an identifier of the list idents. */ - protected List hiddenDefs; + protected List hiddenDefs; /** * Creates an new nesting. */ - public Nesting() - { - this.idents = new ArrayList(); - this.hiddenDefs = new ArrayList(); + public Nesting() { + this.idents = new ArrayList<>(); + this.hiddenDefs = new ArrayList<>(); } + /** * Adds a hidden definition to this. + * * @param ident name of the identifier * @param hidden the hidden definition of ident */ - public void add(String ident, Definition hidden) - { + public void add(String ident, Definition hidden) { idents.add(ident); hiddenDefs.add(hidden); } + /** * Returns an enumeration of idents with hidden definitions. */ - public Iterator getIdents() - { + public Iterator getIdents() { return idents.iterator(); } + /** * Returns an enumeration of hidden definitions. */ - public Iterator getHiddenDefinitions() - { + public Iterator getHiddenDefinitions() { return hiddenDefs.iterator(); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/SymbolTable.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/SymbolTable.java index b8f4d78428f..b3a50aaef41 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/SymbolTable.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/scope/SymbolTable.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 */ -/* - * SymbolTable.java - * - * Created on March 8, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.scope; import java.util.Hashtable; @@ -29,7 +24,7 @@ /** * The symbol table handling declared identifies. * - * @author Michael Bouschen + * @author Michael Bouschen 2000 * @version 0.1 */ public class SymbolTable @@ -42,12 +37,12 @@ public class SymbolTable /** * Stack of old definitions. */ - protected Stack nestings = new Stack(); + protected Stack nestings = new Stack<>(); /** * The table of declared identifier (symbols). */ - protected Hashtable symbols = new Hashtable(); + protected Hashtable symbols = new Hashtable<>(); /** * Opens a new scope. @@ -66,7 +61,7 @@ public void enterScope() */ public void leaveScope() { - forgetNesting((Nesting)nestings.pop()); + forgetNesting(nestings.pop()); actualScope--; } @@ -94,11 +89,11 @@ public int getActualScope() */ public Definition declare(String ident, Definition def) { - Definition old = (Definition)symbols.get(ident); + Definition old = symbols.get(ident); def.setScope(actualScope); if ((old == null) || (old.getScope() < actualScope)) { - Nesting nest = (Nesting)nestings.peek(); + Nesting nest = nestings.peek(); nest.add(ident, old); // save old definition in nesting symbols.put(ident, def); // install new definition as actual definition return null; @@ -130,7 +125,7 @@ public boolean isDeclared(String ident) */ public Definition getDefinition(String ident) { - return (Definition)symbols.get(ident); + return symbols.get(ident); } /** @@ -146,13 +141,13 @@ protected void forgetNesting(Nesting nesting) String ident = null; Definition hidden = null; - Iterator idents = nesting.getIdents(); - Iterator hiddenDefs = nesting.getHiddenDefinitions(); + Iterator idents = nesting.getIdents(); + Iterator hiddenDefs = nesting.getHiddenDefinitions(); while (idents.hasNext()) { - ident = (String) idents.next(); - hidden = (Definition) hiddenDefs.next(); + ident = idents.next(); + hidden = hiddenDefs.next(); if (hidden == null) { symbols.remove(ident); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/ClassType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/ClassType.java index bd6018ebbb9..65f049c2ceb 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/ClassType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/ClassType.java @@ -42,7 +42,7 @@ public class ClassType /** * */ - protected Map fieldInfos; + protected Map fieldInfos; /** * @@ -52,11 +52,11 @@ public class ClassType /** * */ - public ClassType(String name, Class clazz, int enumType, TypeTable typetab) + public ClassType(String name, Class clazz, int enumType, TypeTable typetab) { super(name, clazz, enumType); this.typetab = typetab; - this.fieldInfos = new HashMap(); + this.fieldInfos = new HashMap<>(); // get JDO model element if available ClassLoader classLoader = clazz.getClassLoader(); if (classLoader != null) @@ -76,7 +76,7 @@ public ClassType(String name, Class clazz, int enumType, TypeTable typetab) /** * */ - public ClassType(String name, Class clazz, TypeTable typetab) + public ClassType(String name, Class clazz, TypeTable typetab) { this(name, clazz, FieldTypeEnumeration.NOT_ENUMERATED, typetab); } @@ -138,14 +138,14 @@ public FieldInfo[] getFieldInfos() // NOTE, this code does not work for inheritance! //Field[] fields = clazz.getDeclaredFields(); - final Class cl = clazz; + final Class cl = clazz; Field[] fields = cl.getDeclaredFields(); synchronized(fieldInfos) { for (int i = 0; i < fields.length; i++) { String fieldName = fields[i].getName(); - FieldInfo fieldInfo = (FieldInfo)fieldInfos.get(fieldName); + FieldInfo fieldInfo = fieldInfos.get(fieldName); if (fieldInfo == null) { fieldInfos.put(fieldName, new FieldInfo(fields[i], this)); } @@ -159,10 +159,10 @@ public FieldInfo[] getFieldInfos() */ public FieldInfo getFieldInfo(final String fieldName) { synchronized(fieldInfos) { - FieldInfo fieldInfo = (FieldInfo)fieldInfos.get(fieldName); + FieldInfo fieldInfo = fieldInfos.get(fieldName); if (fieldInfo == null) { // NOTE, no inheritance! - final Class cl = clazz; + final Class cl = clazz; Field field; try { field = cl.getDeclaredField(fieldName); @@ -181,12 +181,12 @@ public FieldInfo getFieldInfo(final String fieldName) { /** * Return the list of key field names */ - public List getKeyFieldNames() + public List getKeyFieldNames() { if (pce != null) { PersistenceFieldElement[] persistentFields = pce.getFields(); - List names = new ArrayList(); + List names = new ArrayList<>(); for (int i = 0; i < persistentFields.length; i++) { if (persistentFields[i].isKey()) { diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/DateType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/DateType.java index 9d1ad63cf96..c15de6a7dc8 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/DateType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/DateType.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,28 +15,20 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * DateType.java - * - * Created on April 14, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** * Instances of this type represent the types java.util.Date, * java.sql.Date, java.sql.Time or java.sql.Timestamp. * - * @author Michael Bouschen + * @author Michael Bouschen 2000 */ -public class DateType - extends ClassType -{ +public class DateType extends ClassType { + /** * */ - public DateType(String name, Class clazz, int enumType, TypeTable typetab) - { + public DateType(String name, Class clazz, int enumType, TypeTable typetab) { super(name, clazz, enumType, typetab); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/FloatingPointType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/FloatingPointType.java index d275497d7cb..ed905827b33 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/FloatingPointType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/FloatingPointType.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 */ -/* - * FloatingPointType.java - * - * Created on April 5, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** @@ -34,7 +29,7 @@ public class FloatingPointType /** * */ - public FloatingPointType(String name, Class clazz, int enumType) + public FloatingPointType(String name, Class clazz, int enumType) { super(name, clazz, enumType); } @@ -46,16 +41,18 @@ public FloatingPointType(String name, Class clazz, int enumType) * @param value value to be converted * @return converted value */ + @Override public Number getValue(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("double".equals(getName())) + } else if ("double".equals(getName())) { ret = new Double(value.doubleValue()); - else if ("float".equals(getName())) + } else if ("float".equals(getName())) { ret = new Float(value.floatValue()); + } return ret; } @@ -65,16 +62,18 @@ else if ("float".equals(getName())) * @param value value to be negated * @return -value */ + @Override public Number negate(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("double".equals(getName())) + } else if ("double".equals(getName())) { ret = new Double(-value.doubleValue()); - else if ("float".equals(getName())) + } else if ("float".equals(getName())) { ret = new Float(-value.floatValue()); + } return ret; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/IntegralType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/IntegralType.java index 51301b70853..1c1deba388c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/IntegralType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/IntegralType.java @@ -35,7 +35,7 @@ public class IntegralType /** * */ - public IntegralType(String name, Class clazz, int enumType) + public IntegralType(String name, Class clazz, int enumType) { super(name, clazz, enumType); } @@ -47,20 +47,22 @@ public IntegralType(String name, Class clazz, int enumType) * @param value value to be converted * @return converted value */ + @Override public Number getValue(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("int".equals(getName())) + } else if ("int".equals(getName())) { ret = new Integer(value.intValue()); - else if ("long".equals(getName())) + } else if ("long".equals(getName())) { ret = new Long(value.longValue()); - else if ("byte".equals(getName())) + } else if ("byte".equals(getName())) { ret = new Byte(value.byteValue()); - else if ("short".equals(getName())) + } else if ("short".equals(getName())) { ret = new Short(value.shortValue()); + } return ret; } @@ -70,20 +72,22 @@ else if ("short".equals(getName())) * @param value value to be negated * @return -value */ + @Override public Number negate(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("int".equals(getName())) + } else if ("int".equals(getName())) { ret = new Integer(-value.intValue()); - else if ("long".equals(getName())) + } else if ("long".equals(getName())) { ret = new Long(-value.longValue()); - else if ("byte".equals(getName())) + } else if ("byte".equals(getName())) { ret = new Byte((byte)-value.byteValue()); - else if ("short".equals(getName())) + } else if ("short".equals(getName())) { ret = new Short((short)-value.shortValue()); + } return ret; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/MathType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/MathType.java index 9b016e187a2..517db010d25 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/MathType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/MathType.java @@ -39,7 +39,7 @@ public class MathType /** * */ - public MathType(String name, Class clazz, int enumType, TypeTable typetab) + public MathType(String name, Class clazz, int enumType, TypeTable typetab) { super(name, clazz, enumType, typetab); } @@ -47,6 +47,7 @@ public MathType(String name, Class clazz, int enumType, TypeTable typetab) /** * A numeric wrapper class type defines an ordering. */ + @Override public boolean isOrderable() { return true; @@ -59,35 +60,38 @@ public boolean isOrderable() * @param value value to be converted * @return converted value */ + @Override public Number getValue(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("java.math.BigDecimal".equals(getName())) + } else if ("java.math.BigDecimal".equals(getName())) { - if (value instanceof BigDecimal) + if (value instanceof BigDecimal) { ret = value; - else if (value instanceof BigInteger) + } else if (value instanceof BigInteger) { ret = new BigDecimal((BigInteger)value); - else if (value instanceof Double) + } else if (value instanceof Double) { ret = new BigDecimal(((Double)value).toString()); - else if (value instanceof Float) + } else if (value instanceof Float) { ret = new BigDecimal(((Float)value).toString()); - else if (value instanceof Number) - ret = BigDecimal.valueOf(((Number)value).longValue()); + } else if (value instanceof Number) { + ret = BigDecimal.valueOf(value.longValue()); + } } else if ("java.math.BigInteger".equals(getName())) { - if (value instanceof BigInteger) + if (value instanceof BigInteger) { ret = value; - else if (value instanceof Double) + } else if (value instanceof Double) { ret = (new BigDecimal(((Double)value).toString())).toBigInteger(); - else if (value instanceof Float) + } else if (value instanceof Float) { ret = (new BigDecimal(((Float)value).toString())).toBigInteger(); - else if (value instanceof Number) - ret = BigInteger.valueOf(((Number)value).longValue()); + } else if (value instanceof Number) { + ret = BigInteger.valueOf(value.longValue()); + } } return ret; @@ -98,35 +102,38 @@ else if (value instanceof Number) * @param value value to be negated * @return -value */ + @Override public Number negate(Number value) { Number ret = null; - if (value == null) + if (value == null) { ret = null; - else if ("java.math.BigDecimal".equals(getName())) + } else if ("java.math.BigDecimal".equals(getName())) { - if (value instanceof BigDecimal) + if (value instanceof BigDecimal) { ret = ((BigDecimal)value).negate(); - else if (value instanceof BigInteger) + } else if (value instanceof BigInteger) { ret = new BigDecimal(((BigInteger)value).negate()); - else if (value instanceof Double) + } else if (value instanceof Double) { ret = (new BigDecimal(((Double)value).toString())).negate(); - else if (value instanceof Float) + } else if (value instanceof Float) { ret = (new BigDecimal(((Float)value).toString())).negate(); - else if (value instanceof Number) - ret = BigDecimal.valueOf(-((Number)value).longValue()); + } else if (value instanceof Number) { + ret = BigDecimal.valueOf(-value.longValue()); + } } else if ("java.math.BigInteger".equals(getName())) { - if (value instanceof BigInteger) + if (value instanceof BigInteger) { ret = ((BigInteger)value).negate(); - else if (value instanceof Double) + } else if (value instanceof Double) { ret = (new BigDecimal(((Double)value).toString())).negate().toBigInteger(); - else if (value instanceof Float) + } else if (value instanceof Float) { ret = (new BigDecimal(((Float)value).toString())).negate().toBigInteger(); - else if (value instanceof Number) - ret = BigInteger.valueOf(-((Number)value).longValue()); + } else if (value instanceof Number) { + ret = BigInteger.valueOf(-value.longValue()); + } } return ret; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericType.java index d7df669a2f8..8fc45bdfdaa 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericType.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,19 +15,12 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * NumericType.java - * - * Created on March 8, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** * This class is the super class for all integral and floating point types. * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ public abstract class NumericType extends PrimitiveType @@ -35,7 +29,7 @@ public abstract class NumericType /** * */ - public NumericType(String name, Class clazz, int enumType) + public NumericType(String name, Class clazz, int enumType) { super(name, clazz, enumType); } @@ -43,6 +37,7 @@ public NumericType(String name, Class clazz, int enumType) /** * A numeric type defines an ordering. */ + @Override public boolean isOrderable() { return true; @@ -55,6 +50,7 @@ public boolean isOrderable() * @param value value to be converted * @return converted value */ + @Override public abstract Number getValue(Number value); /** @@ -62,6 +58,7 @@ public boolean isOrderable() * @param value value to be negated * @return -value */ + @Override public abstract Number negate(Number value); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericWrapperClassType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericWrapperClassType.java index 38fd2a7b948..5a25f15d180 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericWrapperClassType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/NumericWrapperClassType.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,18 +15,11 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * NumericWrapperClassType.java - * - * Created on April 14, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ public class NumericWrapperClassType extends WrapperClassType @@ -34,7 +28,7 @@ public class NumericWrapperClassType /** * */ - public NumericWrapperClassType(String name, Class clazz, int enumType, + public NumericWrapperClassType(String name, Class clazz, int enumType, PrimitiveType primitiveType, TypeTable typetab) { super(name, clazz, enumType, primitiveType, typetab); @@ -43,6 +37,7 @@ public NumericWrapperClassType(String name, Class clazz, int enumType, /** * A numeric wrapper class type defines an ordering. */ + @Override public boolean isOrderable() { return true; @@ -55,6 +50,7 @@ public boolean isOrderable() * @param value value to be converted * @return converted value */ + @Override public Number getValue(Number value) { return ((NumericType)primitiveType).getValue(value); @@ -65,6 +61,7 @@ public Number getValue(Number value) * @param value value to be negated * @return -value */ + @Override public Number negate(Number value) { return ((NumericType)primitiveType).negate(value); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/PrimitiveType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/PrimitiveType.java index 333a1dbbb52..516da9f683d 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/PrimitiveType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/PrimitiveType.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,20 +15,13 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * PrimitiveType.java - * - * Created on March 8, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** * Super class for boolean type, char type, * and all numeric types. * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ public class PrimitiveType extends Type @@ -40,7 +34,7 @@ public class PrimitiveType /** * */ - public PrimitiveType(String name, Class clazz, int enumType) + public PrimitiveType(String name, Class clazz, int enumType) { super(name, clazz, enumType); } @@ -48,12 +42,14 @@ public PrimitiveType(String name, Class clazz, int enumType) /** * */ + @Override public boolean isCompatibleWith(Type type) { - if (type instanceof PrimitiveType) + if (type instanceof PrimitiveType) { return ((PrimitiveType)type).clazz.isAssignableFrom(clazz); - else + } else { return false; + } } /** diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/Type.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/Type.java index 7f80e81c9b6..0ed167e3a64 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/Type.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/Type.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,15 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * Type.java - * - * Created on March 8, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; /** * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ -public abstract class Type -{ +public abstract class Type { /** * The name of the type represented by this object. */ @@ -39,7 +32,7 @@ public abstract class Type /** * The corresponding class object. */ - protected Class clazz; + protected Class clazz; /** * The FieldTypeEnumeration constant for this Type. @@ -51,7 +44,7 @@ public abstract class Type * @param name name of the type represented by this * @param clazz the class object for this type */ - public Type(String name, Class clazz) + public Type(String name, Class clazz) { this(name, clazz, FieldTypeEnumeration.NOT_ENUMERATED); } @@ -62,7 +55,7 @@ public Type(String name, Class clazz) * @param clazz the class object for this type * @param enumType the FieldTypeEnumeration value for this type */ - public Type(String name, Class clazz, int enumType) + public Type(String name, Class clazz, int enumType) { this.name = name; this.clazz = clazz; @@ -80,7 +73,7 @@ public String getName() /** * Returns the corresponding class object. */ - public Class getJavaClass() { + public Class getJavaClass() { return this.clazz; } @@ -114,6 +107,7 @@ public int getEnumType() /** * Representation of this type as a string. */ + @Override public String toString() { return getName(); @@ -124,14 +118,16 @@ public String toString() * * Two types are equal if their names are equal. */ + @Override public boolean equals(Object obj) { - if (obj == this) + if (obj == this) { return true; - else if (obj instanceof Type) + } else if (obj instanceof Type) { return this.name.equals(((Type)obj).name); - else + } else { return false; + } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/TypeTable.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/TypeTable.java index a74aca13705..4eec62cbad5 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/TypeTable.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/TypeTable.java @@ -116,16 +116,16 @@ public class TypeTable /** * The list of actual known types. */ - protected Map types = new HashMap(); + protected Map types = new HashMap<>(); /** Map of TypeTable instances. Key is a classLoader. */ - private static Map typeTables = new HashMap(); + private static Map typeTables = new HashMap<>(); /** */ public static TypeTable getInstance(ClassLoader classLoader) { synchronized (typeTables) { - TypeTable typeTable = (TypeTable)typeTables.get(classLoader); + TypeTable typeTable = typeTables.get(classLoader); if (typeTable == null) { typeTable = new TypeTable(classLoader); typeTables.put(classLoader, typeTable); @@ -155,47 +155,47 @@ private TypeTable(ClassLoader classLoader) booleanType = new BooleanType(); types.put(booleanType.getName(), booleanType); - charType = new IntegralType("char", char.class, FieldTypeEnumeration.CHARACTER_PRIMITIVE); //NOI18N + charType = new IntegralType("char", char.class, FieldTypeEnumeration.CHARACTER_PRIMITIVE); types.put(charType.getName(), charType); - byteType = new IntegralType("byte", byte.class, FieldTypeEnumeration.BYTE_PRIMITIVE); //NOI18N + byteType = new IntegralType("byte", byte.class, FieldTypeEnumeration.BYTE_PRIMITIVE); types.put(byteType.getName(), byteType); - shortType = new IntegralType("short", short.class, FieldTypeEnumeration.SHORT_PRIMITIVE); //NOI18N + shortType = new IntegralType("short", short.class, FieldTypeEnumeration.SHORT_PRIMITIVE); types.put(shortType.getName(), shortType); - intType = new IntegralType("int", int.class, FieldTypeEnumeration.INTEGER_PRIMITIVE); //NOI18N + intType = new IntegralType("int", int.class, FieldTypeEnumeration.INTEGER_PRIMITIVE); types.put(intType.getName(), intType); - longType = new IntegralType("long", long.class, FieldTypeEnumeration.LONG_PRIMITIVE); //NOI18N + longType = new IntegralType("long", long.class, FieldTypeEnumeration.LONG_PRIMITIVE); types.put(longType.getName(), longType); - floatType = new FloatingPointType("float", float.class, FieldTypeEnumeration.FLOAT_PRIMITIVE); //NOI18N + floatType = new FloatingPointType("float", float.class, FieldTypeEnumeration.FLOAT_PRIMITIVE); types.put(floatType.getName(), floatType); - doubleType = new FloatingPointType("double", double.class, FieldTypeEnumeration.DOUBLE_PRIMITIVE); //NOI18N + doubleType = new FloatingPointType("double", double.class, FieldTypeEnumeration.DOUBLE_PRIMITIVE); types.put(doubleType.getName(), doubleType); stringType = new StringType(this); types.put(stringType.getName(), stringType); WrapperClassType booleanClassType = - new WrapperClassType("java.lang.Boolean", Boolean.class, FieldTypeEnumeration.BOOLEAN, booleanType, this); //NOI18N + new WrapperClassType("java.lang.Boolean", Boolean.class, FieldTypeEnumeration.BOOLEAN, booleanType, this); types.put(booleanClassType.getName(), booleanClassType); NumericWrapperClassType byteClassType = - new NumericWrapperClassType("java.lang.Byte", Byte.class, FieldTypeEnumeration.BYTE, byteType, this); //NOI18N + new NumericWrapperClassType("java.lang.Byte", Byte.class, FieldTypeEnumeration.BYTE, byteType, this); types.put(byteClassType.getName(), byteClassType); NumericWrapperClassType shortClassType = - new NumericWrapperClassType("java.lang.Short", Short.class, FieldTypeEnumeration.SHORT, shortType, this); //NOI18N + new NumericWrapperClassType("java.lang.Short", Short.class, FieldTypeEnumeration.SHORT, shortType, this); types.put(shortClassType.getName(), shortClassType); NumericWrapperClassType intClassType = - new NumericWrapperClassType("java.lang.Integer", Integer.class, FieldTypeEnumeration.INTEGER, intType, this); //NOI18N + new NumericWrapperClassType("java.lang.Integer", Integer.class, FieldTypeEnumeration.INTEGER, intType, this); types.put(intClassType.getName(), intClassType); NumericWrapperClassType longClassType = - new NumericWrapperClassType("java.lang.Long", Long.class, FieldTypeEnumeration.LONG, longType, this); //NOI18N + new NumericWrapperClassType("java.lang.Long", Long.class, FieldTypeEnumeration.LONG, longType, this); types.put(longClassType.getName(), longClassType); NumericWrapperClassType charClassType = - new NumericWrapperClassType("java.lang.Character", Character.class, FieldTypeEnumeration.CHARACTER, charType, this); //NOI18N + new NumericWrapperClassType("java.lang.Character", Character.class, FieldTypeEnumeration.CHARACTER, charType, this); types.put(charClassType.getName(), charClassType); NumericWrapperClassType floatClassType = - new NumericWrapperClassType("java.lang.Float", Float.class, FieldTypeEnumeration.FLOAT, floatType, this); //NOI18N + new NumericWrapperClassType("java.lang.Float", Float.class, FieldTypeEnumeration.FLOAT, floatType, this); types.put(floatClassType.getName(), floatClassType); NumericWrapperClassType doubleClassType = - new NumericWrapperClassType("java.lang.Double", Double.class, FieldTypeEnumeration.DOUBLE, doubleType, this); //NOI18N + new NumericWrapperClassType("java.lang.Double", Double.class, FieldTypeEnumeration.DOUBLE, doubleType, this); types.put(doubleClassType.getName(), doubleClassType); booleanType.setWrapper(booleanClassType); @@ -207,9 +207,9 @@ private TypeTable(ClassLoader classLoader) floatType.setWrapper(floatClassType); doubleType.setWrapper(doubleClassType); - bigDecimalType = new MathType("java.math.BigDecimal", BigDecimal.class, FieldTypeEnumeration.BIGDECIMAL, this); //NOI18N + bigDecimalType = new MathType("java.math.BigDecimal", BigDecimal.class, FieldTypeEnumeration.BIGDECIMAL, this); types.put(bigDecimalType.getName(), bigDecimalType); - bigIntegerType = new MathType("java.math.BigInteger", BigInteger.class, FieldTypeEnumeration.BIGINTEGER, this); //NOI18N + bigIntegerType = new MathType("java.math.BigInteger", BigInteger.class, FieldTypeEnumeration.BIGINTEGER, this); types.put(bigIntegerType.getName(), bigIntegerType); // Date types @@ -240,13 +240,13 @@ public Type checkType(String name) { synchronized(types) { - Type result = (Type)types.get(name); + Type result = types.get(name); if (result == null) { // type not found => check repository try { - Class clazz = Class.forName(name, true, classLoader); + Class clazz = Class.forName(name, true, classLoader); result = new ClassType(name, clazz, this); types.put(name, result); } @@ -272,14 +272,15 @@ public Type checkType(String name) * @return the Type object representing the type with the * specified name or null when the type was not found. */ - public Type checkType(Class clazz) + public Type checkType(Class clazz) { - if (clazz == null) + if (clazz == null) { return null; + } String name = clazz.getName(); synchronized (types) { - Type result = (Type)types.get(name); + Type result = types.get(name); if (result == null) { @@ -298,14 +299,15 @@ public Type binaryNumericPromotion(Type left, Type right) { if ((left instanceof NumericType) && (right instanceof NumericType)) { - if (left.equals(doubleType) || right.equals(doubleType)) + if (left.equals(doubleType) || right.equals(doubleType)) { return doubleType; - else if (left.equals(floatType) || right.equals(floatType)) + } else if (left.equals(floatType) || right.equals(floatType)) { return floatType; - else if (left.equals(longType) || right.equals(longType)) + } else if (left.equals(longType) || right.equals(longType)) { return longType; - else + } else { return intType; + } } else { @@ -340,8 +342,8 @@ public Type unaryNumericPromotion(Type type) */ public boolean isNumberType(Type type) { - Type numberType = checkType("java.lang.Number"); //NOI18N - Type characterType = checkType("java.lang.Character"); //NOI18N + Type numberType = checkType("java.lang.Number"); + Type characterType = checkType("java.lang.Character"); return (type instanceof NumericType) || (type.isCompatibleWith(numberType)) || (type.isCompatibleWith(characterType)); @@ -353,10 +355,11 @@ public boolean isNumberType(Type type) */ public boolean isIntegralType(Type type) { - if (type instanceof IntegralType) + if (type instanceof IntegralType) { return true; - else if (type instanceof NumericWrapperClassType) + } else if (type instanceof NumericWrapperClassType) { return ((NumericWrapperClassType)type).getPrimitiveType() instanceof IntegralType; + } return false; } @@ -366,10 +369,11 @@ else if (type instanceof NumericWrapperClassType) */ public boolean isFloatingPointType(Type type) { - if (type instanceof FloatingPointType) + if (type instanceof FloatingPointType) { return true; - else if (type instanceof NumericWrapperClassType) + } else if (type instanceof NumericWrapperClassType) { return ((NumericWrapperClassType)type).getPrimitiveType() instanceof FloatingPointType; + } return false; } @@ -423,7 +427,7 @@ public boolean isPersistenceCapableType(Type type) */ public boolean isCollectionType(Type type) { - Type collectionType = checkType("java.util.Collection"); //NOI18N + Type collectionType = checkType("java.util.Collection"); return (type instanceof ClassType) && type.isCompatibleWith(collectionType); } @@ -434,7 +438,7 @@ public boolean isCollectionType(Type type) */ public boolean isJavaLangMathType(Type type) { - Type mathType = checkType("java.lang.Math"); //NOI18N + Type mathType = checkType("java.lang.Math"); return (type instanceof ClassType) && type.isCompatibleWith(mathType); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/WrapperClassType.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/WrapperClassType.java index 6affbcd6800..0e31236c342 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/WrapperClassType.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/query/util/type/WrapperClassType.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,22 +15,12 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * WrapperClassType.java - * - * Created on April 14, 2000 - */ - package com.sun.jdo.spi.persistence.support.sqlstore.query.util.type; /** - * - * @author Michael Bouschen - * @version 0.1 + * @author Michael Bouschen 2000 */ -public class WrapperClassType - extends ClassType -{ +public class WrapperClassType extends ClassType { /** * @@ -39,18 +30,16 @@ public class WrapperClassType /** * */ - public WrapperClassType(String name, Class clazz, int enumType, - PrimitiveType primitiveType, TypeTable typetab) - { + public WrapperClassType(String name, Class clazz, int enumType, PrimitiveType primitiveType, TypeTable typetab) { super(name, clazz, enumType, typetab); this.primitiveType = primitiveType; } + /** * */ - public PrimitiveType getPrimitiveType() - { + public PrimitiveType getPrimitiveType() { return primitiveType; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/ArrayList.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/ArrayList.java deleted file mode 100644 index e9d27e4fcdf..00000000000 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/ArrayList.java +++ /dev/null @@ -1,711 +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 - */ - -/* - * sco.ArrayList.java - */ - -package com.sun.jdo.spi.persistence.support.sqlstore.sco; - -import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; -import com.sun.jdo.api.persistence.support.JDOUserException; -import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceCapable; -import com.sun.jdo.spi.persistence.support.sqlstore.SCOCollection; -import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; - -import java.util.Collection; -import java.util.Iterator; -import java.util.ResourceBundle; - -import org.glassfish.persistence.common.I18NHelper; - - -/** - * A mutable 2nd class object date. - * @author Marina Vatkina - * @version 1.0 - * @see java.util.ArrayList - */ -public class ArrayList - extends java.util.ArrayList - implements SCOCollection -{ - - private transient PersistenceCapable owner; - - private transient String fieldName; - - private transient Class elementType; - - private transient boolean allowNulls; - - private transient java.util.Vector added = new java.util.Vector(); - - private transient java.util.Vector removed = new java.util.Vector(); - - /** - * I18N message handlers - */ - private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.impl.Bundle", // NOI18N - ArrayList.class.getClassLoader()); - - private final static ResourceBundle messages1 = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N - ArrayList.class.getClassLoader()); - - - /** - * Constructs an empty vector so that its internal data array - * has size 10 and its standard capacity increment is - * zero. Assigns owning object and field name - * @param owner the owning object - * @param fieldName the owning field name - * @param elementType the element types allowed - * @param allowNulls true if nulls are allowed - */ - public ArrayList(Object owner, String fieldName, Class elementType, boolean allowNulls) - { - super(); - if (owner instanceof PersistenceCapable) - { - this.owner = (PersistenceCapable)owner; - this.fieldName = fieldName; - } - this.elementType = elementType; - this.allowNulls = allowNulls; - } - - /** - * Constructs an empty vector with the specified initial capacity and - * with its capacity increment equal to zero. Assigns owning object and field name - * - * @param owner the owning object - * @param fieldName the owning field name - * @param elementType the element types allowed - * @param allowNulls true if nulls are allowed - * @param initialCapacity the initial capacity of the vector. - * @exception IllegalArgumentException if the specified initial capacity - * is negative - */ - public ArrayList(Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialCapacity) - { - super(initialCapacity); - if (owner instanceof PersistenceCapable) - { - this.owner = (PersistenceCapable)owner; - this.fieldName = fieldName; - } - this.elementType = elementType; - this.allowNulls = allowNulls; - } - - /** ------------------Public Methods----------------*/ - - /** - * Replaces the element at the specified position in this ArrayList with the - * specified element. - * - * @param index index of element to replace. - * @param element element to be stored at the specified position. - * @return the element previously at the specified position. - * @exception IndexOutOfBoundsException index out of range - * (index < 0 || index >= size()). - * @exception IllegalArgumentException fromIndex > toIndex. - * @see java.util.ArrayList - */ - public Object set(int index, Object element) { - - throwUnsupportedOption(); - - if (element == null) - { - if (allowNulls == false) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - // It is actualy remove - return this.remove(index); - } - - if (elementType == null || elementType.isAssignableFrom(element.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - Object o = super.set(index, element); - - if (added.remove(o) == false) - removed.add(o); - - if (removed.remove(element) == false) - added.add(element); - - // Apply updates - this.applyUpdates(stateManager, true); - - return o; - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {element}); - } - - } - - - /** - * Appends the specified element to the end of this ArrayList. - * - * @param o element to be appended to this ArrayList. - * @return true (as per the general contract of Collection.add). - * @see java.util.ArrayList - */ - public boolean add(Object o) { - if (allowNulls == false && o == null) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - - if (elementType == null || elementType.isAssignableFrom(o.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - if (removed.remove(o) == false) - added.add(o); - - boolean modified = super.add(o); - - // Apply updates - this.applyUpdates(stateManager, modified); - - return modified; - - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {o}); - } - } - - /** - * Removes the first occurrence of the specified element in this ArrayList - * If the ArrayList does not contain the element, it is unchanged. - * - * @param o element to be removed from this ArrayList, if present. - * @return true if the ArrayList contained the specified element. - * @see java.util.ArrayList - */ - public boolean remove(Object o) { - - // Because java.util.AbstractCollection.remove(Object) delegates remove() to remove(int) - // which is not supported, we cannot rely on jdk. We need to process remove here. - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - int i = super.indexOf(o); - Object obj = null; - if (i > -1) { - obj = super.remove(i); - - if (added.remove(obj) == false) - removed.add(obj); - - // Apply updates - this.applyUpdates(stateManager, true); - return true; - } - return false; - } - - /** - * Inserts the specified element at the specified position in this ArrayList. - * - * @param index index at which the specified element is to be inserted. - * @param element element to be inserted. - * @exception IndexOutOfBoundsException index is out of range - * (index < 0 || index > size()). - * @see java.util.ArrayList - */ - public void add(int index, Object element) { - if (allowNulls == false && element == null) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - - if (elementType == null || elementType.isAssignableFrom(element.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - super.add(index, element); - if (removed.remove(element) == false) - added.add(element); - - // Apply updates - this.applyUpdates(stateManager, true); - - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {element}); - } - - } - - /** - * Removes the element at the specified position in this ArrayList. - * shifts any subsequent elements to the left (subtracts one from their - * indices). Returns the element that was removed from the ArrayList. - * - * @param index the index of the element to removed. - * @exception IndexOutOfBoundsException index out of range (index - * < 0 || index >= size()). - * @see java.util.ArrayList - */ - public Object remove(int index) { - - throwUnsupportedOption(); - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - Object obj = super.remove(index); - - if (added.remove(obj) == false) - removed.add(obj); - - // Apply updates - this.applyUpdates(stateManager, true); - - return obj; - } - - /** - * Removes all of the elements from this ArrayList. The ArrayList will - * be empty after this call returns (unless it throws an exception). - * - * @see java.util.ArrayList - */ - public void clear() { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - for (Iterator iter = super.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (added.remove(o) == false) - removed.add(o); - } - added.clear(); - super.clear(); - - // Apply updates - this.applyUpdates(stateManager, true); - } - - /** - * Appends all of the elements in the specified Collection to the end of - * this ArrayList, in the order that they are returned by the specified - * Collection's Iterator. - * - * @param c elements to be inserted into this ArrayList. - * @exception IndexOutOfBoundsException index out of range (index - * < 0 || index > size()). - * @see java.util.ArrayList - */ - public boolean addAll(Collection c) { - if (allowNulls == false && c.contains(null)) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - - java.util.Vector errc = new java.util.Vector(); - if (elementType != null) - { - // iterate the collection and make a list of wrong elements. - Iterator i = c.iterator(); - while (i.hasNext()) - { - Object o = i.next(); - if (!elementType.isAssignableFrom(o.getClass())) - errc.add(o); - } - } - if (errc != null && errc.size() > 0) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), errc.toArray()); - } - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - removed.removeAll(c); - added.addAll(c); - - boolean modified = super.addAll(c); - - // Apply updates - this.applyUpdates(stateManager, modified); - - return modified; - } - - /** - * Removes from this ArrayList all of its elements that are contained in the - * specified Collection. - * - * @return true if this ArrayList changed as a result of the call. - * @see java.util.ArrayList - */ - public boolean removeAll(Collection c) { - boolean modified = false; - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - Iterator e = c.iterator(); - while (e.hasNext()) { - Object o = e.next(); - if(super.contains(o)) { - removeInternal(o); - if (added.remove(o) == false) - removed.add(o); - modified = true; - } - } - - // Apply updates - this.applyUpdates(stateManager, modified); - - return modified; - } - - /** - * Inserts all of the elements in in the specified Collection into this - * ArrayList at the specified position. Shifts the element currently at - * that position (if any) and any subsequent elements to the right - * (increases their indices). The new elements will appear in the ArrayList - * in the order that they are returned by the specified Collection's - * iterator. - * - * @param index index at which to insert first element - * from the specified collection. - * @param c elements to be inserted into this ArrayList. - * @exception IndexOutOfBoundsException index out of range (index - * < 0 || index > size()). - * @see java.util.ArrayList - */ - public boolean addAll(int index, Collection c) { - if (allowNulls == false && c.contains(null)) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - - java.util.Vector errc = new java.util.Vector(); - if (elementType != null) - { - // iterate the collection and make a list of wrong elements. - Iterator i = c.iterator(); - while (i.hasNext()) - { - Object o = i.next(); - if (!elementType.isAssignableFrom(o.getClass())) - errc.add(o); - } - } - if (errc != null && errc.size() > 0) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), errc.toArray()); - } - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - removed.removeAll(c); - added.addAll(c); - - boolean modified = super.addAll(index, c); - - // Apply updates - this.applyUpdates(stateManager, modified); - - return modified; - } - - /** - * Retains only the elements in this ArrayList that are contained in the - * specified Collection. - * - * @return true if this ArrayList changed as a result of the call. - * @see java.util.ArrayList - */ - public boolean retainAll(Collection c) - { - boolean modified = false; - java.util.Vector v = new java.util.Vector(); - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); - - for (Iterator iter = super.iterator(); iter.hasNext();) - { - Object o = iter.next(); - if (!c.contains(o)) - { - v.add(o); - if (added.remove(o) == false) - removed.add(o); - - modified = true; - } - } - - // Now remove the rest (stored in "v") - for (Iterator iter = v.iterator(); iter.hasNext();) - { - removeInternal(iter.next()); - } - - // Apply updates - this.applyUpdates(stateManager, modified); - - return modified; - } - - /** - * Creates and returns a copy of this object. - * - *

    Mutable Second Class Objects are required to provide a public - * clone method in order to allow for copying PersistenceCapable - * objects. In contrast to Object.clone(), this method must not throw a - * CloneNotSupportedException. - */ - public Object clone() - { - ArrayList obj = (ArrayList)super.clone(); - obj.unsetOwner(); - - return obj; - } - - /** - * Creates and returns a copy of this object without resetting the owner and field value. - * - */ - public Object cloneInternal() - { - return super.clone(); - } - - /** - * Cleans removed and added lists - */ - public void reset() - { - added.clear(); - removed.clear(); - } - - public void markDeferred() - { - } - - public boolean isDeferred() - { - return false; - } - - public void applyDeferredUpdates(Collection c) - { - super.addAll(c); - } - - /** - * Adds an object to the list without recording changes - */ - public void addInternal(Object o) - { - super.add(o); - } - - /** - * Adds a Collection to the list without recording changes - */ - public void addAllInternal(Collection c) - { - super.addAll(c); - } - - /** - * @inheritDoc - */ - public void addToBaseCollection(Object o) - { - super.add(o); - } - - /** - * Removes from this collection without recording changes - */ - public void removeAllInternal(Collection c) - { - super.removeAll(c); - } - - /** - * Returns added collection - * - * @return added collection of added elements - */ - public Collection getAdded() - { - return (Collection)added; - } - - /** - * Returns removed collection - * - * @return removed collection of removed elements - */ - public Collection getRemoved() - { - return (Collection)removed; - } - - - /** - * Clears Collection without notifing the owner - */ - public void clearInternal() - { - super.clear(); - this.reset(); - } - - /** - * Removes an element without notifing the owner - */ - public void removeInternal(Object o) - { - int i = super.indexOf(o); - super.remove(i); - } - - /** - * Nullifies references to the owner Object and Field - */ - public void unsetOwner() - { - this.owner = null; - this.fieldName = null; - this.elementType = null; - added.clear(); - removed.clear(); - } - - /** - * Returns the owner object of the SCO instance - * - * @return owner object - */ - public Object getOwner() - { - return this.owner; - } - - /** - * Returns the field name - * - * @return field name as java.lang.String - */ - public String getFieldName() - { - return this.fieldName; - } - - /** - * Marks object dirty - */ - public StateManager makeDirty() - { - if (owner != null) - { - StateManager stateManager = owner.jdoGetStateManager(); - if (stateManager != null) - { - stateManager.makeDirty(fieldName); - } - - return stateManager; - } - return null; - } - /** - * Apply changes (can be a no-op) - */ - public void applyUpdates(StateManager sm, boolean modified) - { - - if (modified && sm != null) - { - sm.applyUpdates(fieldName, this); - } - } - - /** - * Throw JDOUnsupportedOptionException - */ - private void throwUnsupportedOption() - { - // Index operation that changes the underline collection - // is not supported in 2_beta. Bug 4370474 - throw new JDOUnsupportedOptionException(I18NHelper.getMessage(messages, - "sco.not_supported")); //NOI18N - } - - /** - * Set the owner if this instance is not owned. - * @see SCOCollection#setOwner - * @param owner the new owner. - * @param fieldName the new field name. - * @param elementType the new element type as Class, or null if type - * is not to be checked. - */ - public void setOwner(Object owner, String fieldName, Class elementType) { - - if (this.owner != null) { - throw new JDOUserException(I18NHelper.getMessage( - messages1, "core.statemanager.anotherowner"), // NOI18N - new Object[]{this.owner, this.fieldName}); - } - if (owner instanceof PersistenceCapable) { - this.owner = (PersistenceCapable)owner; - this.fieldName = fieldName; - this.elementType = elementType; - } - } -} diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/HashSet.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/HashSet.java index f01c6784534..c5aecb21a25 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/HashSet.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/HashSet.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,10 +15,6 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * sco.HashSet.java - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sco; import com.sun.jdo.api.persistence.support.JDOUserException; @@ -36,26 +33,24 @@ /** * A mutable 2nd class object date. - * @author Marina Vatkina - * @version 1.0 + * @author Marina Vatkina 2000 * @see java.util.HashSet */ -public class HashSet - extends java.util.HashSet - implements SCOCollection -{ +public class HashSet extends java.util.HashSet implements SCOCollection { + + private static final long serialVersionUID = 2489812924578469637L; private transient PersistenceCapable owner; private transient String fieldName; - private transient Class elementType; + private transient Class elementType; private transient boolean allowNulls; - private transient java.util.HashSet added = new java.util.HashSet(); + private transient java.util.HashSet added = new java.util.HashSet<>(); - private transient java.util.HashSet removed = new java.util.HashSet(); + private transient java.util.HashSet removed = new java.util.HashSet<>(); private transient boolean isDeferred; @@ -63,11 +58,11 @@ public class HashSet * I18N message handlers */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.impl.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.impl.Bundle", HashSet.class.getClassLoader()); private final static ResourceBundle messages1 = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", HashSet.class.getClassLoader()); @@ -80,7 +75,7 @@ public class HashSet * @param elementType the element types allowed * @param allowNulls true if nulls are allowed */ - public HashSet(Object owner, String fieldName, Class elementType, boolean allowNulls) + public HashSet(Object owner, String fieldName, Class elementType, boolean allowNulls) { super(); if (owner instanceof PersistenceCapable) @@ -106,7 +101,7 @@ public HashSet(Object owner, String fieldName, Class elementType, boolean allowN * @see java.util.HashSet */ public HashSet(Object owner, String fieldName, - Class elementType, boolean allowNulls, + Class elementType, boolean allowNulls, int initialCapacity) { super(initialCapacity); @@ -130,18 +125,19 @@ public HashSet(Object owner, String fieldName, * element. * @see java.util.HashSet */ + @Override public boolean add(Object o) { if (allowNulls == false && o == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + "sco.nulls_not_allowed")); } if (elementType != null && !elementType.isAssignableFrom(o.getClass())) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N + "sco.classcastexception", elementType.getName()), new ClassCastException(), new Object[] {o}); } @@ -230,32 +226,34 @@ public boolean add(Object o) * @see java.util.AbstractCollection * @see java.util.HashSet */ - public boolean addAll(Collection c) + @Override + public boolean addAll(Collection c) { if (allowNulls == false && c.contains(null)) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + "sco.nulls_not_allowed")); } - ArrayList errc = new ArrayList(); + ArrayList errc = new ArrayList<>(); if (elementType != null) { // iterate the collection and make a list of wrong elements. - Iterator i = c.iterator(); + Iterator i = c.iterator(); while (i.hasNext()) { Object o = i.next(); - if (!elementType.isAssignableFrom(o.getClass())) + if (!elementType.isAssignableFrom(o.getClass())) { errc.add(o); + } } } if (errc != null && errc.size() > 0) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N + "sco.classcastexception", elementType.getName()), new ClassCastException(), errc.toArray()); } @@ -279,7 +277,7 @@ public boolean addAll(Collection c) // Mark the field as dirty stateManager.makeDirty(fieldName); - for (Iterator iter = c.iterator(); iter.hasNext();) + for (Iterator iter = c.iterator(); iter.hasNext();) { Object o = iter.next(); if (!super.contains(o)) @@ -337,6 +335,7 @@ public boolean addAll(Collection c) * @return true if the set contained the specified element. * @see java.util.HashSet */ + @Override public boolean remove(Object o) { // Mark the field as dirty @@ -403,7 +402,8 @@ public boolean remove(Object o) * @see java.util.HashSet * @see java.util.AbstractCollection */ - public boolean removeAll(Collection c) + @Override + public boolean removeAll(Collection c) { // Mark the field as dirty @@ -424,7 +424,7 @@ public boolean removeAll(Collection c) { stateManager.makeDirty(fieldName); - for (Iterator iter = c.iterator(); iter.hasNext();) + for (Iterator iter = c.iterator(); iter.hasNext();) { Object o = iter.next(); if (super.contains(o)) @@ -474,7 +474,8 @@ public boolean removeAll(Collection c) * @see java.util.HashSet * @see java.util.AbstractCollection */ - public boolean retainAll(Collection c) + @Override + public boolean retainAll(Collection c) { if (owner != null) { @@ -494,7 +495,7 @@ public boolean retainAll(Collection c) // Mark the field as dirty stateManager.makeDirty(fieldName); - for (Iterator iter = super.iterator(); iter.hasNext();) + for (Iterator iter = super.iterator(); iter.hasNext();) { Object o = iter.next(); if (!c.contains(o)) @@ -536,6 +537,7 @@ public boolean retainAll(Collection c) * Removes all of the elements from this set. * @see java.util.HashSet */ + @Override public void clear() { if (owner != null) @@ -559,7 +561,7 @@ public void clear() removed.clear(); added.clear(); - for (Iterator iter = super.iterator(); iter.hasNext();) + for (Iterator iter = super.iterator(); iter.hasNext();) { removed.add(iter.next()); } @@ -593,6 +595,7 @@ public void clear() * objects. In contrast to Object.clone(), this method must not throw a * CloneNotSupportedException. */ + @Override public Object clone() { HashSet obj = (HashSet) super.clone(); @@ -612,33 +615,38 @@ public Object clone() * @return an Iterator over the elements in this set. * @see java.util.ConcurrentModificationException */ - public Iterator iterator() { + @Override + public Iterator iterator() { return new SCOHashIterator(super.iterator(), this); } - private class SCOHashIterator implements Iterator { - Iterator _iterator = null; + private class SCOHashIterator implements Iterator { + Iterator _iterator = null; HashSet _caller = null; Object lastReturned = null; - SCOHashIterator(Iterator it, HashSet cl) { + SCOHashIterator(Iterator it, HashSet cl) { _iterator = it; _caller = cl; } + @Override public boolean hasNext() { return _iterator.hasNext(); } + @Override public Object next() { lastReturned = _iterator.next(); return lastReturned; } + @Override public void remove() { // Check if called twice. - if (lastReturned == null) + if (lastReturned == null) { throw new IllegalStateException(); + } if (_caller.owner != null) { // Mark the field as dirty @@ -689,6 +697,7 @@ public void remove() { * Creates and returns a copy of this object without resetting the owner and field value. * */ + @Override public Object cloneInternal() { return super.clone(); @@ -697,19 +706,23 @@ public Object cloneInternal() /** * Cleans removed and added lists */ + @Override public void reset() { // RESOLVE: do we need to synchronize this?? - if (added != null) + if (added != null) { added.clear(); + } - if (removed != null) + if (removed != null) { removed.clear(); + } } /** * Mark this HashSet as deferred. */ + @Override public void markDeferred() { isDeferred = true; @@ -718,6 +731,7 @@ public void markDeferred() /** * Return true is this HashSet is deferred, false otherwise. */ + @Override public boolean isDeferred() { return isDeferred; @@ -728,7 +742,8 @@ public boolean isDeferred() * with c and they apply any deferred updates specified by the added and * removed lists. */ - public void applyDeferredUpdates(Collection c) + @Override + public void applyDeferredUpdates(Collection c) { if (!isDeferred) { @@ -749,6 +764,7 @@ public void applyDeferredUpdates(Collection c) * Adds an object to the list without recording changes if the HashSet is * not deferred. Otherwise, add o to the added list. */ + @Override public void addInternal(Object o) { if (isDeferred) @@ -769,14 +785,15 @@ public void addInternal(Object o) * Adds a Collection to the list without recording changes if the HashSet is * not deferred. Otherwise, add o to the removed list. */ - public void addAllInternal(Collection c) + @Override + public void addAllInternal(Collection c) { if (c == null) { return; } - Iterator iter = c.iterator(); + Iterator iter = c.iterator(); while (iter.hasNext()) { @@ -784,9 +801,7 @@ public void addAllInternal(Collection c) } } - /** - * @inheritDoc - */ + @Override public void addToBaseCollection(Object o) { super.add(o); @@ -796,14 +811,15 @@ public void addToBaseCollection(Object o) * Remove c from the list if the HashSet is not deferred. * Otherwise, add c to the removed list. */ - public void removeAllInternal(Collection c) + @Override + public void removeAllInternal(Collection c) { if (c == null) { return; } - Iterator iter = c.iterator(); + Iterator iter = c.iterator(); while (iter.hasNext()) { @@ -816,9 +832,10 @@ public void removeAllInternal(Collection c) * * @return added collection of added elements */ - public Collection getAdded() + @Override + public Collection getAdded() { - return (Collection)added; + return added; } /** @@ -826,15 +843,17 @@ public Collection getAdded() * * @return removed collection of removed elements */ - public Collection getRemoved() + @Override + public Collection getRemoved() { - return (Collection)removed; + return removed; } /** * Clears Collection without notifing the owner */ + @Override public void clearInternal() { super.clear(); @@ -844,6 +863,7 @@ public void clearInternal() /** * Removes an element without notifing the owner */ + @Override public void removeInternal(Object o) { if (isDeferred) @@ -863,6 +883,7 @@ public void removeInternal(Object o) /** * Nullifies references to the owner Object and Field */ + @Override public void unsetOwner() { this.owner = null; @@ -877,6 +898,7 @@ public void unsetOwner() * * @return owner object */ + @Override public Object getOwner() { return this.owner; @@ -887,6 +909,7 @@ public Object getOwner() * * @return field name as java.lang.String */ + @Override public String getFieldName() { return this.fieldName; @@ -895,6 +918,7 @@ public String getFieldName() /** * Marks object dirty */ + @Override public StateManager makeDirty() { StateManager stateManager = owner.jdoGetStateManager(); @@ -911,6 +935,7 @@ public StateManager makeDirty() /** * Apply changes (can be a no-op) */ + @Override public void applyUpdates(StateManager sm, boolean modified) { if (modified && sm != null) @@ -927,11 +952,12 @@ public void applyUpdates(StateManager sm, boolean modified) * @param elementType the new element type as Class, or null if type * is not checked or not supported. */ - public void setOwner(Object owner, String fieldName, Class elementType) { + @Override + public void setOwner(Object owner, String fieldName, Class elementType) { if (this.owner != null) { throw new JDOUserException(I18NHelper.getMessage( - messages1, "core.statemanager.anotherowner"), // NOI18N + messages1, "core.statemanager.anotherowner"), new Object[]{this.owner, this.fieldName}); } if (owner instanceof PersistenceCapable) { diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/Vector.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/Vector.java index e58a8db907a..44eea6da65f 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/Vector.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sco/Vector.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,10 +15,6 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * sco.Vector.java - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sco; import com.sun.jdo.api.persistence.support.JDOUnsupportedOptionException; @@ -35,36 +32,34 @@ /** * A mutable 2nd class object date. - * @author Marina Vatkina - * @version 1.0 + * @author Marina Vatkina 2000 * @see java.util.Vector */ -public class Vector - extends java.util.Vector - implements SCOCollection -{ +public class Vector extends java.util.Vector implements SCOCollection { + + private static final long serialVersionUID = 5812205137627529003L; private transient PersistenceCapable owner; private transient String fieldName; - private transient Class elementType; + private transient Class elementType; private transient boolean allowNulls; - private transient java.util.Vector added = new java.util.Vector(); + private transient java.util.Vector added = new java.util.Vector<>(); - private transient java.util.Vector removed = new java.util.Vector(); + private transient java.util.Vector removed = new java.util.Vector<>(); /** * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.impl.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.impl.Bundle", Vector.class.getClassLoader()); private final static ResourceBundle messages1 = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", Vector.class.getClassLoader()); /** @@ -76,16 +71,14 @@ public class Vector * @param elementType the element types allowed * @param allowNulls true if nulls are allowed */ - public Vector(Object owner, String fieldName, Class elementType, boolean allowNulls) - { - super(); - if (owner instanceof PersistenceCapable) - { - this.owner = (PersistenceCapable)owner; - this.fieldName = fieldName; + public Vector(Object owner, String fieldName, Class elementType, boolean allowNulls) { + super(); + if (owner instanceof PersistenceCapable) { + this.owner = (PersistenceCapable) owner; + this.fieldName = fieldName; } - this.elementType = elementType; - this.allowNulls = allowNulls; + this.elementType = elementType; + this.allowNulls = allowNulls; } /** @@ -100,17 +93,14 @@ public Vector(Object owner, String fieldName, Class elementType, boolean allowNu * @exception IllegalArgumentException if the specified initial capacity * is negative */ - public Vector(Object owner, String fieldName, - Class elementType, boolean allowNulls, int initialCapacity) - { - super(initialCapacity); - if (owner instanceof PersistenceCapable) - { - this.owner = (PersistenceCapable)owner; - this.fieldName = fieldName; + public Vector(Object owner, String fieldName, Class elementType, boolean allowNulls, int initialCapacity) { + super(initialCapacity); + if (owner instanceof PersistenceCapable) { + this.owner = (PersistenceCapable) owner; + this.fieldName = fieldName; } - this.elementType = elementType; - this.allowNulls = allowNulls; + this.elementType = elementType; + this.allowNulls = allowNulls; } /** ------------------Public Methods----------------*/ @@ -125,43 +115,40 @@ public Vector(Object owner, String fieldName, * @exception ArrayIndexOutOfBoundsException if the index was invalid. * @see java.util.Vector */ + @Override public synchronized void setElementAt(Object obj, int index) { - - throwUnsupportedOption(); - - if (obj == null) - { - if (allowNulls == false) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + throwUnsupportedOption(); + + if (obj == null) { + if (allowNulls == false) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.nulls_not_allowed")); + } + // It is actualy remove + this.removeElementAt(index); } - // It is actualy remove - this.removeElementAt(index); - } - if (elementType == null || elementType.isAssignableFrom(obj.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + if (elementType == null || elementType.isAssignableFrom(obj.getClass())) { + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - Object o = super.elementAt(index); - super.setElementAt(obj, index); + Object o = super.elementAt(index); + super.setElementAt(obj, index); - if (added.remove(o) == false) - removed.add(o); + if (added.remove(o) == false) { + removed.add(o); + } - if (removed.remove(obj) == false) - added.add(obj); + if (removed.remove(obj) == false) { + added.add(obj); + } - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {obj}); - } + } else { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.classcastexception", elementType.getName()), + new ClassCastException(), new Object[] {obj}); + } } @@ -173,20 +160,21 @@ public synchronized void setElementAt(Object obj, int index) { * @exception ArrayIndexOutOfBoundsException if the index was invalid. * @see java.util.Vector */ + @Override public synchronized void removeElementAt(int index) { + throwUnsupportedOption(); - throwUnsupportedOption(); - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - Object obj = super.elementAt(index); + Object obj = super.elementAt(index); super.removeElementAt(index); - if (added.remove(obj) == false) - removed.add(obj); + if (added.remove(obj) == false) { + removed.add(obj); + } - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); } @@ -199,32 +187,30 @@ public synchronized void removeElementAt(int index) { * @exception ArrayIndexOutOfBoundsException if the index was invalid. * @see java.util.Vector */ + @Override public synchronized void insertElementAt(Object obj, int index) { - if (allowNulls == false && obj == null) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + if (allowNulls == false && obj == null) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.nulls_not_allowed")); } - if (elementType == null || elementType.isAssignableFrom(obj.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + if (elementType == null || elementType.isAssignableFrom(obj.getClass())) { + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - super.insertElementAt(obj, index); - if (removed.remove(obj) == false) - added.add(obj); + super.insertElementAt(obj, index); + if (removed.remove(obj) == false) { + added.add(obj); + } - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {obj}); + } else { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.classcastexception", elementType.getName()), + new ClassCastException(), new Object[] {obj}); + } } - } /** * Adds the specified component to the end of this vector, @@ -233,30 +219,28 @@ public synchronized void insertElementAt(Object obj, int index) { * @param obj the component to be added. * @see java.util.Vector */ + @Override public synchronized void addElement(Object obj) { - if (allowNulls == false && obj == null) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + if (allowNulls == false && obj == null) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.nulls_not_allowed")); } - if (elementType == null || elementType.isAssignableFrom(obj.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + if (elementType == null || elementType.isAssignableFrom(obj.getClass())) { + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - super.addElement(obj); - if (removed.remove(obj) == false) - added.add(obj); + super.addElement(obj); + if (removed.remove(obj) == false) { + added.add(obj); + } - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {obj}); - } + } else { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.classcastexception", elementType.getName()), + new ClassCastException(), new Object[] {obj}); + } } @@ -269,6 +253,7 @@ public synchronized void addElement(Object obj) { * vector; false otherwise. * @see java.util.Vector */ + @Override public synchronized boolean removeElement(Object obj) { // Because java.util.Vector.removeElement(Object) calls internally removeElementAt(int) @@ -281,8 +266,9 @@ public synchronized boolean removeElement(Object obj) { if (i > -1) { super.removeElementAt(i); - if (added.remove(obj) == false) - removed.add(obj); + if (added.remove(obj) == false) { + removed.add(obj); + } // Apply updates this.applyUpdates(stateManager, true); @@ -297,21 +283,23 @@ public synchronized boolean removeElement(Object obj) { * * @see java.util.Vector */ + @Override public synchronized void removeAllElements() { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - for (Iterator iter = super.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (added.remove(o) == false) - removed.add(o); - } - added.clear(); + for (Iterator iter = super.iterator(); iter.hasNext();) { + Object o = iter.next(); + if (added.remove(o) == false) { + removed.add(o); + } + } + added.clear(); - super.removeAllElements(); + super.removeAllElements(); - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); } @@ -325,46 +313,43 @@ public synchronized void removeAllElements() { * @param element element to be stored at the specified position. * @return the element previously at the specified position. * @exception ArrayIndexOutOfBoundsException index out of range - * (index < 0 || index >= size()). + * (index < 0 || index >= size()). * @exception IllegalArgumentException fromIndex > toIndex. * @see java.util.Vector */ + @Override public synchronized Object set(int index, Object element) { - - throwUnsupportedOption(); - - if (element == null) - { - if (allowNulls == false) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N - } - // It is actualy remove - return this.remove(index); + throwUnsupportedOption(); + + if (element == null) { + if (allowNulls == false) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.nulls_not_allowed")); + } + // It is actualy remove + return this.remove(index); } - if (elementType == null || elementType.isAssignableFrom(element.getClass())) - { - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + if (elementType == null || elementType.isAssignableFrom(element.getClass())) { + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - Object o = super.set(index, element); + Object o = super.set(index, element); - if (added.remove(o) == false) - removed.add(o); + if (added.remove(o) == false) { + removed.add(o); + } - if (removed.remove(element) == false) - added.add(element); + if (removed.remove(element) == false) { + added.add(element); + } - // Apply updates - this.applyUpdates(stateManager, true); + // Apply updates + this.applyUpdates(stateManager, true); return o; - } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), new Object[] {element}); - } + } else { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.classcastexception", elementType.getName()), + new ClassCastException(), new Object[] {element}); + } } @@ -376,11 +361,12 @@ public synchronized Object set(int index, Object element) { * @return true (as per the general contract of Collection.add). * @see java.util.Vector */ + @Override public synchronized boolean add(Object o) { if (allowNulls == false && o == null) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + "sco.nulls_not_allowed")); } if (elementType == null || elementType.isAssignableFrom(o.getClass())) @@ -388,8 +374,9 @@ public synchronized boolean add(Object o) { // Mark the field as dirty StateManager stateManager = this.makeDirty(); - if (removed.remove(o) == false) - added.add(o); + if (removed.remove(o) == false) { + added.add(o); + } boolean modified = super.add(o); @@ -400,7 +387,7 @@ public synchronized boolean add(Object o) { } else { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N + "sco.classcastexception", elementType.getName()), new ClassCastException(), new Object[] {o}); } @@ -414,6 +401,7 @@ public synchronized boolean add(Object o) { * @return true if the Vector contained the specified element. * @see java.util.Vector */ + @Override public boolean remove(Object o) { return this.removeElement(o); } @@ -427,6 +415,7 @@ public boolean remove(Object o) { * (index < 0 || index > size()). * @see java.util.Vector */ + @Override public void add(int index, Object element) { this.insertElementAt(element, index); } @@ -441,6 +430,7 @@ public void add(int index, Object element) { * < 0 || index >= size()). * @see java.util.Vector */ + @Override public synchronized Object remove(int index) { throwUnsupportedOption(); @@ -450,8 +440,9 @@ public synchronized Object remove(int index) { Object obj = super.remove(index); - if (added.remove(obj) == false) - removed.add(obj); + if (added.remove(obj) == false) { + removed.add(obj); + } // Apply updates this.applyUpdates(stateManager, true); @@ -465,6 +456,7 @@ public synchronized Object remove(int index) { * * @see java.util.Vector */ + @Override public void clear() { this.removeAllElements(); } @@ -477,29 +469,31 @@ public void clear() { * @param c elements to be inserted into this Vector. * @see java.util.Vector */ - public synchronized boolean addAll(Collection c) { + @Override + public synchronized boolean addAll(Collection c) { if (allowNulls == false && c.contains(null)) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + "sco.nulls_not_allowed")); } - java.util.Vector errc = new java.util.Vector(); + java.util.Vector errc = new java.util.Vector<>(); if (elementType != null) { // iterate the collection and make a list of wrong elements. - Iterator i = c.iterator(); + Iterator i = c.iterator(); while (i.hasNext()) { Object o = i.next(); - if (!elementType.isAssignableFrom(o.getClass())) + if (!elementType.isAssignableFrom(o.getClass())) { errc.add(o); + } } } if (errc != null && errc.size() > 0) { throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N + "sco.classcastexception", elementType.getName()), new ClassCastException(), errc.toArray()); } @@ -524,18 +518,20 @@ public synchronized boolean addAll(Collection c) { * @return true if this Vector changed as a result of the call. * @see java.util.Vector */ - public synchronized boolean removeAll(Collection c) { + @Override + public synchronized boolean removeAll(Collection c) { boolean modified = false; // Mark the field as dirty StateManager stateManager = this.makeDirty(); - Iterator e = c.iterator(); + Iterator e = c.iterator(); while (e.hasNext()) { Object o = e.next(); if(super.contains(o)) { removeInternal(o); - if (added.remove(o) == false) - removed.add(o); + if (added.remove(o) == false) { + removed.add(o); + } modified = true; } } @@ -561,42 +557,38 @@ public synchronized boolean removeAll(Collection c) { * < 0 || index > size()). * @see java.util.Vector */ - public synchronized boolean addAll(int index, Collection c) { - if (allowNulls == false && c.contains(null)) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.nulls_not_allowed")); // NOI18N + @Override + public synchronized boolean addAll(int index, Collection c) { + if (allowNulls == false && c.contains(null)) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.nulls_not_allowed")); } - java.util.Vector errc = new java.util.Vector(); - if (elementType != null) - { - // iterate the collection and make a list of wrong elements. - Iterator i = c.iterator(); - while (i.hasNext()) - { - Object o = i.next(); - if (!elementType.isAssignableFrom(o.getClass())) - errc.add(o); + java.util.Vector errc = new java.util.Vector<>(); + if (elementType != null) { + // iterate the collection and make a list of wrong elements. + Iterator i = c.iterator(); + while (i.hasNext()) { + Object o = i.next(); + if (!elementType.isAssignableFrom(o.getClass())) { + errc.add(o); } + } } - if (errc != null && errc.size() > 0) - { - throw new JDOUserException(I18NHelper.getMessage(messages, - "sco.classcastexception", elementType.getName()), // NOI18N - new ClassCastException(), errc.toArray()); + if (errc != null && errc.size() > 0) { + throw new JDOUserException(I18NHelper.getMessage(messages, "sco.classcastexception", elementType.getName()), + new ClassCastException(), errc.toArray()); } - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); removed.removeAll(c); added.addAll(c); boolean modified = super.addAll(index, c); - // Apply updates - this.applyUpdates(stateManager, modified); + // Apply updates + this.applyUpdates(stateManager, modified); return modified; } @@ -608,35 +600,33 @@ public synchronized boolean addAll(int index, Collection c) { * @return true if this Vector changed as a result of the call. * @see java.util.Vector */ - public synchronized boolean retainAll(Collection c) { - boolean modified = false; - java.util.Vector v = new java.util.Vector(); - - // Mark the field as dirty - StateManager stateManager = this.makeDirty(); + @Override + public synchronized boolean retainAll(Collection c) { + boolean modified = false; + java.util.Vector v = new java.util.Vector<>(); - for (Iterator iter = super.iterator(); iter.hasNext();) - { - Object o = iter.next(); - if (!c.contains(o)) - { - v.add(o); - if (added.remove(o) == false) - removed.add(o); + // Mark the field as dirty + StateManager stateManager = this.makeDirty(); - modified = true; + for (Iterator iter = super.iterator(); iter.hasNext();) { + Object o = iter.next(); + if (!c.contains(o)) { + v.add(o); + if (added.remove(o) == false) { + removed.add(o); } + + modified = true; + } } // Now remove the rest (stored in "v") - for (Iterator iter = v.iterator(); iter.hasNext();) - { - removeInternal(iter.next()); + for (Iterator iter = v.iterator(); iter.hasNext();) { + removeInternal(iter.next()); } - // Apply updates - this.applyUpdates(stateManager, modified); - + // Apply updates + this.applyUpdates(stateManager, modified); return modified; } @@ -649,6 +639,7 @@ public synchronized boolean retainAll(Collection c) { * objects. In contrast to Object.clone(), this method must not throw a * CloneNotSupportedException. */ + @Override public Object clone() { Vector obj = (Vector)super.clone(); @@ -661,6 +652,7 @@ public Object clone() * Creates and returns a copy of this object without resetting the owner and field value. * */ + @Override public Object cloneInternal() { return super.clone(); @@ -669,6 +661,7 @@ public Object cloneInternal() /** * Cleans removed and added lists */ + @Override public void reset() { added.clear(); @@ -676,16 +669,19 @@ public void reset() } + @Override public void markDeferred() { } + @Override public boolean isDeferred() { return false; } - public void applyDeferredUpdates(Collection c) + @Override + public void applyDeferredUpdates(Collection c) { super.addAll(c); } @@ -693,6 +689,7 @@ public void applyDeferredUpdates(Collection c) /** * Adds an object to the list without recording changes */ + @Override public void addInternal(Object o) { super.addElement(o); @@ -702,7 +699,8 @@ public void addInternal(Object o) /** * Adds a Collection to the list without recording changes */ - public void addAllInternal(Collection c) + @Override + public void addAllInternal(Collection c) { super.addAll(c); } @@ -710,6 +708,7 @@ public void addAllInternal(Collection c) /** * @inheritDoc */ + @Override public void addToBaseCollection(Object o) { super.add(o); @@ -718,7 +717,8 @@ public void addToBaseCollection(Object o) /** * Removes from this collection without recording changes */ - public void removeAllInternal(Collection c) + @Override + public void removeAllInternal(Collection c) { super.removeAll(c); } @@ -728,9 +728,10 @@ public void removeAllInternal(Collection c) * * @return added collection of added elements */ - public Collection getAdded() + @Override + public Collection getAdded() { - return (Collection)added; + return added; } /** @@ -738,14 +739,16 @@ public Collection getAdded() * * @return removed collection of removed elements */ - public Collection getRemoved() + @Override + public Collection getRemoved() { - return (Collection)removed; + return removed; } /** * Clears Collection without notifing the owner */ + @Override public void clearInternal() { //Cannot call super.clear() as it internally calls removeAllElements() @@ -766,6 +769,7 @@ public void clearInternal() /** * Removes an element without notifing the owner */ + @Override public void removeInternal(Object o) { int i = super.indexOf(o); @@ -775,6 +779,7 @@ public void removeInternal(Object o) /** * Nullifies references to the owner Object and Field */ + @Override public void unsetOwner() { this.owner = null; @@ -789,6 +794,7 @@ public void unsetOwner() * * @return owner object */ + @Override public Object getOwner() { return this.owner; @@ -799,6 +805,7 @@ public Object getOwner() * * @return field name as java.lang.String */ + @Override public String getFieldName() { return this.fieldName; @@ -807,6 +814,7 @@ public String getFieldName() /** * Marks object dirty */ + @Override public StateManager makeDirty() { if (owner != null) @@ -824,6 +832,7 @@ public StateManager makeDirty() /** * Apply changes (can be a no-op) */ + @Override public void applyUpdates(StateManager sm, boolean modified) { @@ -852,11 +861,12 @@ private void throwUnsupportedOption() * @param elementType the new element type as Class, or null if type * is not to be checked. */ - public void setOwner(Object owner, String fieldName, Class elementType) { + @Override + public void setOwner(Object owner, String fieldName, Class elementType) { if (this.owner != null) { throw new JDOUserException(I18NHelper.getMessage( - messages1, "core.statemanager.anotherowner"), // NOI18N + messages1, "core.statemanager.anotherowner"), new Object[]{this.owner, this.fieldName}); } if (owner instanceof PersistenceCapable) { diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDesc.java index 35c91226bd6..2ca44ccd452 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDesc.java @@ -25,7 +25,6 @@ package com.sun.jdo.spi.persistence.support.sqlstore.sql; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceCapable; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.SCOCollection; @@ -38,13 +37,13 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.ColumnRef; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; import com.sun.jdo.spi.persistence.utility.StringHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Reader; +import java.lang.System.Logger; import java.lang.reflect.Field; import java.sql.ResultSet; import java.sql.SQLException; @@ -61,19 +60,22 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; + /** * This class is used by the store to materialize objects from a * JDBC resultset. Each ResultDesc binds values from the ResultSet * to instances of a persistence capable class. */ -public class ResultDesc { +public class ResultDesc implements ResultDescItem { /** List of ResultFieldDesc/ResultDesc. */ - private List fields; + private List fields; /** List of field names corresponding to fields. */ - private List fieldNames; + private List fieldNames; /** Class descriptor. */ private ClassDesc config; @@ -86,7 +88,7 @@ public class ResultDesc { * prefetched collection relationship fields. The ResultDesc is the * associated result descriptor. */ - private Map prefetchedCollectionFields; + private Map prefetchedCollectionFields; /** The field that is the recipient of the value from this ResultDesc. */ private ForeignFieldDesc parentField; @@ -97,19 +99,16 @@ public class ResultDesc { /** Result type for aggregate queries. */ private int aggregateResultType = FieldTypeEnumeration.NOT_ENUMERATED; - /** The logger. */ - private static Logger logger = LogHelperSQLStore.getLogger(); - /** I18N message handler. */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", ResultDesc.class.getClassLoader()); - private boolean debug; + private static final Logger LOG = System.getLogger(ResultDesc.class.getName(), messages); public ResultDesc(ClassDesc config, int aggregateResultType) { - fields = new ArrayList(); - fieldNames = new ArrayList(); + fields = new ArrayList<>(); + fieldNames = new ArrayList<>(); this.config = config; this.aggregateResultType = aggregateResultType; } @@ -188,11 +187,10 @@ private static Object getConvertedObject(ResultSet resultData, // Get the generic object and let FieldDesc::convertValue() deal with it. // This will return an SCO as needed. retVal = fieldDesc.convertValue(resultData.getObject(columnRef.getIndex()), sm); - } - catch (Exception e) { - //Resolve : The original code was returning null and not throwing any + } catch (Exception e) { + // Resolve : The original code was returning null and not throwing any //exception in this case. Should we also do that???? - logger.log(Logger.WARNING,"sqlstore.exception.log",e); + LOG.log(WARNING, "convertValue failed.", e); } } @@ -254,50 +252,58 @@ private static Object getValueFromResultSet(ResultSet resultData, case FieldTypeEnumeration.BOOLEAN_PRIMITIVE : case FieldTypeEnumeration.BOOLEAN : boolean booleanValue = resultData.getBoolean(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Boolean(booleanValue); + } break; case FieldTypeEnumeration.CHARACTER_PRIMITIVE : case FieldTypeEnumeration.CHARACTER : String strValue = resultData.getString(index); - if(strValue != null) + if(strValue != null) { retVal = FieldDesc.getCharFromString(strValue); + } break; case FieldTypeEnumeration.BYTE_PRIMITIVE : case FieldTypeEnumeration.BYTE : byte byteValue = resultData.getByte(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Byte(byteValue); + } break; case FieldTypeEnumeration.SHORT_PRIMITIVE : case FieldTypeEnumeration.SHORT : short shortValue = resultData.getShort(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Short(shortValue); + } break; case FieldTypeEnumeration.INTEGER_PRIMITIVE : case FieldTypeEnumeration.INTEGER : int intValue = resultData.getInt(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Integer(intValue); + } break; case FieldTypeEnumeration.LONG_PRIMITIVE : case FieldTypeEnumeration.LONG : long longValue = resultData.getLong(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Long(longValue); + } break; case FieldTypeEnumeration.FLOAT_PRIMITIVE : case FieldTypeEnumeration.FLOAT : float floatValue = resultData.getFloat(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Float(floatValue); + } break; case FieldTypeEnumeration.DOUBLE_PRIMITIVE : case FieldTypeEnumeration.DOUBLE : double doubleValue = resultData.getDouble(index); - if(!resultData.wasNull() ) + if(!resultData.wasNull() ) { retVal = new Double(doubleValue); + } break; case FieldTypeEnumeration.BIGDECIMAL : case FieldTypeEnumeration.BIGINTEGER : @@ -353,11 +359,9 @@ private static Object getValueFromResultSet(ResultSet resultData, "sqlstore.resultdesc.unknownfieldtype",resultType) ); } //switch } catch (SQLException e) { - if(logger.isLoggable(Logger.WARNING) ) { - Object items[] = - { new Integer(index), new Integer(resultType), new Integer(columnType), e}; - logger.log(Logger.WARNING,"sqlstore.resultdesc.errorgettingvalefromresulset",items); - } + LOG.log(WARNING, + "Error while getting value from resultset at index {0} as resultType {1}. columnSqlType {2}. Exception: {3}", + index, resultType, columnType); throw e; } @@ -432,7 +436,7 @@ private static byte[] readInputStreamToByteArray(InputStream is) { // log the exception and don't return any value // Eating the exception here. As the caller also does not // know how to deal with this exception. - logger.log(Logger.WARNING,"sqlstore.exception.log",e); + LOG.log(WARNING,"Reading from an input stream failed.",e); } } return byteArray; @@ -456,10 +460,10 @@ private static String readCharacterStreamToString(Reader reader) { buff.append( (char)charRead ); } } catch (IOException e) { - // log the exception and don't return any value - // Eating the exception here. As the caller also does not - // know how to deal with this exception. - logger.log(Logger.WARNING,"sqlstore.exception.log",e); + // log the exception and don't return any value + // Eating the exception here. As the caller also does not + // know how to deal with this exception. + LOG.log(WARNING,"Reading from the reader failed.",e); } retVal = buff.toString(); } @@ -478,10 +482,8 @@ private static String readCharacterStreamToString(Reader reader) { public Object getResult(PersistenceManager pm, ResultSet resultData) throws SQLException { Object result = null; - debug = logger.isLoggable(Logger.FINEST); - if (!isAggregate()) { - Collection resultCollection = new ArrayList(); + Collection resultCollection = new ArrayList<>(); // Fill in the data from the current row of resultData. while (resultData.next()) { @@ -496,7 +498,7 @@ public Object getResult(PersistenceManager pm, ResultSet resultData) throws SQLE // is enabled. Do not add duplicates. Duplicates are required // for projection queries if (!prefetching || !resultCollection.contains(resultObject)) { - resultCollection.add(resultObject); + resultCollection.add((PersistenceCapable) resultObject); } } @@ -515,11 +517,11 @@ public Object getResult(PersistenceManager pm, ResultSet resultData) throws SQLE * Iterate the result collection applying updates to deferred collections. * @param resultCollection Result collection. */ - private void applyDeferredUpdatesToPrefetchedCollections(Collection resultCollection) { + private void applyDeferredUpdatesToPrefetchedCollections(Collection resultCollection) { if (prefetching && prefetchedCollectionFields != null && prefetchedCollectionFields.size() > 0) { - for (Iterator resultItr = resultCollection.iterator(); resultItr.hasNext(); ) { + for (Iterator resultItr = resultCollection.iterator(); resultItr.hasNext(); ) { // each result object is guaranteed to be instance of PersistenceCapable - PersistenceCapable pc = (PersistenceCapable) resultItr.next(); + PersistenceCapable pc = resultItr.next(); // pc can be null if this is a projection query if (pc != null) { @@ -536,25 +538,23 @@ private void applyDeferredUpdatesToPrefetchedCollections(Collection resultCollec private void applyDeferredUpdatesToPrefetchedCollections(PersistenceCapable pc) { if (prefetchedCollectionFields != null) { StateManager sm = pc.jdoGetStateManager(); - Iterator prefetchedCollectionFieldsIter = prefetchedCollectionFields.keySet().iterator(); + Iterator prefetchedCollectionFieldsIter = prefetchedCollectionFields.keySet().iterator(); while (prefetchedCollectionFieldsIter.hasNext()) { - ForeignFieldDesc prefetchedCollectionField = - (ForeignFieldDesc) prefetchedCollectionFieldsIter.next(); - ResultDesc prefetchedResultDesc = - (ResultDesc) prefetchedCollectionFields.get(prefetchedCollectionField); + ForeignFieldDesc prefetchedCollectionField = prefetchedCollectionFieldsIter.next(); + ResultDesc prefetchedResultDesc = prefetchedCollectionFields.get(prefetchedCollectionField); // process deferred updates for prefetched collection relationships if (prefetchedCollectionField.cardinalityUPB > 1) { - Collection relationshipValue = - (Collection) prefetchedCollectionField.getValue(sm); + Collection relationshipValue = (Collection) prefetchedCollectionField.getValue(sm); - if (relationshipValue instanceof SCOCollection && ((SCOCollection) relationshipValue).isDeferred()){ + if (relationshipValue instanceof SCOCollection + && ((SCOCollection) relationshipValue).isDeferred()) { ((SCOCollection) relationshipValue).applyDeferredUpdates(null); } // recursion into the next level - for (Iterator iter = relationshipValue.iterator(); iter.hasNext(); ) { + for (Iterator iter = relationshipValue.iterator(); iter.hasNext();) { PersistenceCapable persistenceCapable = (PersistenceCapable) iter.next(); prefetchedResultDesc.applyDeferredUpdatesToPrefetchedCollections(persistenceCapable); } @@ -597,9 +597,7 @@ private Object getProjectedField(ResultSet resultData) { //Field projection can never be null if this method gets called. FieldDesc f = fieldProjection.getFieldDesc(); - if (debug) { - logger.finest("sqlstore.resultdesc.returning_field", f.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.resultdesc.returning_field", f.getName()); return getConvertedObject(resultData, fieldProjection.getColumnRef(), f, null); } @@ -636,9 +634,7 @@ private Object setFields(PersistenceManager pm, ResultSet resultData) { if (!sm.getPresenceMaskBit(f.absoluteID)) { Object value = getConvertedObject(resultData, rfd.getColumnRef(), f, sm); - if (debug) { - logger.finest("sqlstore.resultdesc.marking_field", f.getName()); // NOI18N - } + LOG.log(TRACE, "sqlstore.resultdesc.marking_field", f.getName()); // Set the field value and presence mask bit. setFieldValue(sm, f, value); @@ -662,10 +658,7 @@ private Object setFields(PersistenceManager pm, ResultSet resultData) { setFieldValue(sm, parentField, fobj); } } - if (debug) { - logger.finest("sqlstore.resultdesc.marking_foreign_field", // NOI18N - parentField.getName()); - } + LOG.log(TRACE, "sqlstore.resultdesc.marking_foreign_field", parentField.getName()); } } @@ -692,12 +685,12 @@ private Object setFields(PersistenceManager pm, ResultSet resultData) { * @param value Given value. */ private static void addCollectionValue(SQLStateManager sm, ForeignFieldDesc f, Object value) { - Collection collection = (Collection) f.getValue(sm); + Collection collection = (Collection) f.getValue(sm); if (collection == null) { // Initialize the collection. sm.replaceCollection(f, null); // Get the newly created SCOCollection back. - collection = (Collection) f.getValue(sm); + collection = (Collection) f.getValue(sm); } // Set the presence mask if necessary. @@ -744,8 +737,8 @@ private boolean isAggregate() { private StateManager findOrCreateStateManager(ResultSet resultData, PersistenceManager pm) { try { - Class oidClass = config.getOidClass(); - Object oid = oidClass.newInstance(); + Class oidClass = config.getOidClass(); + Object oid = oidClass.getDeclaredConstructor().newInstance(); // Copy key field values Field keyFields[] = config.getKeyFields(); @@ -756,13 +749,11 @@ private StateManager findOrCreateStateManager(ResultSet resultData, FieldDesc fd = config.getField(keyName); int index = fieldNames.indexOf(keyName); - ResultFieldDesc rfd = (ResultFieldDesc)fields.get(index); + ResultFieldDesc rfd = (ResultFieldDesc) fields.get(index); Object v = getConvertedObject(resultData, rfd.getColumnRef(), fd, null); - if (debug) { - logger.finest("sqlstore.resultdesc.marking_key_field",keyName); // NOI18N - } + LOG.log(TRACE, "sqlstore.resultdesc.marking_key_field",keyName); if (v == null ) { return null; @@ -790,7 +781,7 @@ public void doJoin(ResultDesc foreignResult, ForeignFieldDesc parentField) { // prefetched, remember it. if(parentField.cardinalityUPB > 1) { if (prefetchedCollectionFields == null) { - prefetchedCollectionFields = new HashMap(); + prefetchedCollectionFields = new HashMap<>(); } prefetchedCollectionFields.put(parentField, foreignResult); } diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaHome.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDescItem.java similarity index 60% rename from appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaHome.java rename to appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDescItem.java index c993090009e..68823dfe0f9 100644 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaHome.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultDescItem.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at @@ -14,22 +14,9 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * RpaHome.java - * - * Created on May 15, 2003, 5:21 PM - */ +package com.sun.jdo.spi.persistence.support.sqlstore.sql; -package shopping; -import jakarta.ejb.EJBHome; -import shopping.RpaRemote; -/** - * - * @author Harpreet Singh - */ -public interface RpaHome extends EJBHome{ - public RpaRemote create(java.lang.String shopperName) - throws java.rmi.RemoteException, jakarta.ejb.CreateException; +interface ResultDescItem { } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultFieldDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultFieldDesc.java index 2ce8f50c6ce..91b4c881f95 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultFieldDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/ResultFieldDesc.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 */ -/* - * ResultFieldDesc.java - * - * Created on October 15, 2001 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql; import com.sun.jdo.spi.persistence.support.sqlstore.model.LocalFieldDesc; @@ -30,7 +24,7 @@ * This class is used to associated a field to the position of a column * in a JDBC resultset. */ -public class ResultFieldDesc extends Object { +public class ResultFieldDesc implements ResultDescItem { /** * field descriptor for the field that is the recipient of the column value * from the resultset diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/RetrieveDescImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/RetrieveDescImpl.java index 29f8be2e4b1..5e84e946494 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/RetrieveDescImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/RetrieveDescImpl.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 */ -/* - * RetrieveDescImpl.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -33,11 +27,13 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.Constraint; import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintFieldName; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.SelectQueryPlan; +import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.Statement; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; import com.sun.jdo.spi.persistence.utility.ParameterInfo; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; @@ -117,7 +113,7 @@ public class RetrieveDescImpl extends Object implements RetrieveDesc, Cloneable public static final int OPT_VERIFY = 0x1000; // 4024 /** Array of ConstraintFieldName. */ - private ArrayList fields; + private List fields; /** The constraint stack */ private Constraint constraint; @@ -126,7 +122,7 @@ public class RetrieveDescImpl extends Object implements RetrieveDesc, Cloneable private int options; /** Candidate class of this instance */ - private Class pcClass; + private Class pcClass; /** Config for candidate class of this instance */ private ClassDesc config; @@ -147,15 +143,13 @@ public class RetrieveDescImpl extends Object implements RetrieveDesc, Cloneable * I18N message handler */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", RetrieveDescImpl.class.getClassLoader()); - public RetrieveDescImpl(Class pcClass, ClassDesc config) { - super(); - + public RetrieveDescImpl(Class pcClass, ClassDesc config) { this.pcClass = pcClass; this.config = config; - fields = new ArrayList(); + fields = new ArrayList<>(); constraint = new Constraint(); } @@ -173,6 +167,7 @@ public RetrieveDescImpl(Class pcClass, ClassDesc config) { * RetrieveDesc describing fields and constraints for a referenced object. * @param projection Specifies, if this is a projection. */ + @Override public void addResult(String name, RetrieveDesc foreignConstraint, boolean projection) { @@ -181,7 +176,7 @@ public void addResult(String name, if (projection) { if ((options & OPT_PROJECTION) > 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.retrievedesc.toomanyprojections")); // NOI18N + "sqlstore.retrievedesc.toomanyprojections")); } // For projections on foreign fields, mark the foreign constraint. @@ -218,6 +213,7 @@ public void addResult(String name, * @param aggregateResultType The object type returned by aggregate queries. * @see com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration */ + @Override public void addResult(int opCode, int aggregateResultType) { switch (opCode) { case ActionDesc.OP_DISTINCT: @@ -243,7 +239,7 @@ public void addResult(int opCode, int aggregateResultType) { break; default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", "" + opCode)); // NOI18N + "core.constraint.illegalop", "" + opCode)); } if (aggregateResultType != FieldTypeEnumeration.NOT_ENUMERATED) { @@ -252,7 +248,7 @@ public void addResult(int opCode, int aggregateResultType) { } else { // aggregate result type has already been set throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.retrievedesc.toomanyresulttypes")); // NOI18N + "sqlstore.retrievedesc.toomanyresulttypes")); } } } @@ -271,6 +267,7 @@ public void addPrefetchedField(String name, RetrieveDesc foreignConstraint) { /** * {@inheritDoc} */ + @Override public void setPrefetchEnabled(boolean prefetchEnabled) { if (!prefetchEnabled) { options |= OPT_DISABLE_RELATIONSHIP_PREFETCH; @@ -289,6 +286,7 @@ public void setPrefetchEnabled(boolean prefetchEnabled) { * nor a local field connecting to the retrieve descriptor * foreignConstraint. */ + @Override public void addConstraint(String name, RetrieveDesc foreignConstraint) { if (name == null) { @@ -305,6 +303,7 @@ public void addConstraint(String name, * emp.addConstraint("lastName", ActionDesc.OP_EQ, mgr, lastName"); * compares the employee's lastName field with the lastName field of the related manager. */ + @Override public void addConstraint(String name, int operation, RetrieveDesc foreignConstraint, String foreignName) { constraint.addField(foreignName, foreignConstraint); @@ -332,6 +331,7 @@ public void addConstraint(String name, int operation, * field should be limited, however it is sometimes used to * hold a parameter count as for the OP_IN operation. */ + @Override public void addConstraint(String name, int operation, Object value) { @@ -339,19 +339,19 @@ public void addConstraint(String name, if ((info & OPINFO_ILLEGAL) > 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", "" + operation)); // NOI18N + "core.constraint.illegalop", "" + operation)); } else if ((info & OPINFO_FIELD_REQUIRED) > 0 && name == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.fieldrequired", "" + operation)); // NOI18N + "core.constraint.fieldrequired", "" + operation)); } else if ((info & OPINFO_FIELD_DISALLOWED) > 0 && name != null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.fielddisallowed", "" + operation)); // NOI18N + "core.constraint.fielddisallowed", "" + operation)); } else if ((info & OPINFO_VAL_REQUIRED) > 0 && value == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.valrequired", "" + operation)); // NOI18N + "core.constraint.valrequired", "" + operation)); } else if ((info & OPINFO_VAL_DISALLOWED) > 0 && value != null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.valdisallowed", "" + operation)); // NOI18N + "core.constraint.valdisallowed", "" + operation)); } if ((info & OPINFO_VAL_IS_PCOUNT) > 0) { if (name != null) { @@ -360,7 +360,7 @@ public void addConstraint(String name, addValueConstraint(name, value); } else { switch (operation) { - case RetrieveDescImpl.OP_PARAMETER: + case ActionDesc.OP_PARAMETER: addParameterConstraint(value); break; case ActionDesc.OP_IN: @@ -443,7 +443,7 @@ private void addParameterConstraint(Object value) { getLocalFieldDesc(parameterInfo.getAssociatedField())); } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalParameterInfo")); // NOI18N + "core.constraint.illegalParameterInfo")); } } @@ -629,12 +629,12 @@ public synchronized SelectQueryPlan buildQueryPlan(SQLStoreManager store, plan.build(); // Generate the text for the select statements. - ArrayList statements = plan.getStatements(); + List statements = plan.getStatements(); // Sanity check. if (statements.size() > 1) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.retrievedesc.stmntsnotjoined")); // NOI18N + "sqlstore.retrievedesc.stmntsnotjoined")); } } return plan; @@ -703,7 +703,7 @@ private RetrieveDescImpl distributeQueryOptions(int queryOptions, // Loop through all dependent retrieve descriptors in the field list. for (int i = 0; i < fields.size(); i++) { - ConstraintFieldName cfn = (ConstraintFieldName) fields.get(i); + ConstraintFieldName cfn = fields.get(i); if (cfn.isProjection()) { // This is a local field projection. @@ -756,6 +756,7 @@ private void setFetchGroupOptions(int queryOptions) { * @param navigationalId Tag to discriminate different retrieve * descriptors that use the same navigational field. */ + @Override public void setNavigationalId(Object navigationalId) { this.navigationalId = navigationalId; } @@ -811,7 +812,8 @@ public void setPlan(SelectQueryPlan plan) { this.plan = plan; } - public Class getPersistenceCapableClass() { + @Override + public Class getPersistenceCapableClass() { return pcClass; } @@ -819,14 +821,15 @@ public Constraint getConstraint() { return constraint; } - public Iterator getFields() { + public Iterator getFields() { return fields.iterator(); } + @Override public Object clone() { try { RetrieveDescImpl clone = (RetrieveDescImpl) super.clone(); - clone.fields = new ArrayList(); + clone.fields = new ArrayList<>(); clone.constraint = new Constraint(); return clone; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/UpdateObjectDescImpl.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/UpdateObjectDescImpl.java index a9cfe743303..403e552f1a8 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/UpdateObjectDescImpl.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/UpdateObjectDescImpl.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,18 +15,10 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * UpdateObjectDescImpl.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.spi.persistence.support.sqlstore.ActionDesc; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; import com.sun.jdo.spi.persistence.support.sqlstore.StateManager; import com.sun.jdo.spi.persistence.support.sqlstore.UpdateObjectDesc; @@ -34,8 +27,8 @@ import com.sun.jdo.spi.persistence.support.sqlstore.model.ForeignFieldDesc; import com.sun.jdo.spi.persistence.support.sqlstore.model.LocalFieldDesc; import com.sun.jdo.spi.persistence.support.sqlstore.sql.concurrency.Concurrency; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -46,24 +39,27 @@ import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.TRACE; + /** * Stores the update information for the associated state manager. */ public class UpdateObjectDescImpl implements UpdateObjectDesc { /** Array of Object. */ - private List afterHiddenValues; + private List afterHiddenValues; private SQLStateManager afterImage; /** Array of Object. */ - private List beforeHiddenValues; + private List beforeHiddenValues; private SQLStateManager beforeImage; private Concurrency concurrency; - private Class pcClass; + private Class pcClass; private int updateAction; @@ -71,27 +67,28 @@ public class UpdateObjectDescImpl implements UpdateObjectDesc { * Array of LocalFieldDesc. * Fields contained in this array are written to the database. */ - private List updatedFields; + private List updatedFields; - private Map updatedJoinTableRelationships; + private Map> updatedJoinTableRelationships; /** Marker for fast relationship update check. */ private boolean relationshipChanged = false; - /** The logger. */ - private static Logger logger = LogHelperSQLStore.getLogger(); - /** I18N message handler. */ private final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", UpdateObjectDescImpl.class.getClassLoader()); - public UpdateObjectDescImpl(Class pcClass) { + /** The logger. */ + private static final Logger LOG = System.getLogger(UpdateObjectDescImpl.class.getName(), messages); + + public UpdateObjectDescImpl(Class pcClass) { this.pcClass = pcClass; - updatedFields = new ArrayList(); + updatedFields = new ArrayList<>(); } - public Class getPersistenceCapableClass() { + @Override + public Class getPersistenceCapableClass() { return pcClass; } @@ -110,7 +107,7 @@ public boolean hasUpdatedFields() { return (updatedFields.size() > 0); } - public Collection getUpdatedJoinTableFields() { + public Collection getUpdatedJoinTableFields() { if (updatedJoinTableRelationships == null) { return null; } @@ -119,8 +116,8 @@ public Collection getUpdatedJoinTableFields() { } // RESOLVE: Should return _all_ join table descs, not separatly by field. - public Collection getUpdateJoinTableDescs(FieldDesc fieldDesc) { - HashMap updateJoinTableDescs = (HashMap) updatedJoinTableRelationships.get(fieldDesc); + public Collection getUpdateJoinTableDescs(FieldDesc fieldDesc) { + HashMap updateJoinTableDescs = updatedJoinTableRelationships.get(fieldDesc); if (updateJoinTableDescs != null) { return updateJoinTableDescs.values(); @@ -140,7 +137,7 @@ public boolean hasUpdatedJoinTableRelationships() { public boolean hasModifiedLobField() { if (updatedFields != null) { - for (Iterator i = updatedFields.iterator(); i.hasNext(); ) { + for (Iterator i = updatedFields.iterator(); i.hasNext(); ) { // The list updatedFields only contains LocalFieldDesc. // Thus it's safe to cast to LocalFieldDesc below. @@ -163,9 +160,7 @@ public boolean hasModifiedLobField() { */ public void markRelationshipChange(FieldDesc fieldDesc) { if (fieldDesc.isRelationshipField() || fieldDesc.isForeignKeyField()) { - if (logger.isLoggable(Logger.FINEST)) { - logger.finest("sqlstore.sql.updateobjdescimpl.markrelationshipchange"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sql.updateobjdescimpl.markrelationshipchange"); // MARK THE RELATIONSHIP CHANGE for this instance. relationshipChanged = true; } @@ -190,7 +185,7 @@ public boolean hasChangedRelationships() { // Check for updated foreign key relationships. if (updatedFields != null) { - for (Iterator iter = updatedFields.iterator(); iter.hasNext(); ) { + for (Iterator iter = updatedFields.iterator(); iter.hasNext(); ) { LocalFieldDesc field = (LocalFieldDesc) iter.next(); if (field.isForeignKeyField()) { return true; @@ -216,14 +211,14 @@ public boolean hasChangedRelationships() { public boolean removeUpdatedJoinTableRelationship(ForeignFieldDesc fieldDesc, SQLStateManager foreignSM, int action) { - HashMap updateJoinTableDescs = null; + HashMap updateJoinTableDescs = null; if ((updatedJoinTableRelationships == null) || - ((updateJoinTableDescs = (HashMap) updatedJoinTableRelationships.get(fieldDesc)) == null)) { + ((updateJoinTableDescs = updatedJoinTableRelationships.get(fieldDesc)) == null)) { return false; } - UpdateJoinTableDesc desc = (UpdateJoinTableDesc) updateJoinTableDescs.get(foreignSM); + UpdateJoinTableDesc desc = updateJoinTableDescs.get(foreignSM); if (desc != null && desc.getAction() == action) { return (updateJoinTableDescs.remove(foreignSM) != null); } @@ -249,19 +244,19 @@ public void recordUpdatedJoinTableRelationship(ForeignFieldDesc fieldDesc, SQLStateManager foreignSM, int action) { if (updatedJoinTableRelationships == null) { - updatedJoinTableRelationships = new HashMap(); + updatedJoinTableRelationships = new HashMap<>(); } - HashMap updateJoinTableDescs = null; + HashMap updateJoinTableDescs = null; - if ((updateJoinTableDescs = (HashMap) updatedJoinTableRelationships.get(fieldDesc)) == null) { - updateJoinTableDescs = new HashMap(); + if ((updateJoinTableDescs = updatedJoinTableRelationships.get(fieldDesc)) == null) { + updateJoinTableDescs = new HashMap<>(); updatedJoinTableRelationships.put(fieldDesc, updateJoinTableDescs); } UpdateJoinTableDesc desc = null; - if ((desc = (UpdateJoinTableDesc) updateJoinTableDescs.get(foreignSM)) == null) { + if ((desc = updateJoinTableDescs.get(foreignSM)) == null) { desc = new UpdateJoinTableDesc(parentSM, foreignSM, action); updateJoinTableDescs.put(foreignSM, desc); } @@ -272,11 +267,12 @@ public void clearUpdatedJoinTableRelationships() { } public void recordUpdatedField(LocalFieldDesc fieldDesc) { - if (!updatedFields.contains(fieldDesc)) + if (!updatedFields.contains(fieldDesc)) { updatedFields.add(fieldDesc); + } } - public List getUpdatedFields() { + public List getUpdatedFields() { return updatedFields; } @@ -348,6 +344,7 @@ public void setConcurrency(Concurrency concurrency) { * (except that we won't have an AfterImage for Deletes and we won't have * a BeforeImage for updates). */ + @Override public void setObjectInfo(StateManager biStateManager, StateManager aiStateManager, int action) { @@ -367,10 +364,8 @@ public void setObjectInfo(StateManager biStateManager, // These are attributes that are stored in this object and are not references // to other persistent objects. - boolean debug = logger.isLoggable(Logger.FINER); - for (int i = 0; i < config.fields.size(); i++) { - FieldDesc f = (FieldDesc) config.fields.get(i); + FieldDesc f = config.fields.get(i); LocalFieldDesc lf = null; boolean updated = false; @@ -411,9 +406,7 @@ public void setObjectInfo(StateManager biStateManager, } if (updated) { - if (debug) { - logger.finer("sqlstore.sql.updateobjdescimpl.updated", f.getName()); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sql.updateobjdescimpl.updated", f.getName()); updatedFields.add(lf); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyCheckDirty.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyCheckDirty.java index e1bd29482c7..f94b22d1015 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyCheckDirty.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyCheckDirty.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 */ -/* - * ConcurrencyCheckDirty.java - * - * Created on March 19, 2002 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.concurrency; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; @@ -31,33 +25,35 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.Statement; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateQueryPlan; -import java.util.ArrayList; +import java.lang.System.Logger; import java.util.BitSet; import java.util.Iterator; +import java.util.List; import org.netbeans.modules.dbschema.ColumnElement; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; + /** */ public class ConcurrencyCheckDirty extends ConcurrencyDBNative { - public void commit(UpdateObjectDesc updateDesc, - SQLStateManager beforeImage, - SQLStateManager afterImage, - int logReason) { + private static final Logger LOG = System.getLogger(ConcurrencyCheckDirty.class.getName(), RESOURCE_BUNDLE); + + @Override + public void commit(UpdateObjectDesc updateDesc, SQLStateManager beforeImage, SQLStateManager afterImage, + int logReason) { this.beforeImage = beforeImage; this.afterImage = afterImage; } + @Override public void update(UpdateQueryPlan plan) { - boolean debug = logger.isLoggable(); - - if (debug) { - logger.fine("sqlstore.sql.concurrency.concurrencychkdirty", beforeImage); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sql.concurrency.concurrencychkdirty", beforeImage); if (beforeImage != null) { - ArrayList fields = plan.getConfig().fields; + List fields = plan.getConfig().fields; BitSet verifyGroupMask = prepareVerifyGroupMask(plan); for (int i = 0; i < 2; i++) { @@ -73,7 +69,7 @@ public void update(UpdateQueryPlan plan) { } for (int j = 0; j < fields.size(); j++) { - FieldDesc f = (FieldDesc) fields.get(j); + FieldDesc f = fields.get(j); if (f instanceof LocalFieldDesc) { LocalFieldDesc lf = (LocalFieldDesc) f; @@ -97,18 +93,16 @@ public void update(UpdateQueryPlan plan) { } } - if (debug) { - logger.fine("sqlstore.sql.concurrency.concurrencychkdirty.exit"); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sql.concurrency.concurrencychkdirty.exit"); } protected BitSet prepareVerifyGroupMask(UpdateQueryPlan plan) { return null; } - protected boolean isFieldVerificationRequired(LocalFieldDesc lf, - BitSet verifyGroupMask) { - return true; + + protected boolean isFieldVerificationRequired(LocalFieldDesc lf, BitSet verifyGroupMask) { + return true; } /** @@ -116,14 +110,14 @@ protected boolean isFieldVerificationRequired(LocalFieldDesc lf, * to the corresponding statements in UpdateQueryPlan plan. */ private static void addConstraint(UpdateQueryPlan plan, LocalFieldDesc lf, Object val) { - for (Iterator iter = lf.getColumnElements(); iter.hasNext(); ) { - ColumnElement c = (ColumnElement) iter.next(); + for (Iterator iter = lf.getColumnElements(); iter.hasNext(); ) { + ColumnElement c = iter.next(); for (int i = 0; i < plan.statements.size(); i++) { - Statement s = (Statement) plan.statements.get(i); + Statement s = plan.statements.get(i); for (int j = 0; j < s.tableList.size(); j++) { - QueryTable t = (QueryTable) s.tableList.get(j); + QueryTable t = s.tableList.get(j); if (t.getTableDesc().getTableElement() == c.getDeclaringTable()) { s.addConstraint(lf, val); @@ -133,13 +127,8 @@ private static void addConstraint(UpdateQueryPlan plan, LocalFieldDesc lf, Objec } } + @Override public Object clone() { return new ConcurrencyCheckDirty(); } } - - - - - - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyDBNative.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyDBNative.java index 9846a932952..40d6c3007b4 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyDBNative.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyDBNative.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,14 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * ConcurrencyDBNative.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.concurrency; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStateManager; import com.sun.jdo.spi.persistence.support.sqlstore.Transaction; import com.sun.jdo.spi.persistence.support.sqlstore.UpdateObjectDesc; import com.sun.jdo.spi.persistence.support.sqlstore.model.ClassDesc; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.SelectQueryPlan; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateQueryPlan; -import com.sun.jdo.spi.persistence.utility.logging.Logger; /** */ @@ -40,33 +32,37 @@ public class ConcurrencyDBNative implements Concurrency { SQLStateManager afterImage; - /** The logger */ - protected static final Logger logger = LogHelperSQLStore.getLogger(); - + @Override public void commit(UpdateObjectDesc updateDesc, SQLStateManager beforeImage, SQLStateManager afterImage, int logReason) { } + @Override public void configPersistence(ClassDesc config) { // RESOLVE: Need to check field properties so that we get the before // images at update time. } + @Override public Transaction suspend() { return null; } + @Override public void resume(Transaction t) { } + @Override public void select(SelectQueryPlan plan) { } + @Override public void update(UpdateQueryPlan plan) { } + @Override public Object clone() { return this; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyOptVerify.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyOptVerify.java index ce2f3cf9e84..12e26ddb91e 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyOptVerify.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/concurrency/ConcurrencyOptVerify.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 */ -/* - * ConcurrencyOptVerify.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.concurrency; import com.sun.jdo.spi.persistence.support.sqlstore.model.FieldDesc; @@ -28,8 +22,8 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.QueryPlan; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UpdateQueryPlan; -import java.util.ArrayList; import java.util.BitSet; +import java.util.List; /** */ @@ -39,8 +33,9 @@ public class ConcurrencyOptVerify extends ConcurrencyCheckDirty { * Find all the local fields that have been updated * and use their concurrencyGroup to set the verifyGroupMask. */ + @Override protected BitSet prepareVerifyGroupMask(UpdateQueryPlan plan) { - ArrayList fields; + List fields; BitSet verifyGroupMask = new BitSet(); int action = plan.getAction(); @@ -56,7 +51,7 @@ protected BitSet prepareVerifyGroupMask(UpdateQueryPlan plan) { } for (int j = 0; j < fields.size(); j++) { - FieldDesc f = (FieldDesc) fields.get(j); + FieldDesc f = fields.get(j); if ((f instanceof LocalFieldDesc) && (f.sqlProperties & FieldDesc.PROP_IN_CONCURRENCY_CHECK) > 0) { @@ -78,6 +73,7 @@ protected BitSet prepareVerifyGroupMask(UpdateQueryPlan plan) { return verifyGroupMask; } + @Override protected boolean isFieldVerificationRequired(LocalFieldDesc lf, BitSet verifyGroupMask) { boolean fieldVerificationRequired = true; @@ -95,6 +91,7 @@ protected boolean isFieldVerificationRequired(LocalFieldDesc lf, return fieldVerificationRequired; } + @Override public Object clone() { return new ConcurrencyOptVerify(); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/Constraint.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/Constraint.java index 1c35fe166a4..bfe5bd3f954 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/Constraint.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/Constraint.java @@ -38,14 +38,14 @@ public class Constraint extends Object { * The stack that contains all constraints beside join constraints. * Join constraints are handled by a separate stack. */ - public List stack; + public List stack; /** * The stack that contains outer join constraints. All the elements of this stack * are instance of {@link ConstraintJoin}. Outer join constraints can be appended * to the query w/o changing the semantic. */ - private List outerJoinStack; + private ListouterJoinStack; /** * The stack that contains order by constraints. We would like to @@ -239,7 +239,7 @@ private boolean isEmptyOrOrderBy() { boolean rc = true; // Abort the loop at first possible opportunity. for (int i = stack.size() - 1; i >= 0 && rc; ) { - ConstraintNode node = (ConstraintNode) stack.get(i); + ConstraintNode node = stack.get(i); if ((node instanceof ConstraintOperation) && ((((ConstraintOperation) node).operation == ActionDesc.OP_ORDERBY) || @@ -270,7 +270,7 @@ private boolean isEmptyOrOrderBy() { * Gets the where clause constraints for this Constraint * @return The where clause constraints for this Constraint */ - public List getConstraints() { + public List getConstraints() { return stack; } @@ -278,13 +278,13 @@ public List getConstraints() { * Gets the outer join constraints for this Constraint * @return The outer join constraints for this Constraint */ - public List getOuterJoinConstraints() { + public List getOuterJoinConstraints() { return outerJoinStack; } public Constraint() { - stack = new ArrayList(); - outerJoinStack = new ArrayList(); + stack = new ArrayList<>(); + outerJoinStack = new ArrayList<>(); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintJoin.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintJoin.java index ff49d39aab5..606bdc3116b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintJoin.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintJoin.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,27 +15,20 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * ConstraintJoin.java - * - * Create on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint; import com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.QueryPlan; -import java.util.ArrayList; +import java.util.List; + +import org.netbeans.modules.dbschema.ColumnElement; -/** - */ public class ConstraintJoin extends ConstraintOperation { - public ArrayList fromColumns; + public List fromColumns; public QueryPlan fromPlan; - public ArrayList toColumns; + public List toColumns; public QueryPlan toPlan; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintValue.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintValue.java index 70d96178e5e..377c4021581 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintValue.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/constraint/ConstraintValue.java @@ -33,7 +33,7 @@ public class ConstraintValue extends ConstraintNode { /** The local field to which this value constraint is bound. Please note * that we have this information only for constraints that corresponds to simple - * expressions ( like ) in query filter. + * expressions ( like {@code )} in query filter. * Do not rely on this information to be always present for any optimizations. */ private LocalFieldDesc localField; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/ColumnRef.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/ColumnRef.java index 0218ec162eb..ac623a54a3b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/ColumnRef.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/ColumnRef.java @@ -57,15 +57,14 @@ public class ColumnRef extends Object implements FieldMapping { // private String name; - public ColumnRef(ColumnElement columnElement, - QueryTable table) { + public ColumnRef(ColumnElement columnElement, QueryTable table) { this.columnElement = columnElement; name = columnElement.getName().getName(); this.table = table; } - public ColumnRef(ColumnElement columnElement, - Object value) { + + public ColumnRef(ColumnElement columnElement, Object value) { this.columnElement = columnElement; name = columnElement.getName().getName(); this.value = value; @@ -117,21 +116,24 @@ public String getName() { /** * This method return int corresponding to java.sql.Types. */ - public int getColumnType() { + @Override + public int getColumnType() { return columnElement.getType(); } /** * This method return the name of the column. */ - public String getColumnName() { + @Override + public String getColumnName() { return name; } /** * This method return the length of the column and -1 if unknown. */ - public int getColumnLength() { + @Override + public int getColumnLength() { Integer len = columnElement.getLength(); return (len != null) ? len.intValue(): -1; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedExistSelectPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedExistSelectPlan.java index 295dc234c40..acefcb30e14 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedExistSelectPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedExistSelectPlan.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 @@ -24,6 +25,7 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintFieldDesc; import java.util.ArrayList; +import java.util.List; /** * Implements the select plan for Exist-Subqueries. @@ -46,9 +48,10 @@ public CorrelatedExistSelectPlan(RetrieveDesc desc, * This method just adds the table for the nested select. * The statement for nested select is created as a side effect. */ + @Override protected void processFields() { for (int i = 0; i < parentField.foreignFields.size(); i++) { - LocalFieldDesc field = (LocalFieldDesc) parentField.foreignFields.get(i); + LocalFieldDesc field = parentField.foreignFields.get(i); addTable(field); } } @@ -57,9 +60,9 @@ protected void processFields() { * The correlated constraint joining this subquery with the parent field. * The joined table is added as a side-effect. */ + @Override protected void doCorrelatedJoin() { - ArrayList foreignFields = null; - + List foreignFields; if (parentField.useJoinTable()) { foreignFields = parentField.assocLocalFields; // The join table is included in #processJoinTable @@ -67,11 +70,11 @@ protected void doCorrelatedJoin() { foreignFields = parentField.foreignFields; } - ArrayList localFields = parentField.localFields; + ArrayList localFields = parentField.localFields; // Add the constraint linking the parent query with the subquery. for (int i = 0; i < localFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) localFields.get(i); - LocalFieldDesc fa = (LocalFieldDesc) foreignFields.get(i); + LocalFieldDesc la = localFields.get(i); + LocalFieldDesc fa = foreignFields.get(i); ConstraintFieldDesc lcfd = new ConstraintFieldDesc(la, parentPlan); ConstraintFieldDesc fcfd = new ConstraintFieldDesc(fa, this); @@ -83,6 +86,7 @@ protected void doCorrelatedJoin() { } } + @Override protected Statement newStatement() { return new SelectOneStatement(store.getVendorType(), this); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedInSelectPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedInSelectPlan.java index 3a6446c3ce4..8cdfe4820a5 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedInSelectPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedInSelectPlan.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 @@ -43,9 +44,9 @@ public CorrelatedInSelectPlan(RetrieveDesc desc, * Add the fields joining the subquery to the list of selected fields. * The joined table is added as a side-effect. */ + @Override protected void processFields() { - List subqueryFieldsToSelect; - + List subqueryFieldsToSelect; if (parentField.useJoinTable()) { subqueryFieldsToSelect = parentField.getAssocLocalFields(); } else { @@ -54,7 +55,7 @@ protected void processFields() { // Add the columns and tables to be selected in the subquery for (int i = 0; i < subqueryFieldsToSelect.size(); i++) { - addColumn((LocalFieldDesc) subqueryFieldsToSelect.get(i)); + addColumn(subqueryFieldsToSelect.get(i)); } } @@ -62,6 +63,7 @@ protected void processFields() { * No-Op. No join condition is added for correlated in selects, * as the queries are joined on the selected fields. */ + @Override protected void doCorrelatedJoin() {} } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedSelectPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedSelectPlan.java index f12c28f0675..99020c050c4 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedSelectPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/CorrelatedSelectPlan.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 @@ -22,7 +23,7 @@ import com.sun.jdo.spi.persistence.support.sqlstore.model.ClassDesc; import com.sun.jdo.spi.persistence.support.sqlstore.model.ForeignFieldDesc; -import java.util.ArrayList; +import java.util.List; import org.netbeans.modules.dbschema.ColumnElement; @@ -54,6 +55,7 @@ public CorrelatedSelectPlan(RetrieveDesc desc, *
  • A join constraint if the parent field uses join table
  • * */ + @Override protected void processConstraints() { // Process the constraint on the stack.` @@ -95,9 +97,8 @@ private void processJoinTable() { * @param columnList List of columns. * @param config Class configuration corresponding to columns. */ - protected void addQueryTables(ArrayList columnList, ClassDesc config) { - for (int i = 0; i < columnList.size(); i++) { - ColumnElement col = (ColumnElement) columnList.get(i); + protected void addQueryTables(List columnList, ClassDesc config) { + for (ColumnElement col : columnList) { addQueryTable(col.getDeclaringTable(), config); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/DBStatement.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/DBStatement.java index 70be0c2c822..5769cda6b44 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/DBStatement.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/DBStatement.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,22 +15,14 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * DBStatement.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.database.DBVendorType; import com.sun.jdo.spi.persistence.support.sqlstore.model.LocalFieldDesc; -import com.sun.jdo.spi.persistence.utility.logging.Logger; import java.io.ByteArrayInputStream; import java.io.StringReader; +import java.lang.System.Logger; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Blob; @@ -44,6 +37,8 @@ import org.netbeans.modules.dbschema.ColumnElement; +import static java.lang.System.Logger.Level.DEBUG; + /** */ public class DBStatement extends Object { @@ -56,8 +51,9 @@ public class DBStatement extends Object { * Batch threshold. Set the value from the system property named by * this class followed by "BATCH_THRESHOLD". Default is 100. */ - private static final int BATCH_THRESHOLD = - Integer.getInteger(BATCH_THRESHOLD_PROPERTY, 100).intValue(); + private static final int BATCH_THRESHOLD = Integer.getInteger(BATCH_THRESHOLD_PROPERTY, 100).intValue(); + + private static final Logger LOG = System.getLogger(DBStatement.class.getName()); /** The wrapped PreparedStatement. */ private PreparedStatement preparedStmt; @@ -68,9 +64,6 @@ public class DBStatement extends Object { /** The SQL text. */ private String statementText; - /** The logger */ - private static Logger logger = LogHelperSQLStore.getLogger(); - /** * This constructor is used for batched updates. * @param conn the connection @@ -121,10 +114,7 @@ public void addBatch() throws SQLException { batchCounter++; - if (logger.isLoggable(Logger.FINER)) { - logger.finer("sqlstore.sql.generator.dbstatement.addbatch", // NOI18N - new Integer(batchCounter)); - } + LOG.log(DEBUG, "sqlstore.sql.generator.dbstatement.addbatch", batchCounter); preparedStmt.addBatch(); } @@ -132,13 +122,8 @@ public void addBatch() * Delegates the executeBatch call to the PreparedStatement wrapped by * this DBStatement and resets the batch counter. */ - public int[] executeBatch() - throws SQLException - { - if (logger.isLoggable(Logger.FINER)) { - logger.finer("sqlstore.sql.generator.dbstatement.executebatch", // NOI18N - new Integer(batchCounter)); - } + public int[] executeBatch() throws SQLException { + LOG.log(DEBUG, "sqlstore.sql.generator.dbstatement.executebatch", batchCounter); batchCounter = 0; return preparedStmt.executeBatch(); } @@ -195,10 +180,7 @@ public void bindInputColumn(int index, Object val, ColumnElement columnElement, throws SQLException { int sqlType = getSqlType(columnElement); - if (logger.isLoggable(Logger.FINER)) { - Object[] items = {new Integer(index),val,new Integer(sqlType)}; - logger.finer("sqlstore.sql.generator.dbstatement.bindinputcolumn", items); // NOI18N - } + LOG.log(DEBUG, "sqlstore.sql.generator.dbstatement.bindinputcolumn", Integer.valueOf(index), val, sqlType); if (val == null) { //setNull is called only for insert and update statement to set a column diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/InputDesc.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/InputDesc.java index 039b739fc6a..6206fd01950 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/InputDesc.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/InputDesc.java @@ -24,6 +24,7 @@ package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import java.util.ArrayList; +import java.util.List; /** */ @@ -31,10 +32,9 @@ public class InputDesc extends Object { // // array of InputValue // - public ArrayList values; + public List values; public InputDesc() { - super(); - values = new ArrayList(); + values = new ArrayList<>(); } } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryPlan.java index eff58e3fbd9..17829c1ce16 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryPlan.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 */ -/* - * QueryPlan.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -31,6 +25,7 @@ import com.sun.jdo.spi.persistence.support.sqlstore.model.TableDesc; import java.util.ArrayList; +import java.util.List; import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; @@ -54,7 +49,7 @@ public abstract class QueryPlan { protected static final int ST_BUILT = 0x1; /** Array of Statement. */ - public ArrayList statements; + public List statements; protected ClassDesc config; @@ -70,7 +65,7 @@ public abstract class QueryPlan { protected SQLStoreManager store; /** Array of QueryTable. */ - protected ArrayList tables; + protected List tables; /** I18N message handler. */ protected final static ResourceBundle messages = I18NHelper.loadBundle( @@ -78,8 +73,8 @@ public abstract class QueryPlan { QueryPlan.class.getClassLoader()); public QueryPlan(ActionDesc desc, SQLStoreManager store) { - this.tables = new ArrayList(); - this.statements = new ArrayList(); + this.tables = new ArrayList<>(); + this.statements = new ArrayList<>(); this.store = store; this.config = (ClassDesc) store.getPersistenceConfig(desc.getPersistenceCapableClass()); } @@ -106,22 +101,21 @@ public QueryTable addQueryTable(TableDesc tableDesc) { public QueryTable addQueryTable(TableElement tableElement, ClassDesc persistenceConfig) { - ClassDesc _config = (persistenceConfig == null) ? this.config : persistenceConfig; + ClassDesc _config = persistenceConfig == null ? this.config : persistenceConfig; TableDesc tableDesc = _config.findTableDesc(tableElement); if (tableDesc == null) { - if (tableElement != null) { - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.classnotmappedtotable", // NOI18N - _config.getPersistenceCapableClass().getName(), - tableElement.getName().getName())); - } else { + if (tableElement == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, "core.configuration.classnotmapped", // NOI18N _config.getPersistenceCapableClass().getName())); } + throw new JDOFatalInternalException(I18NHelper.getMessage(messages, + "core.configuration.classnotmappedtotable", // NOI18N + _config.getPersistenceCapableClass().getName(), + tableElement.getName().getName())); } return addQueryTable(tableDesc); @@ -134,11 +128,10 @@ public QueryTable addQueryTable(TableElement tableElement, * * @param queryTables Query tables from the foreign plan to be added. */ - public void addQueryTables(ArrayList queryTables) { + public void addQueryTables(List queryTables) { for (int i = 0; i < queryTables.size(); i++) { - QueryTable t = (QueryTable) queryTables.get(i); - + QueryTable t = queryTables.get(i); if (tables.indexOf(t) == -1) { tables.add(t); t.getTableIndex().setValue(tables.size() - 1); @@ -152,7 +145,7 @@ public void addQueryTables(ArrayList queryTables) { */ public QueryTable findQueryTable(TableElement tableElement) { for (int i = 0; i < tables.size(); i++) { - QueryTable t = (QueryTable) tables.get(i); + QueryTable t = tables.get(i); if (t.getTableDesc().getTableElement() == tableElement) { //if (t.getTableDesc().getTableElement().equals(tableElement)) { @@ -169,17 +162,19 @@ public QueryTable findQueryTable(TableElement tableElement) { */ public QueryTable findQueryTable(TableDesc tableDesc) { for (int i = 0; i < tables.size(); i++) { - QueryTable t = (QueryTable) tables.get(i); + QueryTable t = tables.get(i); - if (t.getTableDesc() == tableDesc) return t; + if (t.getTableDesc() == tableDesc) { + return t; + } } return null; } - public ArrayList getStatements() { + public List getStatements() { for (int i = 0; i < statements.size(); i++) { - Statement s = (Statement) statements.get(i); + Statement s = statements.get(i); //Initialize sql text of the statement s.getText(); } @@ -206,13 +201,16 @@ protected Statement createStatement(QueryTable t) { } protected Statement getStatement(QueryTable t) { - if (t == null) return null; + if (t == null) { + return null; + } for (int i = 0; i < statements.size(); i++) { - Statement s = (Statement) statements.get(i); + Statement s = statements.get(i); - if (s.tableList.indexOf(t) != -1) + if (s.tableList.indexOf(t) != -1) { return s; + } } return null; @@ -226,15 +224,15 @@ protected Statement getStatement(QueryTable t) { */ protected void processStatements() { for (int i = 0; i < statements.size(); i++) { - Statement s = (Statement) statements.get(i); + Statement s = statements.get(i); - QueryTable qt = (QueryTable) s.getQueryTables().get(0); + QueryTable qt = s.getQueryTables().get(0); - ArrayList secondaryTableKeys = qt.getTableDesc().getSecondaryTableKeys(); + List secondaryTableKeys = qt.getTableDesc().getSecondaryTableKeys(); if (secondaryTableKeys != null) { for (int j = 0; j < secondaryTableKeys.size(); j++) { - ReferenceKeyDesc secondaryTableKey = (ReferenceKeyDesc) secondaryTableKeys.get(j); + ReferenceKeyDesc secondaryTableKey = secondaryTableKeys.get(j); s.addSecondaryTableStatement(getStatement(findQueryTable(secondaryTableKey.getTableDesc()))); } } @@ -250,8 +248,3 @@ public ClassDesc getConfig() { } } - - - - - diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryTable.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryTable.java index 00a5b9d3e08..1324bfb2ece 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryTable.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/QueryTable.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 */ -/* - * SqlQueryTable.java - * - * Create on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.spi.persistence.support.sqlstore.model.TableDesc; @@ -36,7 +30,7 @@ public class QueryTable extends Object { // // array of SqlQueryTable // - public ArrayList nextTable; + public ArrayList nextTable; public StringBuffer onClause; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectQueryPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectQueryPlan.java index 2e67e4f5b41..67650ba6178 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectQueryPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectQueryPlan.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,19 +15,11 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * SelectQueryPlan.java - * - * Created on October 3, 2001 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; import com.sun.jdo.api.persistence.support.JDOUserException; import com.sun.jdo.spi.persistence.support.sqlstore.ActionDesc; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore; import com.sun.jdo.spi.persistence.support.sqlstore.PersistenceManager; import com.sun.jdo.spi.persistence.support.sqlstore.RetrieveDesc; import com.sun.jdo.spi.persistence.support.sqlstore.SQLStoreManager; @@ -50,8 +43,8 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintSubquery; import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintValue; import com.sun.jdo.spi.persistence.utility.FieldTypeEnumeration; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; @@ -64,6 +57,9 @@ import org.glassfish.persistence.common.I18NHelper; import org.netbeans.modules.dbschema.ColumnElement; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.TRACE; + /** * This class prepares the generation of select statements, @@ -92,7 +88,7 @@ public class SelectQueryPlan extends QueryPlan { public int options; /** Iterator for the retrieve descriptor's list of fields to be retrieved. */ - private Iterator fieldIterator; + private Iterator fieldIterator; /** * Aggregate result type from the retrieve descriptor as defined by @@ -104,7 +100,7 @@ public class SelectQueryPlan extends QueryPlan { * List of SelectQueryPlan. After this plan is completely built, this field * contains all the foreign plans that could not be joined with this plan. */ - private ArrayList foreignPlans; + private ArrayList foreignPlans; /** * This foreign field joins this plan to the parent plan. The field is from @@ -129,7 +125,7 @@ public class SelectQueryPlan extends QueryPlan { /** BitSet containing the fields to be retrieved for this plan */ private BitSet fieldMask; - private Map foreignConstraintPlans; + private Map foreignConstraintPlans; private ResultDesc resultDesc; @@ -141,19 +137,18 @@ public class SelectQueryPlan extends QueryPlan { // See navigation033 for an example private boolean appendAndOp; - /** The logger. */ - private final static Logger logger = LogHelperSQLStore.getLogger(); + private static final Logger LOG = System.getLogger(SelectQueryPlan.class.getName(), RESOURCE_BUNDLE); /** Name of the MULTILEVEL_PREFETCH property. */ public static final String MULTILEVEL_PREFETCH_PROPERTY = - "com.sun.jdo.spi.persistence.support.sqlstore.MULTILEVEL_PREFETCH"; // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.MULTILEVEL_PREFETCH"; /** * Property to switch on multilevel prefetch. Note, that the default * is false, meaning that multilevel prefetch is disabled by default. */ private static final boolean MULTILEVEL_PREFETCH = Boolean.valueOf( - System.getProperty(MULTILEVEL_PREFETCH_PROPERTY, "false")).booleanValue(); // NOI18N + System.getProperty(MULTILEVEL_PREFETCH_PROPERTY, "false")).booleanValue(); /** * Creates a new instance of SelectQueryPlan depending on the retrieve @@ -213,7 +208,7 @@ public SelectQueryPlan(ActionDesc desc, aggregateResultType = retrieveDesc.getAggregateResultType(); } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", desc.getClass().getName(), "RetrieveDescImpl")); // NOI18N + "core.generic.notinstanceof", desc.getClass().getName(), "RetrieveDescImpl")); } } @@ -276,17 +271,19 @@ private void addColumn(LocalFieldDesc fieldDesc, boolean add, boolean projection // request as a column to the found statement. If none of the tables // are being used in this query plan then we create a new statement. // - for (Iterator iter = fieldDesc.getColumnElements(); iter.hasNext(); ) { - ColumnElement columnElement = (ColumnElement) iter.next(); + for (Iterator iter = fieldDesc.getColumnElements(); iter.hasNext(); ) { + ColumnElement columnElement = iter.next(); QueryTable table = findQueryTable(columnElement.getDeclaringTable()); - if (table == null) + if (table == null) { table = addQueryTable(columnElement.getDeclaringTable(), null); + } SelectStatement statement = (SelectStatement) getStatement(table); - if (statement == null) + if (statement == null) { statement = (SelectStatement) addStatement(table); + } if (add) { ColumnRef columnRef = statement.addColumn(columnElement, table); @@ -309,28 +306,22 @@ private void addColumn(LocalFieldDesc fieldDesc, boolean add, boolean projection * @param localFields List of fields to be selected. * @see RetrieveDescImpl */ - private void processForeignFields(ArrayList foreignFields, - ArrayList localFields) { + private void processForeignFields(ArrayList foreignFields, + ArrayList localFields) { if (foreignFields.size() == 0) { return; } - boolean debug = logger.isLoggable(Logger.FINEST); + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processforeignfield", + config.getPersistenceCapableClass().getName()); - if (debug) { - logger.finest("sqlstore.sql.generator.selectqueryplan.processforeignfield", // NOI18N - config.getPersistenceCapableClass().getName()); - } - - foreignPlans = new ArrayList(); + foreignPlans = new ArrayList<>(); for (int i = 0; i < foreignFields.size(); i++) { - processForeignField((ConstraintFieldName) foreignFields.get(i), localFields); + processForeignField(foreignFields.get(i), localFields); } - if (debug) { - logger.finest("sqlstore.sql.generator.selectqueryplan.processforeignfield.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processforeignfield.exit"); } /** @@ -343,7 +334,7 @@ private void processForeignFields(ArrayList foreignFields, * @param localFields */ private void processForeignField(ConstraintFieldName cfn, - ArrayList localFields) { + ArrayList localFields) { SelectQueryPlan fp = new SelectQueryPlan(cfn.desc, store, concurrency); @@ -361,7 +352,7 @@ private void processForeignField(ConstraintFieldName cfn, // For external (user) queries, we just make sure we include the // corresponding table into the table list. for (int i = 0; i < fp.parentField.localFields.size(); i++) { - LocalFieldDesc la = (LocalFieldDesc) fp.parentField.localFields.get(i); + LocalFieldDesc la = fp.parentField.localFields.get(i); if (!getFieldMask(la.absoluteID)) { if ((options & RetrieveDescImpl.OPT_ADD_FETCHGROUPS) > 0) { @@ -379,19 +370,21 @@ private void processForeignField(ConstraintFieldName cfn, } private boolean getGroupMask(int groupID) { - if (groupID >= FieldDesc.GROUP_DEFAULT) + if (groupID >= FieldDesc.GROUP_DEFAULT) { return hierarchicalGroupMask.get(groupID); - else if (groupID < FieldDesc.GROUP_NONE) + } else if (groupID < FieldDesc.GROUP_NONE) { return independentGroupMask.get(-(groupID + 1)); + } return true; } private void setGroupMask(int groupID) { - if (groupID >= FieldDesc.GROUP_DEFAULT) + if (groupID >= FieldDesc.GROUP_DEFAULT) { hierarchicalGroupMask.set(groupID); - else if (groupID < FieldDesc.GROUP_NONE) + } else if (groupID < FieldDesc.GROUP_NONE) { independentGroupMask.set(-(groupID + 1)); + } } /** @@ -412,17 +405,17 @@ else if (groupID < FieldDesc.GROUP_NONE) * @param foreignFields List of foreign fields connecting to foreign plans. */ private void addFetchGroup(int groupID, - ArrayList localFields, - ArrayList foreignFields) { + ArrayList localFields, + ArrayList foreignFields) { // We should enter this method only if OPT_ADD_FETCHGROUPS is set. assert (options & RetrieveDescImpl.OPT_ADD_FETCHGROUPS) > 0; - ArrayList group = config.getFetchGroup(groupID); + List group = config.getFetchGroup(groupID); setGroupMask(groupID); if (group != null) { for (int i = 0; i < group.size() ; i++) { - FieldDesc f = (FieldDesc) group.get(i); + FieldDesc f = group.get(i); if (!getFieldMask(f.absoluteID)) { final boolean isLocalField = f instanceof LocalFieldDesc; @@ -470,8 +463,8 @@ private void addFetchGroup(int groupID, * @param foreignFields List of foreign fields. */ private void addFetchGroups(int groupID, - ArrayList localFields, - ArrayList foreignFields) { + ArrayList localFields, + ArrayList foreignFields) { if (groupID >= FieldDesc.GROUP_DEFAULT) { //Hierachical fetch group @@ -506,7 +499,7 @@ private void addFetchGroups(int groupID, * @param foreignFields List of foreign fields. * @see RetrieveDescImpl#setFetchGroupOptions(int) */ - private void processFetchGroups(ArrayList localFields, ArrayList foreignFields) { + private void processFetchGroups(ArrayList localFields, ArrayList foreignFields) { if ((options & RetrieveDescImpl.OPT_ADD_FETCHGROUPS) > 0) { int requestedItems = localFields.size() + foreignFields.size(); @@ -518,7 +511,7 @@ private void processFetchGroups(ArrayList localFields, ArrayList foreignFields) if (requestedItems > 0) { for (int i = 0; i < localFields.size(); i++) { - FieldDesc f = (FieldDesc) localFields.get(i); + FieldDesc f = localFields.get(i); setFieldMask(f.absoluteID); @@ -530,7 +523,7 @@ private void processFetchGroups(ArrayList localFields, ArrayList foreignFields) } for (int i = 0; i < foreignFields.size(); i++) { - ConstraintFieldName cfn = (ConstraintFieldName) foreignFields.get(i); + ConstraintFieldName cfn = foreignFields.get(i); FieldDesc f = config.getField(cfn.name); setFieldMask(f.absoluteID); @@ -551,29 +544,23 @@ private void processFetchGroups(ArrayList localFields, ArrayList foreignFields) * @param localFields List of local fields to be selected. * @param projectionField The projected field. */ - private void processLocalFields(ArrayList localFields, LocalFieldDesc projectionField) { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - logger.finest("sqlstore.sql.generator.selectqueryplan.processlocalfield", // NOI18N - config.getPersistenceCapableClass().getName()); - } + private void processLocalFields(ArrayList localFields, LocalFieldDesc projectionField) { + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processlocalfield", + config.getPersistenceCapableClass().getName()); for (int i = 0; i < localFields.size(); i++) { LocalFieldDesc lf = (LocalFieldDesc) localFields.get(i); addColumn(lf, true, (projectionField == lf)); } - if (debug) { - logger.finest("sqlstore.sql.generator.selectqueryplan.processlocalfield.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processlocalfield.exit"); } private void joinSecondaryTableStatement(SelectStatement statement, SelectStatement secondaryTableStatement) { statement.copyColumns(secondaryTableStatement); - QueryTable secondaryTable = (QueryTable) secondaryTableStatement.getQueryTables().get(0); + QueryTable secondaryTable = secondaryTableStatement.getQueryTables().get(0); ReferenceKeyDesc key = secondaryTable.getTableDesc().getPrimaryTableKey(); addJoinConstraint(this, this, @@ -584,7 +571,7 @@ private void joinSecondaryTableStatement(SelectStatement statement, } private void processRelatedStatements(SelectStatement statement) { - ArrayList secondaryTableStatements = statement.getSecondaryTableStatements(); + List secondaryTableStatements = statement.getSecondaryTableStatements(); if (secondaryTableStatements != null) { for (int i = 0; i < secondaryTableStatements.size(); i++) { @@ -600,14 +587,10 @@ private void processRelatedStatements(SelectStatement statement) { } } + @Override protected void processStatements() { - boolean debug = logger.isLoggable(Logger.FINEST); - - if (debug) { - Object[] items = new Object[] {config.getPersistenceCapableClass().getName(), - new Integer(statements.size())}; - logger.finest("sqlstore.sql.generator.selectqueryplan.processstmts",items); // NOI18N - } + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processstmts", + config.getPersistenceCapableClass().getName(), statements.size()); if (concurrency != null) { concurrency.select(this); @@ -621,8 +604,9 @@ protected void processStatements() { for (int i = 0; i < size; i++) { SelectStatement s = (SelectStatement) statements.get(i); - if (!s.isJoined()) + if (!s.isJoined()) { processRelatedStatements(s); + } } // Remove all the statements that have been joined. @@ -637,9 +621,7 @@ protected void processStatements() { } } - if (debug) { - logger.finest("sqlstore.sql.generator.selectqueryplan.processstmts.exit"); // NOI18N - } + LOG.log(TRACE, "sqlstore.sql.generator.selectqueryplan.processstmts.exit"); } @@ -651,10 +633,10 @@ protected void processStatements() { * @see ConstraintFieldName#originalPlan */ private void processLocalConstraints() { - List stack = constraint.getConstraints(); + List stack = constraint.getConstraints(); for (int i = 0; i < stack.size(); i++) { - ConstraintNode node = (ConstraintNode) stack.get(i); + ConstraintNode node = stack.get(i); if (node instanceof ConstraintFieldName) { ConstraintFieldName fieldNode = (ConstraintFieldName) node; @@ -720,20 +702,20 @@ private SelectQueryPlan newForeignConstraintPlan(RetrieveDescImpl rd, } if (foreignConstraintPlans == null) { - foreignConstraintPlans = new HashMap(); + foreignConstraintPlans = new HashMap<>(); } SelectQueryPlan masterPlan = null; Object tag = (rd.getNavigationalId() != null) ? rd.getNavigationalId() : fieldName; - if ((masterPlan = (SelectQueryPlan) foreignConstraintPlans.get(tag)) != null) { + if ((masterPlan = foreignConstraintPlans.get(tag)) != null) { // Share the tables with the master plan. fcp.tables = masterPlan.tables; fcp.foreignConstraintPlans = masterPlan.foreignConstraintPlans; } else { foreignConstraintPlans.put(tag, fcp); - fcp.foreignConstraintPlans = new HashMap(); + fcp.foreignConstraintPlans = new HashMap<>(); } return fcp; @@ -750,7 +732,7 @@ private SelectQueryPlan newForeignConstraintPlan(RetrieveDescImpl rd, */ private void addCorrelatedExistsQuery(ForeignFieldDesc ff, int operation) { - Class classType = (ff.cardinalityUPB > 1) ? ff.getComponentType() : ff.getType(); + Class classType = (ff.cardinalityUPB > 1) ? ff.getComponentType() : ff.getType(); RetrieveDescImpl rd = (RetrieveDescImpl) store.getRetrieveDesc(classType); SelectQueryPlan subqueryPlan = new CorrelatedExistSelectPlan(rd, store, ff, this); @@ -774,12 +756,12 @@ private void addCorrelatedExistsQuery(ForeignFieldDesc ff, int operation) { * @see RetrieveDescImpl */ private void processForeignConstraints() { - List currentStack = constraint.getConstraints(); - constraint.stack = new ArrayList(); + List currentStack = constraint.getConstraints(); + constraint.stack = new ArrayList<>(); int index = 0; while (index < currentStack.size()) { - ConstraintNode node = (ConstraintNode) currentStack.get(index); + ConstraintNode node = currentStack.get(index); if (node instanceof ConstraintForeignFieldName) { processForeignFieldConstraint((ConstraintForeignFieldName) node); @@ -812,7 +794,7 @@ private void processForeignFieldConstraint(ConstraintForeignFieldName node) { if (rd == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.constraint.noretrievedesc", // NOI18N + "sqlstore.constraint.noretrievedesc", node.name, config.getPersistenceCapableClass().getName())); } @@ -839,7 +821,7 @@ private void processForeignFieldConstraint(ConstraintForeignFieldName node) { * @param index Index in current stack. */ private int processLocalFieldConstraint(ConstraintFieldName node, - List currentStack, + List currentStack, int index) { if (node.desc != null) { SelectQueryPlan fcp = ((RetrieveDescImpl) node.desc).getPlan(); @@ -882,7 +864,7 @@ private int processLocalFieldConstraint(ConstraintFieldName node, * @param index Index in current stack. */ private int processForeignFieldNullComparision(ConstraintFieldName node, - List currentStack, + List currentStack, int index) { boolean addCurrentNode = true; if (node.name != null) { @@ -890,7 +872,7 @@ private int processForeignFieldNullComparision(ConstraintFieldName node, FieldDesc f = config.getField(node.name); if (f instanceof ForeignFieldDesc && (index + 1 < currentStack.size())) { - ConstraintNode nextNode = (ConstraintNode) currentStack.get(++index); + ConstraintNode nextNode = currentStack.get(++index); if ((nextNode instanceof ConstraintOperation) && ((((ConstraintOperation) nextNode).operation == ActionDesc.OP_NULL) || (((ConstraintOperation) nextNode).operation == ActionDesc.OP_NOTNULL))) { @@ -923,10 +905,10 @@ private void processNullConstraint(ForeignFieldDesc ff, ConstraintNode nextNode) if (ff.hasForeignKey()) { // Optimize the query to compare the foreign key fields with null. - ArrayList localFields = ff.getLocalFields(); + ArrayList localFields = ff.getLocalFields(); for (int j = 0; j < localFields.size(); j++) { - constraint.stack.add(new ConstraintFieldDesc((LocalFieldDesc) localFields.get(j))); + constraint.stack.add(new ConstraintFieldDesc(localFields.get(j))); constraint.stack.add(nextNode); } } else { @@ -959,7 +941,7 @@ private void addCorrelatedInQuery(ConstraintFieldNameSubQuery node) { if (ff.getComponentType() != rd.getPersistenceCapableClass() ) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.unknownfield", // NOI18N + "core.constraint.unknownfield", node.fieldName, rd.getPersistenceCapableClass().getName())); } @@ -974,16 +956,16 @@ private void addCorrelatedInQuery(ConstraintFieldNameSubQuery node) { subqueryConstraint.plan = subqueryPlan; constraint.stack.add(subqueryConstraint); - ArrayList localFields = ff.getLocalFields(); + ArrayList localFields = ff.getLocalFields(); // Add the local fields corresponding to the subquery to the stack. for (int i = 0; i < localFields.size(); i++) { - constraint.addField((LocalFieldDesc) localFields.get(i), this); + constraint.addField(localFields.get(i), this); } } else { // We didn't get a ForeignFieldDesc from config, // or the field is not present in the config. throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.unknownfield", // NOI18N + "core.constraint.unknownfield", node.fieldName, rd.getPersistenceCapableClass().getName())); } } @@ -999,11 +981,11 @@ private void addCorrelatedInQuery(ConstraintFieldNameSubQuery node) { * {@link RetrieveDesc#addConstraint(String, int, RetrieveDesc, String)}. */ private void processUnboundConstraints() { - List currentStack = constraint.getConstraints(); - constraint.stack = new ArrayList(); + List currentStack = constraint.getConstraints(); + constraint.stack = new ArrayList<>(); for (int i = 0; i < currentStack.size(); i++) { - ConstraintNode node = (ConstraintNode) currentStack.get(i); + ConstraintNode node = currentStack.get(i); if (node instanceof ConstraintFieldName) { ConstraintFieldName fieldNode = (ConstraintFieldName) node; @@ -1056,7 +1038,7 @@ private void processParentField(ClassDesc parentConfig, String fieldName) { if (f == null || !(f instanceof ForeignFieldDesc)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.unknownfield", // NOI18N + "core.constraint.unknownfield", fieldName, parentConfig.getPersistenceCapableClass().getName())); } parentField = (ForeignFieldDesc) f; @@ -1068,7 +1050,7 @@ private void processParentField(ClassDesc parentConfig, String fieldName) { // See collection38 // for (int i = 0; i < parentField.assocLocalColumns.size(); i++) { - ColumnElement col = (ColumnElement) parentField.assocLocalColumns.get(i); + ColumnElement col = parentField.assocLocalColumns.get(i); addQueryTable(col.getDeclaringTable(), config); } } @@ -1077,7 +1059,7 @@ private void processParentField(ClassDesc parentConfig, String fieldName) { // This is required for cases where no fields from this plan are selected // The side-effect for this is to create statements with no columns. for (int i = 0; i < parentField.foreignColumns.size(); i++) { - ColumnElement col = (ColumnElement) parentField.foreignColumns.get(i); + ColumnElement col = parentField.foreignColumns.get(i); addQueryTable(col.getDeclaringTable(), config); } } @@ -1087,6 +1069,7 @@ private void processParentField(ClassDesc parentConfig, String fieldName) { * Builds the query plan for a select type * {@link ActionDesc} (i.e. a {@link RetrieveDesc}). */ + @Override public void build() { // Plan must be build only once. if ((status & ST_BUILT) > 0) { @@ -1109,8 +1092,8 @@ public void build() { * Must be overwritten by subquery plans! */ protected void processFields() { - ArrayList foreignFields = new ArrayList(); - ArrayList localFields = new ArrayList(); + ArrayList foreignFields = new ArrayList<>(); + ArrayList localFields = new ArrayList<>(); LocalFieldDesc projectionField = separateFieldList(localFields, foreignFields); @@ -1134,18 +1117,18 @@ protected void processFields() { * @param foreignFields List of ConstraintFieldName. * @return LocalFieldDesc of the projected field. */ - private LocalFieldDesc separateFieldList(ArrayList localFields, - ArrayList foreignFields) { + private LocalFieldDesc separateFieldList(ArrayList localFields, + ArrayList foreignFields) { LocalFieldDesc projectionField = null; while (fieldIterator.hasNext()) { - ConstraintFieldName cfn = (ConstraintFieldName) fieldIterator.next(); + ConstraintFieldName cfn = fieldIterator.next(); FieldDesc f = config.getField(cfn.name); if (f == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.unknownfield", // NOI18N + "core.constraint.unknownfield", cfn.name, config.getPersistenceCapableClass().getName())); } @@ -1314,22 +1297,22 @@ private void mergeResultDesc(SelectQueryPlan foreignPlan) { * * @param fromPlan The plan for fromColumns * @param toPlan The plan for toColumns - * @param fromColumns List of local columns. - * @param toColumns List of foreign columns. + * @param localColumns List of local columns. + * @param assocLocalColumns List of foreign columns. * @param joinOp Join operation. This operation is never a non relationship join. */ protected void addJoinConstraint(SelectQueryPlan fromPlan, SelectQueryPlan toPlan, - ArrayList fromColumns, - ArrayList toColumns, + List localColumns, + List assocLocalColumns, int joinOp) { ConstraintJoin join = new ConstraintJoin(); join.operation = joinOp; - join.fromColumns = fromColumns; + join.fromColumns = localColumns; join.fromPlan = fromPlan; - join.toColumns = toColumns; + join.toColumns = assocLocalColumns; join.toPlan = toPlan; constraint.addJoinConstraint(join); @@ -1350,8 +1333,8 @@ private void processJoins() { return; } - for (Iterator iter = foreignPlans.iterator(); iter.hasNext(); ) { - SelectQueryPlan fp = (SelectQueryPlan) iter.next(); + for (Iterator iter = foreignPlans.iterator(); iter.hasNext(); ) { + SelectQueryPlan fp = iter.next(); if ((fp.status & ST_JOINED) == 0) { // Recursively join foreign plans of the foreign plan. @@ -1370,12 +1353,11 @@ private void processJoins() { } // Sanity check. - if (foreignPlans != null && foreignPlans.size() > 0) { - - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.sql.generator.selectqueryplan.plansnotjoined")); // NOI18N - } else { + if (foreignPlans == null || foreignPlans.isEmpty()) { foreignPlans = null; + } else { + throw new JDOFatalInternalException(I18NHelper.getMessage(messages, + "sqlstore.sql.generator.selectqueryplan.plansnotjoined")); } } @@ -1455,7 +1437,7 @@ public void processOrderConstraints() { return; } - ArrayList orderByArray = new ArrayList(); + ArrayList> orderByArray = new ArrayList<>(); int i, pos; int insertAt = 0; @@ -1466,14 +1448,14 @@ public void processOrderConstraints() { if (constraint != null) { i = 0; while (i < constraint.stack.size()) { - ConstraintNode opNode = (ConstraintNode) constraint.stack.get(i); + ConstraintNode opNode = constraint.stack.get(i); if ((opNode instanceof ConstraintOperation) - && ((((ConstraintOperation) opNode).operation == ActionDesc.OP_ORDERBY) || - (((ConstraintOperation) opNode).operation == ActionDesc.OP_ORDERBY_DESC))) { + && ((((ConstraintOperation) opNode).operation == ActionDesc.OP_ORDERBY) + || (((ConstraintOperation) opNode).operation == ActionDesc.OP_ORDERBY_DESC))) { pos = -1; if ((i > 1) && (constraint.stack.get(i - 2) instanceof ConstraintValue)) { - pos = ((Integer) ((ConstraintValue) constraint.stack.get(i - 2)).getValue() ).intValue(); + pos = ((Integer) ((ConstraintValue) constraint.stack.get(i - 2)).getValue()).intValue(); constraint.stack.remove(i - 2); i = i - 1; } @@ -1487,10 +1469,10 @@ public void processOrderConstraints() { } if (orderByArray.get(insertAt) == null) { - orderByArray.set(insertAt, new ArrayList()); + orderByArray.set(insertAt, new ArrayList<>()); } - ConstraintNode fieldNode = (ConstraintNode) constraint.stack.get(i - 1); + ConstraintNode fieldNode = constraint.stack.get(i - 1); ConstraintFieldDesc consFieldDesc = null; if (fieldNode instanceof ConstraintFieldName) { @@ -1500,25 +1482,19 @@ public void processOrderConstraints() { originalPlan = ((ConstraintField) fieldNode).originalPlan; } - FieldDesc fieldDesc = originalPlan.config. - getField(((ConstraintFieldName) fieldNode).name); + FieldDesc fieldDesc = originalPlan.config.getField(((ConstraintFieldName) fieldNode).name); if (!(fieldDesc instanceof LocalFieldDesc)) { - throw new JDOUserException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - fieldDesc.getClass().getName(), - "LocalFieldDesc")); // NOI18N + throw new JDOUserException(I18NHelper.getMessage(messages, "core.generic.notinstanceof", + fieldDesc.getClass().getName(), "LocalFieldDesc")); } - consFieldDesc = new ConstraintFieldDesc((LocalFieldDesc) fieldDesc, - originalPlan, 1); + consFieldDesc = new ConstraintFieldDesc((LocalFieldDesc) fieldDesc, originalPlan, 1); } else if (fieldNode instanceof ConstraintFieldDesc) { consFieldDesc = (ConstraintFieldDesc) fieldNode; } else { - throw new JDOUserException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - fieldNode.getClass().getName(), - "ConstraintFieldName/ConstraintFieldDesc")); // NOI18N + throw new JDOUserException(I18NHelper.getMessage(messages, "core.generic.notinstanceof", + fieldNode.getClass().getName(), "ConstraintFieldName/ConstraintFieldDesc")); } if (((ConstraintOperation) opNode).operation == ActionDesc.OP_ORDERBY_DESC) { @@ -1526,7 +1502,7 @@ public void processOrderConstraints() { } // Remember constraint in orderByArray. - ArrayList temp = (ArrayList) (orderByArray.get(insertAt)); + List temp = (orderByArray.get(insertAt)); temp.add(consFieldDesc); constraint.stack.remove(i); @@ -1538,14 +1514,14 @@ public void processOrderConstraints() { } for (int j = 0, size = orderByArray.size(); j < size; j++) { - ArrayList oa = (ArrayList) orderByArray.get(j); + List oa = orderByArray.get(j); if (constraint == null) { constraint = new Constraint(); } for (int k = 0, sizeK = oa.size(); k < sizeK; k++) { - ConstraintFieldDesc ob = (ConstraintFieldDesc) oa.get(k); + ConstraintFieldDesc ob = oa.get(k); if (ob.ordering < 0) { constraint.addField(ob); @@ -1560,6 +1536,7 @@ public void processOrderConstraints() { status |= ST_OC_BUILT; } + @Override protected Statement newStatement() { return new SelectStatement(store.getVendorType(), this); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectStatement.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectStatement.java index 6a8a0d5d4d9..ffc48462d0d 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectStatement.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/SelectStatement.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 */ -/* - * SelectStatement.java - * - * Created on October 3, 2001 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.api.persistence.support.JDOFatalDataStoreException; @@ -71,12 +65,10 @@ public void markJoined() { isJoined = true; } - public ColumnRef addColumn(ColumnElement columnElement, - QueryTable queryTable) { - - ColumnRef columnRef = null; - if ((columnRef = getColumnRef(columnElement)) == null) { + public ColumnRef addColumn(ColumnElement columnElement, QueryTable queryTable) { + ColumnRef columnRef = getColumnRef(columnElement); + if (columnRef == null) { columnRef = new ColumnRef(columnElement, queryTable); addColumnRef(columnRef); } @@ -85,13 +77,11 @@ public ColumnRef addColumn(ColumnElement columnElement, } public void copyColumns(SelectStatement sourceStatement) { - ArrayList columnRefs = sourceStatement.getColumnRefs(); - + List columnRefs = sourceStatement.getColumnRefs(); int index = columns.size() + 1; - for (int i = 0; i < columnRefs.size(); i++) { //addColumnRef((ColumnRef) columnRefs.get(i)); - ColumnRef cref = (ColumnRef) columnRefs.get(i); + ColumnRef cref = columnRefs.get(i); cref.setIndex(index + i); columns.add(cref); } @@ -102,6 +92,7 @@ protected boolean isUpdateLockRequired(QueryTable table) { && table.getTableDesc().isUpdateLockRequired(); } + @Override public void appendTableText(StringBuffer text, QueryTable table) { super.appendTableText(text, table); @@ -132,6 +123,7 @@ public boolean isColumnTypeDefinitionNeeded() { } /** @inheritDoc */ + @Override public QueryPlan getQueryPlan() { return plan; } @@ -139,6 +131,7 @@ public QueryPlan getQueryPlan() { /** * @inheritDoc */ + @Override protected void generateStatementText() { // Because join conditions for ANSI outer joins end up in the // from clause, the constraint stack has to be processed before we @@ -181,7 +174,7 @@ private void generateRegularStatementText(StringBuffer whereClause) { StringBuffer columnText = generateColumnText(); String tableListText = generateTableListText(); String aggregateText = getAggregateText(); - String aggregateEnd = (aggregateText.length() > 0) ? ")" : ""; // NOI18N + String aggregateEnd = (aggregateText.length() > 0) ? ")" : ""; if (orderClause.length() > 0) { orderClause.insert(0, " order by "); @@ -192,9 +185,9 @@ private void generateRegularStatementText(StringBuffer whereClause) { String distinctText = getDistinctText(updateLockRequired); // Create the query filling in the column list, table name, etc. - statementText.append("select "). // NOI18N + statementText.append("select "). append(aggregateText).append(distinctText).append(columnText).append(aggregateEnd). - append(" from ").append(tableListText). // NOI18N + append(" from ").append(tableListText). append(whereClause).append(orderClause).append(forUpdateClause); } @@ -279,9 +272,9 @@ private void generateCorrelatedExistsText(StringBuffer whereClause) { String tableListText = generateTableListText(); // Create the query with the previous generated parts. - statementText.append("select count(*) from "). // NOI18N + statementText.append("select count(*) from "). append(primaryTableText). - append(" where exists (select * from "). // NOI18N + append(" where exists (select * from "). append(tableListText).append(whereClause).append(")"). //NOI18N append(forUpdateClause); } @@ -295,7 +288,7 @@ private void generateCorrelatedExistsText(StringBuffer whereClause) { private QueryTable generatePrimaryTableText(StringBuffer primaryTableText) { // Get the primary table from the first selected column. // TODO: Is the first column always mapped to the primary table? - QueryTable primaryTable = ((ColumnRef)columns.get(0)).getQueryTable(); + QueryTable primaryTable = columns.get(0).getQueryTable(); // Generate the table text. appendTableText(primaryTableText, primaryTable); @@ -307,11 +300,11 @@ protected StringBuffer generateColumnText() { StringBuffer columnText = new StringBuffer(); for (int i = 0; i < columns.size(); i++) { - ColumnRef cr = (ColumnRef) columns.get(i); + ColumnRef cr = columns.get(i); - columnText.append("t").append(cr.getQueryTable().getTableIndex()).append("."); // NOI18N + columnText.append("t").append(cr.getQueryTable().getTableIndex()).append("."); appendQuotedText(columnText, cr.getName()); - columnText.append(", "); // NOI18N + columnText.append(", "); } columnText.delete(columnText.length() - 2, columnText.length()); return columnText; @@ -322,18 +315,18 @@ private String getAggregateText() { switch (aggregateOption) { case RetrieveDescImpl.OPT_AVG: - return "AVG( "; // NOI18N + return "AVG( "; case RetrieveDescImpl.OPT_MIN: - return "MIN("; // NOI18N + return "MIN("; case RetrieveDescImpl.OPT_MAX: - return "MAX("; // NOI18N + return "MAX("; case RetrieveDescImpl.OPT_SUM: - return "SUM("; // NOI18N + return "SUM("; case RetrieveDescImpl.OPT_COUNT: case RetrieveDescImpl.OPT_COUNT_PC: - return "COUNT("; // NOI18N + return "COUNT("; default: - return ""; // NOI18N + return ""; } } @@ -346,7 +339,7 @@ private StringBuffer generateForUpdateClause(boolean updateLockRequired) { // Throw an exception user wanted to have update lock // But vendor is not supporting it. Do not allow user to proceed throw new JDOFatalDataStoreException(I18NHelper.getMessage(messages, - "sqlstore.selectstatement.noupdatelocksupport"));// NOI18N + "sqlstore.selectstatement.noupdatelocksupport")); } // generating the ForUpdate Clause @@ -358,14 +351,14 @@ private StringBuffer generateForUpdateClause(boolean updateLockRequired) { if (vendorType.isLockColumnListSupported()) { for (int i = 0; i < tableList.size(); i++) { - QueryTable queryTable = (QueryTable) tableList.get(i); + QueryTable queryTable = tableList.get(i); if (isUpdateLockRequired(queryTable)) { TableDesc tableDesc = queryTable.getTableDesc(); //Get the first column of primary key - ColumnElement ce = (ColumnElement) tableDesc.getKey().getColumns().get(0); - forUpdateClause.append("t").append(i).append("."); // NOI18N + ColumnElement ce = tableDesc.getKey().getColumns().get(0); + forUpdateClause.append("t").append(i).append("."); appendQuotedText(forUpdateClause, ce.getName().getName()); - forUpdateClause.append(", "); // NOI18N + forUpdateClause.append(", "); } } // Remove trailing ", " @@ -378,7 +371,7 @@ private StringBuffer generateForUpdateClause(boolean updateLockRequired) { } private String getDistinctText(boolean updateLockRequired) { - String distinctText = ""; // NOI18N + String distinctText = ""; if ((plan.options & RetrieveDescImpl.OPT_DISTINCT) > 0) { if( !updateLockRequired || vendorType.isDistinctSupportedWithUpdateLock()) { @@ -389,7 +382,7 @@ private String getDistinctText(boolean updateLockRequired) { //For the case where update lock is required and vendor does not support DISTINCT/ //with update lock, we would do DISTINCT in our code after retrieving the data //see SQLStoreManger::retrieve() - distinctText = "distinct "; // NOI18N + distinctText = "distinct "; } } return distinctText; @@ -406,7 +399,7 @@ private boolean isUpdateLockRequired() { // TODO: We can optimize this by storing the value in a member variable for (int i = 0; i < tableList.size() && !updateLockRequired; i++) { - QueryTable queryTable = (QueryTable) tableList.get(i); + QueryTable queryTable = tableList.get(i); updateLockRequired = isUpdateLockRequired(queryTable); } @@ -417,31 +410,33 @@ private boolean isUpdateLockRequired() { * Processes Order By constraints and calls the super class * method for all other constrains. */ + @Override protected void processRootConstraint(ConstraintOperation opNode, - List stack, + List stack, StringBuffer whereText) { int op = opNode.operation; int opInfo = operationFormat(op); if ((opInfo & OP_ORDERBY_MASK) > 0) { stack.remove(stack.size() - 1); - ConstraintNode node = (ConstraintNode) stack.get(stack.size() - 1); + ConstraintNode node = stack.get(stack.size() - 1); - if (!(node instanceof ConstraintField)) { - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needfieldnode")); // NOI18N - } else { + if (node instanceof ConstraintField) { processOrderByField((ConstraintFieldDesc) node, op); stack.remove(stack.size() - 1); + } else { + throw new JDOFatalInternalException(I18NHelper.getMessage(messages, + "core.constraint.needfieldnode")); } } else { super.processRootConstraint(opNode, stack, whereText); } } + @Override protected void processIrregularOperation(ConstraintOperation opNode, int opCode, - List stack, + List stack, StringBuffer result) { switch (opCode) { case ActionDesc.OP_EQUIJOIN: @@ -461,7 +456,7 @@ protected void processIrregularOperation(ConstraintOperation opNode, */ private StringBuffer processOuterJoinConstraints() { StringBuffer joinCondition = null; - final List joinStack = constraint.getOuterJoinConstraints(); + final List joinStack = constraint.getOuterJoinConstraints(); final int joinStackSize = joinStack.size(); if (joinStackSize > 0) { @@ -516,8 +511,8 @@ private void generateJoin(ConstraintJoin jnode, int opCode) { for (int i = 0; i < jnode.fromColumns.size(); i++) { - ColumnElement fromColumn = (ColumnElement)jnode.fromColumns.get(i); - ColumnElement toColumn = (ColumnElement)jnode.toColumns.get(i); + ColumnElement fromColumn = jnode.fromColumns.get(i); + ColumnElement toColumn = jnode.toColumns.get(i); QueryTable fromTable = findQueryTable(jnode.fromPlan, fromColumn); QueryTable toTable = findQueryTable(jnode.toPlan, toColumn); @@ -550,8 +545,8 @@ private void generateJoin(ConstraintJoin jnode, private void generateAnsiJoin(ConstraintJoin jnode, int opCode) { for (int i = 0; i < jnode.fromColumns.size(); i++) { - ColumnElement fromColumn = (ColumnElement)jnode.fromColumns.get(i); - ColumnElement toColumn = (ColumnElement)jnode.toColumns.get(i); + ColumnElement fromColumn = jnode.fromColumns.get(i); + ColumnElement toColumn = jnode.toColumns.get(i); QueryTable fromTable = findQueryTable(jnode.fromPlan, fromColumn); QueryTable toTable = findQueryTable(jnode.toPlan, toColumn); @@ -593,7 +588,7 @@ private static void processFromClause(QueryTable fromTable, QueryTable toTable) // alias and the new based, of course, on the key columns. if (fromTable.nextTable == null) { - fromTable.nextTable = new ArrayList(); + fromTable.nextTable = new ArrayList<>(); fromTable.nextTable.add(toTable); toTable.prevTable = fromTable; } else { @@ -626,10 +621,10 @@ private void appendJoinCondition(StringBuffer result, result.append(" and "); } - result.append("t").append(fromTable.getTableIndex()).append("."); // NOI18N + result.append("t").append(fromTable.getTableIndex()).append("."); appendQuotedText(result, fromColumn.getName().getName()); - result.append(" ").append(joinOp). // NOI18N - append(" t").append(toTable.getTableIndex()).append("."); // NOI18N + result.append(" ").append(joinOp). + append(" t").append(toTable.getTableIndex()).append("."); appendQuotedText(result, toColumn.getName().getName()); } @@ -645,7 +640,7 @@ protected String getJoinOperator(int operation) { switch (operation) { case ActionDesc.OP_EQUIJOIN: - result = " = "; // NOI18N + result = " = "; break; case ActionDesc.OP_LEFTJOIN: result = vendorType.getLeftJoin(); @@ -656,7 +651,7 @@ protected String getJoinOperator(int operation) { default: throw new JDOFatalInternalException( I18NHelper.getMessage(messages, - "core.constraint.illegalop", operation)); // NOI18N + "core.constraint.illegalop", operation)); } return result; } @@ -675,11 +670,11 @@ private String generateTableListText() { StringBuffer str = new StringBuffer(); for (int i = 0; i < tableList.size(); i++) { - QueryTable t = (QueryTable) tableList.get(i); + QueryTable t = tableList.get(i); if (t.prevTable == null && t.nextTable == null) { appendTableText(str, t); - str.append(", "); // NOI18N + str.append(", "); } else { // Table is part of an outer join list. @@ -716,7 +711,7 @@ private void appendAnsiJoinText(StringBuffer str, QueryTable t) { str.append(vendorType.getTableListStart()); appendAnsiJoinTableText(str, t); str.append(vendorType.getTableListEnd()); - str.append(", "); // NOI18N + str.append(", "); } /** @@ -738,13 +733,13 @@ private void appendAnsiJoinTableText(StringBuffer text, QueryTable table) { } for (int i = 0; i < table.nextTable.size(); i++) { - QueryTable toTable = (QueryTable) table.nextTable.get(i); - text.append(getJoinOperator(table.joinOp)).append(" "); // NOI18N + QueryTable toTable = table.nextTable.get(i); + text.append(getJoinOperator(table.joinOp)).append(" "); appendTableText(text, toTable); if (toTable.onClause != null) { - text.append(" on "); // NOI18N + text.append(" on "); text.append(toTable.onClause); } @@ -775,11 +770,11 @@ private void processOrderByField(ConstraintFieldDesc fieldNode, int op) { generateColumnText(fieldNode.desc, thePlan, orderText); if (op == ActionDesc.OP_ORDERBY_DESC) { - orderText.append(" desc"); // NOI18N + orderText.append(" desc"); } if (orderClause.length() > 0) { - orderText.append(", "); // NOI18N + orderText.append(", "); orderText.append(orderClause); } orderClause = orderText; @@ -796,7 +791,7 @@ private void processOrderByField(ConstraintFieldDesc fieldNode, int op) { public void bindInputValues(DBStatement s, ValueFetcher parameters) throws SQLException { for (int i = 0, size = inputDesc.values.size(); i < size; i++) { - InputValue inputVal = (InputValue) inputDesc.values.get(i); + InputValue inputVal = inputDesc.values.get(i); s.bindInputColumn(i + 1, getInputValue(inputVal, parameters), inputVal.getColumnElement(), vendorType); } @@ -812,7 +807,7 @@ private Object[] getInputValues(ValueFetcher parameters) { final int size = inputDesc.values.size(); Object[] inputValues = new Object[size]; for (int i = 0; i < size; i++) { - InputValue inputValue = (InputValue) inputDesc.values.get(i); + InputValue inputValue = inputDesc.values.get(i); inputValues[i] = getInputValue(inputValue, parameters); } return inputValues; @@ -838,8 +833,7 @@ public String getFormattedSQLText(ValueFetcher parameters) { * @param parameters The parameters. * @return Appropriate value as described above. */ - private static Object getInputValue(InputValue inputVal, - ValueFetcher parameters) { + private static Object getInputValue(InputValue inputVal, ValueFetcher parameters) { Object val; if (inputVal instanceof InputParamValue) { int paramIndex = ((InputParamValue) inputVal).getParamIndex().intValue(); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/Statement.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/Statement.java index 177c8cf7012..1dc8cc7610b 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/Statement.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/Statement.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 */ -/* - * Statement.java - * - * Created on March 3, 2000 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -38,6 +32,8 @@ import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintSubquery; import com.sun.jdo.spi.persistence.support.sqlstore.sql.constraint.ConstraintValue; +import java.lang.System.Logger; +import java.lang.System.Logger.Level; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; @@ -48,12 +44,15 @@ import org.netbeans.modules.dbschema.ColumnElement; import org.netbeans.modules.dbschema.TableElement; +import static java.lang.System.Logger.Level.TRACE; + /** * This class is used to represent a SQL statement. */ public abstract class Statement extends Object implements Cloneable { - private static final Integer ONE = new Integer(1); + private static final Logger LOG = System.getLogger(Statement.class.getName()); + private static final Integer ONE = Integer.valueOf(1); protected static final int OP_PREFIX_MASK = 0x001; // 1 @@ -86,7 +85,7 @@ public abstract class Statement extends Object implements Cloneable { private String quoteCharEnd; /** array of ColumnRef */ - protected ArrayList columns; + protected List columns; Constraint constraint; @@ -95,33 +94,34 @@ public abstract class Statement extends Object implements Cloneable { int action; /** array of QueryTable */ - public ArrayList tableList; + public List tableList; protected DBVendorType vendorType; - protected ArrayList secondaryTableStatements; + protected List secondaryTableStatements; /** * I18N message handler */ protected final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", Statement.class.getClassLoader()); public Statement(DBVendorType vendorType) { inputDesc = new InputDesc(); - columns = new ArrayList(); + columns = new ArrayList<>(); constraint = new Constraint(); - tableList = new ArrayList(); + tableList = new ArrayList<>(); this.vendorType = vendorType; - if (vendorType.getQuoteSpecialOnly() == false) { - // DO NOT SUPPORT QUOTING OTHERWISE - this.quoteCharStart = vendorType.getQuoteCharStart(); - this.quoteCharEnd = vendorType.getQuoteCharEnd(); + if (vendorType.getQuoteSpecialOnly()) { + return; } + // DO NOT SUPPORT QUOTING OTHERWISE + this.quoteCharStart = vendorType.getQuoteCharStart(); + this.quoteCharEnd = vendorType.getQuoteCharEnd(); } public void addQueryTable(QueryTable table) { @@ -141,15 +141,18 @@ protected ColumnRef getColumnRef(ColumnElement columnElement) { int size = columns.size(); for (int i = 0; i < size; i++) { - ColumnRef cref = (ColumnRef) columns.get(i); + ColumnRef cref = columns.get(i); - if (cref.getColumnElement() == columnElement) return cref; + if (cref.getColumnElement() == columnElement) { + return cref; + } } return null; } protected void addColumnRef(ColumnRef columnRef) { + LOG.log(Level.DEBUG, "addColumnRef(columnRef={0})", columnRef); columnRef.setIndex(columns.size()+1); columns.add(columnRef); } @@ -185,7 +188,7 @@ public DBVendorType getVendorType() { public void appendTableText(StringBuffer text, QueryTable table) { appendQuotedText(text, table.getTableDesc().getName()); - text.append(" t"); // NOI18N + text.append(" t"); text.append(table.getTableIndex()); } @@ -195,6 +198,7 @@ public void appendTableText(StringBuffer text, QueryTable table) { * @param text The given text */ protected void appendQuotedText(StringBuffer buffer, String text) { + LOG.log(TRACE, () -> "Adding quoted text: " + text); buffer.append(quoteCharStart); buffer.append(text); buffer.append(quoteCharEnd); @@ -206,12 +210,9 @@ protected void appendQuotedText(StringBuffer buffer, String text) { * @return The text of the SQL query described by this object. */ public String getText() { - if (statementText == null) { generateStatementText(); } - - return statementText.toString(); } @@ -229,15 +230,15 @@ public String getText() { */ public StringBuffer processConstraints() { StringBuffer whereText = new StringBuffer(); - List stack = constraint.getConstraints(); + List stack = constraint.getConstraints(); while (stack.size() > 0) { - ConstraintNode node = (ConstraintNode) stack.get(stack.size() - 1); + ConstraintNode node = stack.get(stack.size() - 1); if (!(node instanceof ConstraintOperation)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - node.getClass().getName(), "ConstraintOperation")); // NOI18N + "core.generic.notinstanceof", + node.getClass().getName(), "ConstraintOperation")); } processRootConstraint((ConstraintOperation) node, stack, whereText); @@ -247,7 +248,7 @@ public StringBuffer processConstraints() { } protected void processRootConstraint(ConstraintOperation opNode, - List stack, + List stack, StringBuffer whereText) { int op = opNode.operation; int opInfo = operationFormat(op); @@ -262,7 +263,7 @@ protected void processRootConstraint(ConstraintOperation opNode, whereText.append(constraint); } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "sqlstore.sql.generator.statement.unexpectedconstraint", op)); // NOI18N + "sqlstore.sql.generator.statement.unexpectedconstraint", op)); } } @@ -283,17 +284,17 @@ protected void processRootConstraint(ConstraintOperation opNode, * We would need to sort constraints out by statement and do something * about constraints that span statements (e.g. t1.c1 = t2.c2). */ - protected String getWhereText(List stack) { + protected String getWhereText(List stack) { StringBuffer result = new StringBuffer(); ConstraintNode node; if (stack.size() == 0) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } - node = (ConstraintNode) stack.get(stack.size() - 1); + node = stack.get(stack.size() - 1); stack.remove(stack.size() - 1); if (node instanceof ConstraintParamIndex) { @@ -308,7 +309,7 @@ protected String getWhereText(List stack) { processConstraintOperation((ConstraintOperation) node, stack, result); } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalnode", // NOI18N + "core.constraint.illegalnode", node.getClass().getName())); } @@ -319,12 +320,12 @@ protected void processConstraintParamIndex(ConstraintParamIndex node, StringBuff // DB2 requires cast for parameter markers involved in numeric expressions. result.append(vendorType.getParameterMarker(node.getType())); Integer index = node.getIndex(); - inputDesc.values.add(new InputParamValue(index, getColumnElementForValueNode(node) )); + inputDesc.values.add(new InputParamValue(index, getColumnElementForValueNode(node))); } protected void processConstraintValue(ConstraintValue node, StringBuffer result) { boolean generateValueInSQLStatement = false; - String strToAppend = "?"; // NOI18N + String strToAppend = "?"; // DB2 requires cast for parameter markers involved in numeric expressions. // For DB2, do not generate parameter markers, but inline values in generated SQL. @@ -363,9 +364,9 @@ private void processConstraintField(ConstraintField fieldNode, StringBuffer resu desc = thePlan.config.getLocalFieldDesc(((ConstraintFieldName) fieldNode).name); } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N + "core.generic.notinstanceof", fieldNode.getClass().getName(), - "ConstraintFieldDesc/ConstraintFieldName")); // NOI18N + "ConstraintFieldDesc/ConstraintFieldName")); } generateColumnText(desc, thePlan, result); } @@ -385,10 +386,10 @@ protected void generateColumnText(LocalFieldDesc desc, QueryPlan thePlan, StringBuffer sb) { QueryTable table = null; ColumnElement column = null; - Iterator iter = desc.getColumnElements(); + Iterator iter = desc.getColumnElements(); while (iter.hasNext() && table == null) { - column = (ColumnElement) iter.next(); + column = iter.next(); // For updates, the member variable tableList is complete // at this point and includes only the table being updated. @@ -404,14 +405,14 @@ protected void generateColumnText(LocalFieldDesc desc, QueryPlan thePlan, if (table == null) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.configuration.fieldnotable", // NOI18N + "core.configuration.fieldnotable", desc.getName())); } // Select statements might include columns from several tables. // Qualify the column with the table index. if (action == QueryPlan.ACT_SELECT) { - sb.append("t").append(table.getTableIndex()).append("."); // NOI18N + sb.append("t").append(table.getTableIndex()).append("."); } appendQuotedText(sb, column.getName().getName()); @@ -428,8 +429,8 @@ protected void generateColumnText(LocalFieldDesc desc, QueryPlan thePlan, protected QueryTable findQueryTable(TableElement tableElement) { QueryTable table = null; - for (Iterator iter = tableList.iterator(); iter.hasNext() && table == null; ) { - QueryTable t = (QueryTable) iter.next(); + for (Iterator iter = tableList.iterator(); iter.hasNext() && table == null; ) { + QueryTable t = iter.next(); if (t.getTableDesc().getTableElement() == tableElement) { // if (t.getTableDesc().getTableElement().equals(tableElement)) { table = t; @@ -440,7 +441,7 @@ protected QueryTable findQueryTable(TableElement tableElement) { } private void processConstraintOperation(ConstraintOperation opNode, - List stack, + List stack, StringBuffer result) { int opCode = opNode.operation; int format = operationFormat(opCode); @@ -454,7 +455,7 @@ private void processConstraintOperation(ConstraintOperation opNode, private void processFunctionOrBinaryOperation(int format, int opCode, - List stack, + List stack, StringBuffer result) { if ((format & OP_PREFIX_MASK) > 0) { @@ -463,7 +464,7 @@ private void processFunctionOrBinaryOperation(int format, if ((format & OP_PCOUNT_MASK) > 0) { if ((format & OP_PAREN_MASK) > 0) { - result.append("("); // NOI18N + result.append("("); } result.append(getWhereText(stack)); @@ -474,14 +475,14 @@ private void processFunctionOrBinaryOperation(int format, result.append(infixOperator(opCode, i - 1)); } else { // opCode for which OP_FUNC_MASK is set - result.append(", "); // NOI18N + result.append(", "); } result.append(getWhereText(stack)); } if ((format & OP_PAREN_MASK) > 0) { - result.append(")"); // NOI18N + result.append(")"); } } @@ -492,7 +493,7 @@ private void processFunctionOrBinaryOperation(int format, protected void processIrregularOperation(ConstraintOperation opNode, int opCode, - List stack, + List stack, StringBuffer result) { switch (opCode) { case ActionDesc.OP_NULL: @@ -502,15 +503,15 @@ protected void processIrregularOperation(ConstraintOperation opNode, case ActionDesc.OP_BETWEEN: if (stack.size() < 3) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } if (!(stack.get(stack.size() - 1) instanceof ConstraintField)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needfieldnode")); // NOI18N + "core.constraint.needfieldnode")); } else { result.append(getWhereText(stack)); - result.append(" between "); // NOI18N + result.append(" between "); } result.append(getWhereText(stack)); result.append(" and "); @@ -524,38 +525,38 @@ protected void processIrregularOperation(ConstraintOperation opNode, case ActionDesc.OP_EXISTS: if (!(opNode instanceof ConstraintSubquery)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - opNode.getClass().getName(), "ConstraintSubquery")); // NOI18N + "core.generic.notinstanceof", + opNode.getClass().getName(), "ConstraintSubquery")); } ConstraintSubquery sqNode = (ConstraintSubquery) opNode; result.append(prefixOperator(opCode)); - result.append("("); // NOI18N + result.append("("); - Statement sqstmt = (Statement) sqNode.plan.statements.get(0); + Statement sqstmt = sqNode.plan.statements.get(0); result.append(sqstmt.getText()); - result.append(")"); // NOI18N + result.append(")"); break; case ActionDesc.OP_LIKE_ESCAPE: if (stack.size() < 3) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } if (vendorType.supportsLikeEscape()) { if (!(stack.get(stack.size() - 1) instanceof ConstraintField)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needfieldnode")); // NOI18N + "core.constraint.needfieldnode")); } else { result.append(getWhereText(stack)); - result.append(" LIKE "); // NOI18N + result.append(" LIKE "); } result.append(getWhereText(stack)); result.append(vendorType.getLeftLikeEscape()); - result.append(" ESCAPE "); // NOI18N + result.append(" ESCAPE "); result.append(getWhereText(stack)); result.append(vendorType.getRightLikeEscape()); } else { @@ -568,45 +569,45 @@ protected void processIrregularOperation(ConstraintOperation opNode, case ActionDesc.OP_SUBSTRING: if (stack.size() < 3) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } result.append(vendorType.getSubstring()); - result.append("("); // NOI18N + result.append("("); result.append(getWhereText(stack)); result.append(vendorType.getSubstringFrom()); result.append(getWhereText(stack)); result.append(vendorType.getSubstringFor()); result.append(getWhereText(stack)); - result.append(")"); // NOI18N + result.append(")"); break; case ActionDesc.OP_POSITION: if (stack.size() < 2) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } result.append(vendorType.getPosition()); - result.append("("); // NOI18N + result.append("("); boolean swap = vendorType.isPositionSearchSource(); if (swap) { ConstraintNode expr = - (ConstraintNode)stack.remove(stack.size() - 1); + stack.remove(stack.size() - 1); ConstraintNode pattern = - (ConstraintNode)stack.remove(stack.size() - 1); + stack.remove(stack.size() - 1); stack.add(expr); stack.add(pattern); } result.append(getWhereText(stack)); result.append(vendorType.getPositionSep()); - result.append(" ").append(getWhereText(stack)); // NOI18N - result.append(")"); // NOI18N + result.append(" ").append(getWhereText(stack)); + result.append(")"); break; case ActionDesc.OP_POSITION_START: if (stack.size() < 3) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } boolean swapArgs = vendorType.isPositionSearchSource(); @@ -615,20 +616,20 @@ protected void processIrregularOperation(ConstraintOperation opNode, if (threeArgs) { if (swapArgs) { ConstraintNode expr = - (ConstraintNode)stack.remove(stack.size() - 1); + stack.remove(stack.size() - 1); ConstraintNode pattern = - (ConstraintNode)stack.remove(stack.size() - 1); + stack.remove(stack.size() - 1); stack.add(expr); stack.add(pattern); } result.append(vendorType.getPosition()); - result.append("("); // NOI18N + result.append("("); result.append(getWhereText(stack)); result.append(vendorType.getPositionSep()); - result.append(" ").append(getWhereText(stack)); // NOI18N + result.append(" ").append(getWhereText(stack)); result.append(vendorType.getPositionSep()); - result.append(" ").append(getWhereText(stack)); // NOI18N - result.append(")"); // NOI18N + result.append(" ").append(getWhereText(stack)); + result.append(")"); } else { //twoArgs ConstraintValue valueNode = (ConstraintValue)stack.remove(stack.size() - 3); @@ -638,7 +639,7 @@ protected void processIrregularOperation(ConstraintOperation opNode, } else { throw new JDOFatalInternalException( I18NHelper.getMessage(messages, - "sqlstore.sql.generator.statement.positionthreeargsnotsupported")); // NOI18N + "sqlstore.sql.generator.statement.positionthreeargsnotsupported")); } } break; @@ -648,14 +649,14 @@ protected void processIrregularOperation(ConstraintOperation opNode, case ActionDesc.OP_MOD: if (stack.size() < 2) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } result.append(prefixOperator(opCode)); - result.append("("); // NOI18N + result.append("("); result.append(getWhereText(stack)); - result.append(", "); // NOI18N + result.append(", "); result.append(getWhereText(stack)); - result.append(")"); // NOI18N + result.append(")"); break; case ActionDesc.OP_CONCAT: processConcatOperation(opCode, stack, result); @@ -663,52 +664,51 @@ protected void processIrregularOperation(ConstraintOperation opNode, default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N - "" + opCode)); // NOI18N + "core.constraint.illegalop", + "" + opCode)); } } - private void processConcatOperation(int opCode, List stack, - StringBuffer result) { + private void processConcatOperation(int opCode, List stack, StringBuffer result) { if (stack.size() < 2) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } String concatCast = vendorType.getConcatCast(); if (concatCast.length() != 0) { result.append(concatCast); //Opening brace for concat cast - result.append("( "); // NOI18N + result.append("( "); } // Concat is a binary infix operator. Process it manually here. // Resolve: Why should CONCAT operation be inside braces. // Opening brace around CONCAT operation - result.append("( "); // NOI18N + result.append("( "); result.append(getWhereText(stack)); result.append(infixOperator(opCode, 0)); result.append(getWhereText(stack)); // Closing brace around CONCAT operation - result.append(" ) "); // NOI18N + result.append(" ) "); if (concatCast.length() != 0) { // Closing brace for concat cast - result.append(" ) "); // NOI18N + result.append(" ) "); } } - private void processMaybeNullOperation(List stack, StringBuffer result) { + private void processMaybeNullOperation(List stack, StringBuffer result) { ConstraintValue valueNode = null; ConstraintField fieldNode = null; if (stack.size() < 2) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } if (!(stack.get(stack.size() - 1) instanceof ConstraintField)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needfieldnode")); // NOI18N + "core.constraint.needfieldnode")); } else { fieldNode = (ConstraintField) stack.get(stack.size() - 1); stack.remove(stack.size() - 1); @@ -716,7 +716,7 @@ private void processMaybeNullOperation(List stack, StringBuffer result) { if (!(stack.get(stack.size() - 1) instanceof ConstraintValue)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needvalnode")); // NOI18N + "core.constraint.needvalnode")); } else { valueNode = (ConstraintValue) stack.get(stack.size() - 1); stack.remove(stack.size() - 1); @@ -774,7 +774,7 @@ private void processMaybeNullOperation(List stack, StringBuffer result) { } } - private void processNullOperation(int opCode, List stack, StringBuffer result) { + private void processNullOperation(int opCode, List stack, StringBuffer result) { String nullComparisionFunctionName = vendorType.getNullComparisonFunctionName(); if( nullComparisionFunctionName.length() != 0) { @@ -799,7 +799,7 @@ private void processNullOperation(int opCode, List stack, StringBuffer result) { } } else { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } } result.append (getWhereText(stack)); @@ -807,7 +807,7 @@ private void processNullOperation(int opCode, List stack, StringBuffer result) { result.append(str); } - private void processInOperation(int opCode, List stack, StringBuffer result) { + private void processInOperation(int opCode, List stack, StringBuffer result) { //We are trying to construct a where clause like following in the quotes here // where "(t0.field1, t0.field2, t0.field3,...) in // ( select t1.fld1, t1.fld2, t2.fld3,...where ....)" @@ -816,15 +816,15 @@ private void processInOperation(int opCode, List stack, StringBuffer result) { if (stack.size() < 2) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.stackempty")); // NOI18N + "core.constraint.stackempty")); } //Append the first bracket "(" to the result - result.append("("); // NOI18N + result.append("("); if (!(stack.get(stack.size() - 1) instanceof ConstraintField)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needfieldnode")); // NOI18N + "core.constraint.needfieldnode")); } else { //append "t0.field1" to c c.append(getWhereText(stack)); @@ -832,51 +832,34 @@ private void processInOperation(int opCode, List stack, StringBuffer result) { //Append ", t0.field2, t0fld3,...." while (stack.size() > 1 && (stack.get(stack.size() - 1) instanceof ConstraintField)) { - c.replace(0, 0, ", "); // NOI18N + c.replace(0, 0, ", "); c.replace(0, 0, getWhereText(stack)); } result.append(c.toString()); - result.append(") "); // NOI18N + result.append(") "); if (opCode == ActionDesc.OP_NOTIN) { - result.append("not "); // NOI18N + result.append("not "); } - result.append("in ("); // NOI18N + result.append("in ("); - ConstraintNode currentNode = (ConstraintNode)stack.remove(stack.size() - 1); + ConstraintNode currentNode = stack.remove(stack.size() - 1); if ( ! ( currentNode instanceof ConstraintSubquery)) { throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.generic.notinstanceof", // NOI18N - currentNode.getClass().getName(), "ConstraintSubquery")); // NOI18N - } else { - - ConstraintSubquery sqnode = (ConstraintSubquery) currentNode; - - Statement sqstmt = (Statement) sqnode.plan.statements.get(0); - //Append the subquery i.e. "select t1.fld1, t1.fld2, t2.fld3,...where ...." - result.append(sqstmt.getText()); - - //Close the final bracket - result.append(")"); // NOI18N - - //Append the Input values to the InputDesc of current statement - inputDesc.values.addAll(sqstmt.inputDesc.values); + "core.generic.notinstanceof", + currentNode.getClass().getName(), "ConstraintSubquery")); } + ConstraintSubquery sqnode = (ConstraintSubquery) currentNode; - /* - //This is old code that takes care of case when we just have a list of values - //as the parameter to the IN clause. We might uncomment and enhance this code - //when we implement the functionality to have list of values inside IN clause. - if (!(stack.get(stack.size() - 1) instanceof ConstraintValue)) { - throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.needvalnode")); // NOI18N - } else { - result.append(((ConstraintValue) stack.get(stack.size() - 1)).value.toString()); - stack.remove(stack.size() - 1); - } + Statement sqstmt = sqnode.plan.statements.get(0); + //Append the subquery i.e. "select t1.fld1, t1.fld2, t2.fld3,...where ...." + result.append(sqstmt.getText()); + + //Close the final bracket + result.append(")"); - result.append(")"); // NOI18N - */ + //Append the Input values to the InputDesc of current statement + inputDesc.values.addAll(sqstmt.inputDesc.values); } /** @@ -922,28 +905,28 @@ protected String infixOperator(int operation, int position) { switch (operation) { case ActionDesc.OP_ADD: - result.append(" + "); // NOI18N + result.append(" + "); break; case ActionDesc.OP_AND: result.append(" and "); break; case ActionDesc.OP_DIV: - result.append(" / "); // NOI18N + result.append(" / "); break; case ActionDesc.OP_EQ: - result.append(" = "); // NOI18N + result.append(" = "); break; case ActionDesc.OP_GE: - result.append(" >= "); // NOI18N + result.append(" >= "); break; case ActionDesc.OP_GT: - result.append(" > "); // NOI18N + result.append(" > "); break; case ActionDesc.OP_LE: - result.append(" <= "); // NOI18N + result.append(" <= "); break; case ActionDesc.OP_LT: - result.append(" < "); // NOI18N + result.append(" < "); break; case ActionDesc.OP_NE: result.append(" "); @@ -951,13 +934,13 @@ protected String infixOperator(int operation, int position) { result.append(" "); break; case ActionDesc.OP_OR: - result.append(" or "); // NOI18N + result.append(" or "); break; case ActionDesc.OP_LIKE: - result.append(" like "); // NOI18N + result.append(" like "); break; case ActionDesc.OP_MUL: - result.append(" * "); // NOI18N + result.append(" * "); break; case ActionDesc.OP_SUB: result.append(" - "); // NOI1N8 @@ -967,7 +950,7 @@ protected String infixOperator(int operation, int position) { break; case ActionDesc.OP_BETWEEN: if (position == 1) { - result.append(" between "); // NOI18N + result.append(" between "); } else { result.append(" and "); } @@ -977,8 +960,8 @@ protected String infixOperator(int operation, int position) { break; default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N - "" + operation)); // NOI18N + "core.constraint.illegalop", + "" + operation)); } return result.toString(); @@ -1080,8 +1063,8 @@ protected int operationFormat(int operation) { default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N - "" + operation)); // NOI18N + "core.constraint.illegalop", + "" + operation)); } return format; @@ -1111,8 +1094,8 @@ protected String postfixOperator(int operation) { break; default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", // NOI18N - "" + operation)); // NOI18N + "core.constraint.illegalop", + "" + operation)); } return result.toString(); @@ -1132,10 +1115,10 @@ protected String prefixOperator(int operation) { switch (operation) { case ActionDesc.OP_ABS: - result.append(vendorType.getAbs()); // NOI18N + result.append(vendorType.getAbs()); break; case ActionDesc.OP_LENGTH: - result.append(vendorType.getCharLength()); // NOI18N + result.append(vendorType.getCharLength()); break; case ActionDesc.OP_RTRIM: result.append(vendorType.getRtrim()); @@ -1144,50 +1127,53 @@ protected String prefixOperator(int operation) { result.append(prefixOperator(ActionDesc.OP_RTRIM)); break; case ActionDesc.OP_NOT: - result.append("not "); // NOI18N + result.append("not "); break; case ActionDesc.OP_SQRT: result.append(vendorType.getSqrt()); break; case ActionDesc.OP_NOTEXISTS: - result.append("not exists "); // NOI18N + result.append("not exists "); break; case ActionDesc.OP_EXISTS: - result.append("exists "); // NOI18N + result.append("exists "); break; case ActionDesc.OP_NULL_COMPARISION_FUNCTION: result.append(vendorType.getNullComparisonFunctionName()); break; case ActionDesc.OP_MOD: - result.append(vendorType.getModFunctionName()); // NOI18N + result.append(vendorType.getModFunctionName()); break; default: throw new JDOFatalInternalException(I18NHelper.getMessage(messages, - "core.constraint.illegalop", "" + operation)); // NOI18N + "core.constraint.illegalop", "" + operation)); } return result.toString(); } public void addSecondaryTableStatement(Statement s) { - if (s == null) return; + if (s == null) { + return; + } - if (secondaryTableStatements == null) - secondaryTableStatements = new ArrayList(); + if (secondaryTableStatements == null) { + secondaryTableStatements = new ArrayList<>(); + } secondaryTableStatements.add(s); } - public ArrayList getSecondaryTableStatements() { + public List getSecondaryTableStatements() { return secondaryTableStatements; } - public ArrayList getQueryTables() { + public List getQueryTables() { return tableList; } - public ArrayList getColumnRefs() { + public List getColumnRefs() { return columns; } @@ -1199,6 +1185,7 @@ public int getAction() { return action; } + @Override public Object clone() { try { return super.clone(); @@ -1218,7 +1205,7 @@ public Object clone() { */ public void bindInputValues(DBStatement s) throws SQLException { for (int i = 0, size = inputDesc.values.size(); i < size; i++) { - InputValue inputVal = (InputValue) inputDesc.values.get(i); + InputValue inputVal = inputDesc.values.get(i); s.bindInputColumn(i + 1, inputVal.getValue(), inputVal.getColumnElement(), vendorType); } @@ -1232,7 +1219,7 @@ private Object[] getInputValues() { final int size = inputDesc.values.size(); Object[] inputValues = new Object[size]; for (int i = 0; i < size; i++) { - InputValue inputValue = (InputValue) inputDesc.values.get(i); + InputValue inputValue = inputDesc.values.get(i); inputValues[i] = inputValue.getValue(); } return inputValues; @@ -1261,27 +1248,27 @@ static protected String formatSqlText(String sqlText, Object[] input) { str.append(I18NHelper.getMessage(messages, "sqlstore.sql.generator.statement.sqlStatement") ); //NOI18N - str.append("<").append(sqlText).append("> "); // NOI18N + str.append("<").append(sqlText).append("> "); if (input != null && input.length > 0) { str.append(I18NHelper.getMessage(messages, - "sqlstore.sql.generator.statement.withinputvalues")); // NOI18N + "sqlstore.sql.generator.statement.withinputvalues")); for (int i = 0; i < input.length; i++) { if (i > 0) { - str.append(", "); // NOI18N + str.append(", "); } Object inputValue = input[i]; if (inputValue == null) { - str.append(""); // NOI18N + str.append(""); } else { str.append(inputValue.getClass().getName()); - str.append(":"); // NOI18N + str.append(":"); str.append(inputValue.toString()); } } } else { str.append(I18NHelper.getMessage(messages, - "sqlstore.sql.generator.statement.withnoinputvalues")); // NOI18N + "sqlstore.sql.generator.statement.withnoinputvalues")); } return str.toString(); diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateQueryPlan.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateQueryPlan.java index 66b70160dc6..fc43481886f 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateQueryPlan.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateQueryPlan.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 */ -/* - * UpdateQueryPlan.java - * - * Created on October 3, 2001 - * - */ - package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; import com.sun.jdo.api.persistence.support.JDOFatalInternalException; @@ -91,8 +85,8 @@ private void addColumn(LocalFieldDesc fieldDesc, Object value) { return; } - for (Iterator iter = fieldDesc.getColumnElements(); iter.hasNext(); ) { - ColumnElement columnElement = (ColumnElement) iter.next(); + for (Iterator iter = fieldDesc.getColumnElements(); iter.hasNext(); ) { + ColumnElement columnElement = iter.next(); TableElement tableElement = columnElement.getDeclaringTable(); if (tableElement == null) { @@ -121,6 +115,7 @@ private void addColumn(LocalFieldDesc fieldDesc, Object value) { } } + @Override public void build() { build(false); } @@ -133,7 +128,9 @@ public void build() { */ public void build(boolean batch) { - if ((status & ST_BUILT) > 0) return; + if ((status & ST_BUILT) > 0) { + return; + } this.batch = batch; @@ -153,14 +150,15 @@ public void build(boolean batch) { private void generateStatements() { // For insert and delete we build a statement for each table if ((action == ACT_DELETE) || (action == ACT_INSERT)) { - Iterator iter = config.getTables(); + Iterator iter = config.getTables(); while (iter.hasNext()) { - TableDesc t = (TableDesc) iter.next(); + TableDesc t = iter.next(); // Skip join tables if (!t.isJoinTable()) { - if (findQueryTable(t.getTableElement()) == null) + if (findQueryTable(t.getTableElement()) == null) { addStatement(addQueryTable(t)); + } } } @@ -170,7 +168,7 @@ private void generateStatements() { int j = statements.size() - 1; while (i < j) { - Statement s = (Statement) statements.get(i); + Statement s = statements.get(i); statements.set(i, statements.get(j)); statements.set(j, s); i++; @@ -198,24 +196,24 @@ private void addColumns() { } private void addConstraints(UpdateStatement statement, - ArrayList localFields, - ArrayList foreignFields, - ArrayList columns) { + List localFields, + List foreignFields, + List columns) { boolean isBeforeImageRequired = updateDesc.isBeforeImageRequired(); for (int i = 0; i < localFields.size(); i++) { LocalFieldDesc lf = (LocalFieldDesc) localFields.get(i); LocalFieldDesc ff = (LocalFieldDesc) foreignFields.get(i); - ColumnElement ce = (ColumnElement) columns.get(i); + ColumnElement ce = columns.get(i); addConstraint(statement, lf, ff, ce, isBeforeImageRequired); } // Add the constraint on the version field if needed. if (getConfig().hasVersionConsistency() && action != ACT_INSERT) { - QueryTable table = (QueryTable) statement.getQueryTables().get(0); + QueryTable table = statement.getQueryTables().get(0); LocalFieldDesc versionField = table.getTableDesc().getVersionField(); - ColumnElement ce = (ColumnElement) versionField.getColumnElements().next(); + ColumnElement ce = versionField.getColumnElements().next(); addConstraint(statement, versionField, versionField, ce, false); } @@ -245,28 +243,28 @@ private void addConstraint(UpdateStatement statement, } private void addSecondaryTableConstraint(UpdateStatement statement) { - QueryTable table = (QueryTable) statement.getQueryTables().get(0); + QueryTable table = statement.getQueryTables().get(0); ReferenceKeyDesc key = table.getTableDesc().getPrimaryTableKey(); - ArrayList localFields = key.getReferencingKey().getFields(); - ArrayList foreignFields = key.getReferencedKey().getFields(); - ArrayList columns = key.getReferencingKey().getColumns(); + List localFields = key.getReferencingKey().getFields(); + List foreignFields = key.getReferencedKey().getFields(); + List columns = key.getReferencingKey().getColumns(); addConstraints(statement, localFields, foreignFields, columns); } private void addBasetableConstraint(UpdateStatement statement) { - QueryTable table = (QueryTable) statement.getQueryTables().get(0); + QueryTable table = statement.getQueryTables().get(0); KeyDesc key = table.getTableDesc().getKey(); - ArrayList localFields = key.getFields(); - ArrayList columns = key.getColumns(); + List localFields = key.getFields(); + List columns = key.getColumns(); addConstraints(statement, localFields, localFields, columns); } private void processRelatedStatements(UpdateStatement statement) { - ArrayList secondaryTableStatements = statement.getSecondaryTableStatements(); + List secondaryTableStatements = statement.getSecondaryTableStatements(); if (secondaryTableStatements != null) { for (int i = 0; i < secondaryTableStatements.size(); i++) { @@ -281,6 +279,7 @@ private void processRelatedStatements(UpdateStatement statement) { } } + @Override protected void processStatements() { int size = statements.size(); @@ -290,52 +289,59 @@ protected void processStatements() { for (int i = 0; i < size; i++) { UpdateStatement statement = (UpdateStatement) statements.get(i); - if (!statement.isConstraintAdded()) + if (!statement.isConstraintAdded()) { processRelatedStatements(statement); + } } } UpdateStatement masterStatement = null; - if (size == 1) + if (size == 1) { masterStatement = (UpdateStatement) statements.get(0); - else { + } else { // Look for the master statement. It should be the one // with no constraints added. for (int i = 0; i < size; i++) { masterStatement = (UpdateStatement) statements.get(i); - if (!masterStatement.isConstraintAdded()) break; + if (!masterStatement.isConstraintAdded()) { + break; + } } } - if (action != ACT_INSERT) + if (action != ACT_INSERT) { addBasetableConstraint(masterStatement); + } - if ((action != ACT_INSERT) && (updateDesc.getConcurrency() != null)) + if ((action != ACT_INSERT) && (updateDesc.getConcurrency() != null)) { updateDesc.getConcurrency().update(this); + } } private void processJoinTables() { - Collection fields = updateDesc.getUpdatedJoinTableFields(); + Collection fields = updateDesc.getUpdatedJoinTableFields(); - if (fields == null) return; + if (fields == null) { + return; + } - Iterator fieldIter = fields.iterator(); + Iterator fieldIter = fields.iterator(); - ArrayList deleteStatements = new ArrayList(); - ArrayList insertStatements = new ArrayList(); + List deleteStatements = new ArrayList<>(); + List insertStatements = new ArrayList<>(); while (fieldIter.hasNext()) { - ForeignFieldDesc f = (ForeignFieldDesc) fieldIter.next(); - Collection descs = updateDesc.getUpdateJoinTableDescs(f); - Iterator descIter = descs.iterator(); + ForeignFieldDesc f = fieldIter.next(); + Collection descs = updateDesc.getUpdateJoinTableDescs(f); + Iterator descIter = descs.iterator(); - ColumnElement c = (ColumnElement) f.assocLocalColumns.get(0); + ColumnElement c = f.assocLocalColumns.get(0); QueryTable t = addQueryTable(config.findTableDesc(c.getDeclaringTable())); while (descIter.hasNext()) { - UpdateJoinTableDesc desc = (UpdateJoinTableDesc) descIter.next(); + UpdateJoinTableDesc desc = descIter.next(); int action = getAction(desc.getAction()); UpdateStatement s = (UpdateStatement) createStatement(t); @@ -362,12 +368,14 @@ private void processJoinTables() { // All join table delete statements have to go first and all // join table insert statements have to go last. - ArrayList oldStatements = statements; - statements = deleteStatements; + List oldStatements = statements; + statements = new ArrayList<>(); + statements.addAll(deleteStatements); statements.addAll(oldStatements); statements.addAll(insertStatements); } + @Override protected Statement newStatement() { return new UpdateStatement(store.getVendorType(), this, batch); } @@ -381,8 +389,9 @@ public boolean checkBatchThreshold(Transaction tran) { for (int i = 0, size = statements.size(); i < size; i++) { UpdateStatement updateStatement = (UpdateStatement) statements.get(i); - if (updateStatement.exceedsBatchThreshold(tran)) + if (updateStatement.exceedsBatchThreshold(tran)) { return true; + } } return false; } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateStatement.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateStatement.java index 846cddbf715..d1fc280a8be 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateStatement.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/sql/generator/UpdateStatement.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 */ -/* - * UpdateStatement.java - * - * Created on October 3, 2001 - * - */ package com.sun.jdo.spi.persistence.support.sqlstore.sql.generator; @@ -48,16 +43,16 @@ public class UpdateStatement extends Statement implements Cloneable { public int minAffectedRows; - private Map dbStatementCache = new HashMap(); + private Map dbStatementCache = new HashMap<>(); /** The UpdateQueryplan */ UpdateQueryPlan plan; /** List of ColumnRef for the where clause used during batch. */ - private List columnRefsForWhereClause; + private List columnRefsForWhereClause; /** List of version columns */ - private List versionColumns; + private List versionColumns; /** Flag indicating whether we use batch. */ private boolean batch = false; @@ -70,7 +65,7 @@ public class UpdateStatement extends Statement implements Cloneable { /** Name of the USE_BATCH property. */ public static final String UPDATE_VERSION_COL_PROPERTY = - "com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UPDATE_VERSION_COL"; // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.sql.generator.UPDATE_VERSION_COL"; /** * Property to swich on/off updating of version col. @@ -78,13 +73,13 @@ public class UpdateStatement extends Statement implements Cloneable { * property is not specified. */ private static final boolean UPDATE_VERSION_COL = Boolean.valueOf( - System.getProperty(UPDATE_VERSION_COL_PROPERTY, "true")).booleanValue(); // NOI18N + System.getProperty(UPDATE_VERSION_COL_PROPERTY, "true")).booleanValue(); public UpdateStatement(DBVendorType vendorType, UpdateQueryPlan plan, boolean batch) { super(vendorType); this.plan = plan; - columnRefsForWhereClause = new ArrayList(); + columnRefsForWhereClause = new ArrayList<>(); this.batch = batch; minAffectedRows = 1; } @@ -109,8 +104,8 @@ private void calculateWhereClauseColumnRefIndexes() { // NOTE, the sqlstore processes the constraints in reverse order, // so start with the last index and decrement int nextIndex = columns.size() + columnRefsForWhereClause.size(); - for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { - ColumnRef columnRef = (ColumnRef)i.next(); + for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { + ColumnRef columnRef = i.next(); columnRef.setIndex(nextIndex--); } } @@ -124,6 +119,7 @@ public void markConstraintAdded() { } /** @inheritDoc */ + @Override public QueryPlan getQueryPlan() { return plan; } @@ -131,33 +127,34 @@ public QueryPlan getQueryPlan() { /** * @inheritDoc */ + @Override protected void generateStatementText() { statementText = new StringBuffer(); StringBuffer columnList = generateColumnText(); StringBuffer constraint = processConstraints(); - String tableName = ((QueryTable) tableList.get(0)).getTableDesc().getName(); + String tableName = tableList.get(0).getTableDesc().getName(); // Create the query filling in the column list, table name, etc. switch (action) { case QueryPlan.ACT_UPDATE: - statementText.append("update ");// NOI18N + statementText.append("update "); appendQuotedText(statementText, tableName); - statementText.append(" set ").append(columnList).append(" where ").append(constraint); // NOI18N + statementText.append(" set ").append(columnList).append(" where ").append(constraint); break; case QueryPlan.ACT_DELETE: - statementText.append("delete from ");// NOI18N + statementText.append("delete from "); appendQuotedText(statementText, tableName); - statementText.append(" where ").append(constraint); // NOI18N + statementText.append(" where ").append(constraint); break; case QueryPlan.ACT_INSERT: - statementText.append("insert into ");// NOI18N + statementText.append("insert into "); appendQuotedText(statementText, tableName); - statementText.append("(").append(columnList).// NOI18N - append(") values ").append("(").append(values).append(")"); // NOI18N + statementText.append("(").append(columnList). + append(") values ").append("(").append(values).append(")"); break; } @@ -169,23 +166,23 @@ private StringBuffer generateColumnText() { int numValues = -1; for (int i = 0; i < columns.size(); i++) { - ColumnRef c = (ColumnRef) columns.get(i); + ColumnRef c = columns.get(i); if (columnList.length() > 0) { - columnList.append(", "); // NOI18N + columnList.append(", "); } switch (action) { case QueryPlan.ACT_UPDATE: appendQuotedText(columnList, c.getName()); - columnList.append("= ?"); // NOI18N + columnList.append("= ?"); break; case QueryPlan.ACT_INSERT: appendQuotedText(columnList, c.getName()); if (i == 0) { - values = new StringBuffer().append(" ?"); // NOI18N + values = new StringBuffer().append(" ?"); } else { - values.append(", ?"); // NOI18N + values.append(", ?"); } break; } @@ -196,8 +193,7 @@ private StringBuffer generateColumnText() { ((action == QueryPlan.ACT_UPDATE) || (action == QueryPlan.ACT_INSERT))) { numValues = numValues + 1; - InputValue val = new InputValue(c.getValue(), c.getColumnElement()); - inputDesc.values.add(numValues, val); + inputDesc.values.add(numValues, new InputValue(c.getValue(), c.getColumnElement())); } } @@ -217,7 +213,7 @@ private void appendVersionColumnUpdateClause(StringBuffer setClause) { if (versionColumns != null) { for (int i = 0; i < versionColumns.size(); i++) { - ColumnElement columnElement = (ColumnElement) versionColumns.get(i); + ColumnElement columnElement = versionColumns.get(i); String columnName = columnElement.getName().getName(); setClause.append(", "); appendQuotedText(setClause, columnName); @@ -233,16 +229,16 @@ private void appendVersionColumnUpdateClause(StringBuffer setClause) { public void addLocalConstraints(int action, ForeignFieldDesc f, SQLStateManager sm) { for (int i = 0; i < f.localFields.size(); i++) { - LocalFieldDesc lf = (LocalFieldDesc) f.localFields.get(i); + LocalFieldDesc lf = f.localFields.get(i); if (action == QueryPlan.ACT_INSERT) { // For inserts into the join table, we get the values we are inserting // for the parent object and the added object. - ColumnElement lc = (ColumnElement) f.assocLocalColumns.get(i); + ColumnElement lc = f.assocLocalColumns.get(i); addColumn(lc, lf.getValue(sm)); } else if (action == QueryPlan.ACT_DELETE) { - LocalFieldDesc alf = (LocalFieldDesc) f.assocLocalFields.get(i); + LocalFieldDesc alf = f.assocLocalFields.get(i); // For deletes from the join table, we get the constraint values // from the parent object and the remove object. @@ -253,16 +249,16 @@ public void addLocalConstraints(int action, ForeignFieldDesc f, SQLStateManager public void addForeignConstraints(int action, ForeignFieldDesc f, SQLStateManager sm) { for (int i = 0; i < f.foreignFields.size(); i++) { - LocalFieldDesc ff = (LocalFieldDesc) f.foreignFields.get(i); + LocalFieldDesc ff = f.foreignFields.get(i); if (action == QueryPlan.ACT_INSERT) { // For inserts into the join table, we get the values we are inserting // for the parent object and the added object. - ColumnElement fc = (ColumnElement) f.assocForeignColumns.get(i); + ColumnElement fc = f.assocForeignColumns.get(i); addColumn(fc, ff.getValue(sm)); } else if (action == QueryPlan.ACT_DELETE) { - LocalFieldDesc aff = (LocalFieldDesc) f.assocForeignFields.get(i); + LocalFieldDesc aff = f.assocForeignFields.get(i); // For deletes from the join table, we get the constraint values // from the parent object and the remove object. @@ -275,10 +271,12 @@ public void addForeignConstraints(int action, ForeignFieldDesc f, SQLStateManage * Redefines processConstraintValue in order to skip the creation of * an InputValue in the case of batch. */ + @Override protected void processConstraintValue(ConstraintValue node, StringBuffer result) { - result.append("?"); // NOI18N - if (!batch) + result.append("?"); + if (!batch) { generateInputValueForConstraintValueNode(node); + } } /** @@ -297,7 +295,7 @@ public DBStatement getDBStatement(Transaction tran, Connection conn) synchronized (dbStatementCache) { // dbStatement cachelookup - dbStatement = (DBStatement)dbStatementCache.get(tran); + dbStatement = dbStatementCache.get(tran); if (dbStatement == null) { dbStatement = new DBStatement(conn, getText(), @@ -315,7 +313,7 @@ public boolean exceedsBatchThreshold(Transaction tran) { synchronized (dbStatementCache) { - DBStatement dbStatement = (DBStatement)dbStatementCache.get(tran); + DBStatement dbStatement = dbStatementCache.get(tran); return (dbStatement != null) && dbStatement.exceedsBatchThreshold(); } } @@ -329,7 +327,7 @@ public DBStatement removeDBStatement(Transaction tran) { synchronized (dbStatementCache) { - DBStatement s = (DBStatement)dbStatementCache.remove(tran); + DBStatement s = dbStatementCache.remove(tran); return s; } } @@ -339,12 +337,12 @@ public void bindInputColumns(DBStatement s, throws SQLException { // bind set clause (if necessary) - for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) { - bindInputColumn(s, (ColumnRef)i.next(), updateDesc, false ); + for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) { + bindInputColumn(s, i.next(), updateDesc, false ); } // bind where clause (if necessary) - for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { - bindInputColumn(s, (ColumnRef) i.next(), updateDesc, + for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { + bindInputColumn(s, i.next(), updateDesc, updateDesc.isBeforeImageRequired()); } @@ -376,14 +374,14 @@ private void bindInputColumn(DBStatement stmt, private Object[] getInputValues(UpdateObjectDescImpl updateDesc) { Object[] inputValues = new Object[getColumnRefs().size() + columnRefsForWhereClause.size()]; - for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) { - ColumnRef columnRef = (ColumnRef)i.next(); + for (Iterator i = getColumnRefs().iterator(); i.hasNext(); ) { + ColumnRef columnRef = i.next(); // columnRef's index are 1 based. inputValues[columnRef.getIndex() - 1] = getInputValue(updateDesc, columnRef, false); } final boolean getBeforeValue = updateDesc.isBeforeImageRequired(); - for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { - ColumnRef columnRef = (ColumnRef)i.next(); + for (Iterator i = columnRefsForWhereClause.iterator(); i.hasNext(); ) { + ColumnRef columnRef = i.next(); inputValues[columnRef.getIndex() - 1] = getInputValue(updateDesc, columnRef, getBeforeValue); } return inputValues; @@ -419,9 +417,8 @@ private static Object getInputValue(UpdateObjectDescImpl updateDesc, // as they're incremented internally after each flush. // Version fields must not be modified from "outside". value = updateDesc.getAfterValue(field); - } else { - value = getBeforeValue ? updateDesc.getBeforeValue(field) : - updateDesc.getAfterValue(field); + } else { + value = getBeforeValue ? updateDesc.getBeforeValue(field) : updateDesc.getAfterValue(field); } return value; @@ -429,7 +426,7 @@ private static Object getInputValue(UpdateObjectDescImpl updateDesc, public void addVersionColumn(ColumnElement versionColumn) { if (versionColumns == null) { - versionColumns = new ArrayList(); + versionColumns = new ArrayList<>(); } versionColumns.add(versionColumn); } diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/state/LifeCycleState.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/state/LifeCycleState.java index 9047c137f29..4f7eaa97f9c 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/state/LifeCycleState.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/state/LifeCycleState.java @@ -21,13 +21,15 @@ package com.sun.jdo.spi.persistence.support.sqlstore.state; import com.sun.jdo.api.persistence.support.JDOUserException; -import com.sun.jdo.spi.persistence.support.sqlstore.LogHelperStateManager; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; import java.util.ResourceBundle; import org.glassfish.persistence.common.I18NHelper; +import static com.sun.jdo.spi.persistence.support.sqlstore.LogHelperSQLStore.RESOURCE_BUNDLE; +import static java.lang.System.Logger.Level.DEBUG; + public abstract class LifeCycleState { @@ -35,7 +37,7 @@ public abstract class LifeCycleState { * I18N message handler */ protected final static ResourceBundle messages = I18NHelper.loadBundle( - "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", // NOI18N + "com.sun.jdo.spi.persistence.support.sqlstore.Bundle", LifeCycleState.class.getClassLoader()); protected boolean isPersistent; @@ -102,8 +104,7 @@ public abstract class LifeCycleState { private static LifeCycleState stateTypes[]; - //The logger - private static Logger logger = LogHelperStateManager.getLogger(); + private static final Logger LOG = System.getLogger(LifeCycleState.class.getName(), RESOURCE_BUNDLE); // ****************************************************************** // Initialisation stuff @@ -185,10 +186,7 @@ protected static void initLifeCycleState() { * @return the type as LifeCycleState object */ public static LifeCycleState getLifeCycleState(int state) { - if (logger.isLoggable(Logger.FINER)) { - logger.finer("sqlstore.state.lifecyclestate.initial",stateTypes[state]); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.state.lifecyclestate.initial", stateTypes[state]); return stateTypes[state]; } @@ -253,7 +251,7 @@ public LifeCycleState transitionWriteField(boolean transactionActive) { protected void assertTransaction(boolean transactionActive) { if (!transactionActive) { throw new JDOUserException(I18NHelper.getMessage(messages, - "jdo.lifecycle.xactnotactive")); // NOI18N + "jdo.lifecycle.xactnotactive")); } } @@ -376,48 +374,45 @@ public int getUpdateAction() { * Life Cycle State change */ public LifeCycleState changeState(int newStateType) { - if (logger.isLoggable(Logger.FINER)) { - Object[] items = new Object[] {this,stateTypes[newStateType]}; - logger.finer("sqlstore.state.lifecyclestate.changestate",items); // NOI18N - } - + LOG.log(DEBUG, "sqlstore.state.lifecyclestate.changestate", this, stateTypes[newStateType]); return (stateTypes[newStateType]); } + @Override public String toString() { switch (stateType) { case HOLLOW: - return "HOLLOW"; // NOI18N + return "HOLLOW"; case P_NON_TX: - return "P_NON_TX"; // NOI18N + return "P_NON_TX"; case P_CLEAN: - return "P_CLEAN"; // NOI18N + return "P_CLEAN"; case P_DIRTY: - return "P_DIRTY"; // NOI18N + return "P_DIRTY"; case P_NEW: - return "P_NEW"; // NOI18N + return "P_NEW"; case P_NEW_FLUSHED: - return "P_NEW_FLUSHED"; // NOI18N + return "P_NEW_FLUSHED"; case P_NEW_FLUSHED_DELETED: - return "P_NEW_FLUSHED_DELETED"; // NOI18N + return "P_NEW_FLUSHED_DELETED"; case P_NEW_DELETED: - return "P_NEW_DELETED"; // NOI18N + return "P_NEW_DELETED"; case P_DELETED: - return "P_DELETED"; // NOI18N + return "P_DELETED"; case P_DELETED_FLUSHED: - return "P_DELETED_FLUSHED"; // NOI18N + return "P_DELETED_FLUSHED"; case AP_NEW: - return "AP_NEW"; // NOI18N + return "AP_NEW"; case AP_NEW_PENDING: - return "AP_NEW_PENDING"; // NOI18N + return "AP_NEW_PENDING"; case AP_NEW_FLUSHED: - return "AP_NEW_FLUSHED"; // NOI18N + return "AP_NEW_FLUSHED"; case AP_NEW_FLUSHED_PENDING: - return "AP_NEW_FLUSHED_PENDING"; // NOI18N + return "AP_NEW_FLUSHED_PENDING"; case AP_NEW_FLUSHED_DELETED: - return "AP_NEW_FLUSHED_DELETED"; // NOI18N + return "AP_NEW_FLUSHED_DELETED"; case AP_NEW_DELETED: - return "AP_NEW_DELETED"; //NOI18N + return "AP_NEW_DELETED"; } return null; diff --git a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/utility/AugmentationTest.java b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/utility/AugmentationTest.java index 720e4cf95d0..9b1488a5aa7 100644 --- a/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/utility/AugmentationTest.java +++ b/appserver/persistence/cmp/support-sqlstore/src/main/java/com/sun/jdo/spi/persistence/support/sqlstore/utility/AugmentationTest.java @@ -47,18 +47,20 @@ public class AugmentationTest static final void affirm(boolean cond) { - if (debug && !cond) + if (debug && !cond) { throw new RuntimeException("affirmion failed."); + } } static final void affirm(Object obj) { - if (debug && obj == null) + if (debug && obj == null) { throw new RuntimeException("affirmion failed: obj = null"); + } } static String toString(int mods, - Class type, + Class type, String name) { final StringBuffer s = new StringBuffer(); @@ -72,7 +74,7 @@ static String toString(int mods, static String toString(int mods, String name, - Class[] params) + Class[] params) { final StringBuffer s = new StringBuffer(); s.append(Modifier.toString(mods)); @@ -82,17 +84,18 @@ static String toString(int mods, final int j = params.length - 1; for (int i = 0; i <= j; i++) { s.append(params[i].getName()); - if (i < j) + if (i < j) { s.append(","); + } } s.append(")"); return s.toString(); } static String toString(int mods, - Class result, + Class result, String name, - Class[] params) + Class[] params) { final StringBuffer s = new StringBuffer(); s.append(Modifier.toString(mods)); @@ -104,8 +107,9 @@ static String toString(int mods, final int j = params.length - 1; for (int i = 0; i <= j; i++) { s.append(params[i].getName()); - if (i < j) + if (i < j) { s.append(","); + } } s.append(")"); return s.toString(); @@ -117,9 +121,8 @@ static String toString(int mods, boolean verbose; boolean requirePC; - List classes; String className; - Class classClass; + Class classClass; public AugmentationTest() {} @@ -136,14 +139,16 @@ final void println(String msg) final void verbose() { - if (verbose) + if (verbose) { out.println(); + } } final void verbose(String msg) { - if (verbose) + if (verbose) { out.println(msg); + } } public int testLoadingClass() @@ -169,9 +174,9 @@ public int testLoadingClass() } } - int implementsInterface(Class intf) + int implementsInterface(Class intf) { - final Class[] interfaces = classClass.getInterfaces(); + final Class[] interfaces = classClass.getInterfaces(); for (int i = interfaces.length - 1; i >= 0; i--) { if (interfaces[i].equals(intf)) { verbose("+++ implements interface: " + intf.getName()); @@ -183,7 +188,7 @@ int implementsInterface(Class intf) } int hasField(int mods, - Class type, + Class type, String name) { try { @@ -207,10 +212,10 @@ int hasField(int mods, } int hasConstructor(int mods, - Class[] params) + Class[] params) { try { - final Constructor ctor = classClass.getConstructor(params); + final Constructor ctor = classClass.getConstructor(params); if (ctor.getModifiers() != mods) { println("!!! ERROR: constructor declaration: "); @@ -230,9 +235,9 @@ int hasConstructor(int mods, } int hasMethod(int mods, - Class result, + Class result, String name, - Class[] params) + Class[] params) { try { final Method method = classClass.getMethod(name, params); @@ -343,8 +348,9 @@ public int hasGenericAugmentation() return ERROR; } - if (j > NEGATIVE) + if (j > NEGATIVE) { res = j; + } } if (res > NEGATIVE) { @@ -404,8 +410,9 @@ public int hasSpecificAugmentation() return ERROR; } - if (j > NEGATIVE) + if (j > NEGATIVE) { res = j; + } } if (res > NEGATIVE) { @@ -480,15 +487,15 @@ public int testPCFeasibility() } //verbose("get superclass ..."); - final Class superClass = classClass.getSuperclass(); + final Class superClass = classClass.getSuperclass(); if (superClass == null) { println("!!! ERROR: specified class doesn't have super class"); status = ERROR; } else { try { //verbose("get superclass' default constructor ..."); - final Class[] params = new Class[]{}; - Constructor sctor = superClass.getConstructor(params); + final Class[] params = new Class[]{}; + Constructor sctor = superClass.getConstructor(params); } catch (NoSuchMethodException ex) { println("!!! ERROR: super class '" + superClass.getName() + "' doesn't provide default constructor"); @@ -510,8 +517,8 @@ public int testJdoConstructor() try { //verbose("get jdo constructor ..."); - final Class[] params = new Class[]{StateManager.class}; - final Constructor ctor = classClass.getConstructor(params); + final Class[] params = new Class[]{StateManager.class}; + final Constructor ctor = classClass.getConstructor(params); //verbose("create new instance by jdo constructor ..."); final Object[] args = new Object[]{null}; @@ -680,7 +687,7 @@ static public void main(String[] argv) // parse args boolean verbose = false; boolean requirePC = false; - List classes = new ArrayList(); + List classes = new ArrayList<>(); for (int i = 0; i < argv.length; i++) { String arg = argv[i]; if (arg.equals("-h") || arg.equals("--help")) { @@ -721,8 +728,9 @@ static public void main(String[] argv) out.println(" verbose = " + verbose); out.println(" requirePC = " + requirePC); out.print(" classes ="); - for (int i = 0; i < classes.size(); i++) + for (int i = 0; i < classes.size(); i++) { out.print(" " + classes.get(i)); + } out.println(); } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/BucketizedHashtable.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/BucketizedHashtable.java index 665258c1241..22fe2f90709 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/BucketizedHashtable.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/BucketizedHashtable.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 @@ -30,9 +31,9 @@ * * @author Shing Wai Chan */ -public class BucketizedHashtable implements Cloneable, Map, Serializable { +public class BucketizedHashtable implements Cloneable, Map, Serializable { private int bucketSize; - private Hashtable[] hashtables = null; + private Hashtable[] hashtables = null; /** * Constructs a new, empty BucketizedHashtable with the specified @@ -41,8 +42,7 @@ public class BucketizedHashtable implements Cloneable, Map, Serializable { * @param initialCapacity the initial capacity of BucketizedHashtable * @param loadFactor the load factor of hashtable */ - public BucketizedHashtable(int bucketSize, int initialCapacity, - float loadFactor) { + public BucketizedHashtable(int bucketSize, int initialCapacity, float loadFactor) { if (bucketSize <= 0 || initialCapacity < 0) { throw new IllegalArgumentException(); } @@ -53,11 +53,10 @@ public BucketizedHashtable(int bucketSize, int initialCapacity, // always round up to the nearest integer so that it has at // least the initialCapacity - int initialHashtableSize = - (int)Math.ceil((double)initialCapacity / bucketSize); + int initialHashtableSize = (int) Math.ceil((double) initialCapacity / bucketSize); for (int i = 0; i < bucketSize; i++) { - hashtables[i] = new Hashtable(initialHashtableSize, loadFactor); + hashtables[i] = new Hashtable<>(initialHashtableSize, loadFactor); } } @@ -96,7 +95,8 @@ public BucketizedHashtable() { * @param key a key in the hashtable * @return the value to which the specified key is mapped. */ - public Object get(Object key) { + @Override + public V get(Object key) { return hashtables[getBucketIndex(key)].get(key); } @@ -106,7 +106,8 @@ public Object get(Object key) { * @return the value to which the key had been mapped, * or null if the key did not have a mapping. */ - public Object remove(Object key) { + @Override + public V remove(Object key) { return hashtables[getBucketIndex(key)].remove(key); } @@ -119,7 +120,8 @@ public Object remove(Object key) { * @return the previous value of the specified key in hashtables, * or null if it did not have one. */ - public Object put(Object key, Object value) { + @Override + public V put(K key, V value) { return hashtables[getBucketIndex(key)].put(key, value); } @@ -127,9 +129,10 @@ public Object put(Object key, Object value) { * @param t BucketizedHashtable * or a Map with a supported operation entrySet */ - public void putAll(Map t) { + @Override + public void putAll(Map t) { if (t instanceof BucketizedHashtable) { - BucketizedHashtable bt = (BucketizedHashtable)t; + BucketizedHashtable bt = (BucketizedHashtable) t; for (int i = 0; i < bt.bucketSize; i++) { putAllFromMapWithEntrySet(bt.hashtables[i]); } @@ -143,6 +146,7 @@ public void putAll(Map t) { * @return true if and only if the specified object is a key in one of * of the hashtables */ + @Override public boolean containsKey(Object key) { return hashtables[getBucketIndex(key)].containsKey(key); } @@ -152,6 +156,7 @@ public boolean containsKey(Object key) { * @return true if and only if the specified object is a value in one of * of the hashtables */ + @Override public boolean containsValue(Object value) { for (int i = 0; i < bucketSize; i++) { if (hashtables[i].containsValue(value)) { @@ -164,6 +169,7 @@ public boolean containsValue(Object value) { /** * @return the total number of key-value mappings of all buckets */ + @Override public int size() { int totalSize = 0; for (int i = 0; i < bucketSize; i++) { @@ -175,6 +181,7 @@ public int size() { /** * @return the hash code value for this map */ + @Override public int hashCode() { int h = 0; for (int i = 0; i < bucketSize; i++) { @@ -186,6 +193,7 @@ public int hashCode() { /** * @return true if this map contains no key-value mappings */ + @Override public boolean isEmpty() { for (int i = 0; i < bucketSize; i++) { if (!hashtables[i].isEmpty()) { @@ -198,6 +206,7 @@ public boolean isEmpty() { /** * Clears this BucketizedHashtable so that it contains no key. */ + @Override public void clear() { for (int i = 0; i < bucketSize; i++) { hashtables[i].clear(); @@ -210,7 +219,8 @@ public void clear() { * @return a set of Map.Entry when bucketSet equal 1 * @exception UnsupportedOperationException when bucketSize is greater one */ - public Set entrySet() { + @Override + public Set> entrySet() { if (bucketSize == 1) { return hashtables[0].entrySet(); } else { @@ -224,7 +234,8 @@ public Set entrySet() { * @return a set of keys when bucketSet equal 1 * @exception UnsupportedOperationException when bucketSize is greater one */ - public Set keySet() { + @Override + public Set keySet() { if (bucketSize == 1) { return hashtables[0].keySet(); } else { @@ -238,7 +249,8 @@ public Set keySet() { * @return a collection of values when bucketSet equal 1 * @exception UnsupportedOperationException when bucketSize is greater one */ - public Collection values() { + @Override + public Collection values() { if (bucketSize == 1) { return hashtables[0].values(); } else { @@ -251,6 +263,7 @@ public Collection values() { * @return true if the specified object is a BucketizedHashtable * with hashtables represent the same set of mappings. */ + @Override public boolean equals(Object o) { if (o == this) { return true; @@ -259,7 +272,7 @@ public boolean equals(Object o) { if (!(o instanceof BucketizedHashtable)) { return false; } - BucketizedHashtable bt = (BucketizedHashtable)o; + BucketizedHashtable bt = (BucketizedHashtable) o; if (bt.bucketSize != bucketSize || bt.size() != size()) { return false; } @@ -278,13 +291,14 @@ public boolean equals(Object o) { * The keys and values are not cloned. * @return a clone of BucketizedHashtable */ + @Override public Object clone() { try { - BucketizedHashtable bt = (BucketizedHashtable)super.clone(); + BucketizedHashtable bt = (BucketizedHashtable) super.clone(); bt.bucketSize = bucketSize; bt.hashtables = new Hashtable[bucketSize]; for (int i = 0; i < bucketSize; i++) { - bt.hashtables[i] = (Hashtable)hashtables[i].clone(); + bt.hashtables[i] = (Hashtable) hashtables[i].clone(); } return bt; } catch (CloneNotSupportedException e) { @@ -297,6 +311,7 @@ public Object clone() { /** * @return a string representation of this BucketizedHashtable */ + @Override public String toString() { StringBuffer buf = new StringBuffer("["); // NOI18N //bucketSize always >= 1 @@ -312,10 +327,10 @@ public String toString() { /** * @param t Map with a supported entrySet operation */ - private void putAllFromMapWithEntrySet(Map t) { - Iterator iter = t.entrySet().iterator(); + private void putAllFromMapWithEntrySet(Map t) { + Iterator> iter = t.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry e = (Map.Entry)iter.next(); + Entry e = iter.next(); put(e.getKey(), e.getValue()); } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/Bundle.properties b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/Bundle.properties deleted file mode 100644 index d4c70902e08..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/Bundle.properties +++ /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 -# - -# resource bundle for runtime messages -# key consists of: ... -# - is optional, package under runtime -# - class name -# - method name -# - short description (use _ to represent space) -# all keys should be in lowercase -# -# The message ID for a message in persistence is derived as follows: -# JDO<2_digit_bundle_prefix><1_digit_section_number><2_digit_serial_number> -# -# The 2 digit prefix for this bundle is 81. -# -# When adding a new message: -# 1. Please make sure that you add the message to the end of the file. -# 2. Please add message ID to any user visible message. -# 3. The message ID for the new message = message ID for the last numbered -# message in the file + 1. -# 4. Please do not change message number for existing messages. These numbers -# are potentially mapped to more explanation about the message for the end -# user. -# - -############################################################################### -# -# Message ID Range: JDO81000 - JDO81999 -############################################################################### -utility.nullsemaphore.constructor=NullSemaphore constructor() for {0}. -utility.nullsemaphore.acquire=NullSemaphore.acquire() for {0}. -utility.nullsemaphore.release=NullSemaphore.release() for {0}. - -utility.semaphoreimpl.acquire=SemaphoreImpl.acquire() for {0}, thread = {1} with _lockCounter = {2}. -utility.semaphoreimpl.gotlock=SemaphoreImpl.acquire() for {0}, got for thread = {1} with _lockCounter = {2}. -utility.semaphoreimpl.release=SemaphoreImpl.release() for {0}, thread = {1} with _lockCounter = {2}. -utility.semaphoreimpl.wrongthread=SemaphoreImpl.release() wrong thread for {0}, thread = {1}. - diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/JavaTypeHelper.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/JavaTypeHelper.java index c527dabf8b2..a84442cb8d4 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/JavaTypeHelper.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/JavaTypeHelper.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 */ -/* - * JavaTypeHelper.java - * - * Created on January 22, 2002, 3:39 PM - */ - package com.sun.jdo.spi.persistence.utility; import java.util.HashMap; @@ -30,25 +25,24 @@ * extraction of a short (non-qualified) name from a fully qualified class * name, and various wrapper and primitive type methods. * - * @author Rochelle Raccah + * @author Rochelle Raccah 2002 */ public class JavaTypeHelper { /** Map of primitive to wrapper classes */ - private final static Map _primitiveToWrappers; + private final static Map, Class> _primitiveToWrappers; /** Map of primitive names to primitive classes */ - private final static Map _primitiveNamesToPrimitives; + private final static Map> _primitiveNamesToPrimitives; /** Map of primitive names to wrapper names */ - private final static Map _primitiveNamesToWrapperNames; + private final static Map _primitiveNamesToWrapperNames; /** Map of wrapper classes to primitive names*/ - private final static Map _wrapperToPrimitiveNames; + private final static Map, String> _wrapperToPrimitiveNames; - static - { - _primitiveToWrappers = new HashMap(9); + static { + _primitiveToWrappers = new HashMap<>(9); _primitiveToWrappers.put(Boolean.TYPE, Boolean.class); _primitiveToWrappers.put(Byte.TYPE, Byte.class); _primitiveToWrappers.put(Character.TYPE, Character.class); @@ -59,38 +53,38 @@ public class JavaTypeHelper _primitiveToWrappers.put(Short.TYPE, Short.class); _primitiveToWrappers.put(Void.TYPE, Void.class); - _primitiveNamesToPrimitives = new HashMap(9); - _primitiveNamesToPrimitives.put("boolean", Boolean.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("byte", Byte.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("char", Character.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("double", Double.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("float", Float.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("int", Integer.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("long", Long.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("short", Short.TYPE); // NOI18N - _primitiveNamesToPrimitives.put("void", Void.TYPE); // NOI18N - - _primitiveNamesToWrapperNames = new HashMap(9); - _primitiveNamesToWrapperNames.put("boolean", "Boolean"); // NOI18N - _primitiveNamesToWrapperNames.put("byte", "Byte"); // NOI18N - _primitiveNamesToWrapperNames.put("char", "Character"); // NOI18N - _primitiveNamesToWrapperNames.put("double", "Double"); // NOI18N - _primitiveNamesToWrapperNames.put("float", "Float"); // NOI18N - _primitiveNamesToWrapperNames.put("int", "Integer"); // NOI18N - _primitiveNamesToWrapperNames.put("long", "Long"); // NOI18N - _primitiveNamesToWrapperNames.put("short", "Short"); // NOI18N - _primitiveNamesToWrapperNames.put("void", "Void"); // NOI18N - - _wrapperToPrimitiveNames = new HashMap(9); - _wrapperToPrimitiveNames.put(Boolean.class, "boolean"); // NOI18N - _wrapperToPrimitiveNames.put(Byte.class, "byte"); // NOI18N - _wrapperToPrimitiveNames.put(Character.class, "char"); // NOI18N - _wrapperToPrimitiveNames.put(Double.class, "double"); // NOI18N - _wrapperToPrimitiveNames.put(Float.class, "float"); // NOI18N - _wrapperToPrimitiveNames.put(Integer.class, "int"); // NOI18N - _wrapperToPrimitiveNames.put(Long.class, "long"); // NOI18N - _wrapperToPrimitiveNames.put(Short.class, "short"); // NOI18N - _wrapperToPrimitiveNames.put(Void.class, "void"); // NOI18N + _primitiveNamesToPrimitives = new HashMap<>(9); + _primitiveNamesToPrimitives.put("boolean", Boolean.TYPE); + _primitiveNamesToPrimitives.put("byte", Byte.TYPE); + _primitiveNamesToPrimitives.put("char", Character.TYPE); + _primitiveNamesToPrimitives.put("double", Double.TYPE); + _primitiveNamesToPrimitives.put("float", Float.TYPE); + _primitiveNamesToPrimitives.put("int", Integer.TYPE); + _primitiveNamesToPrimitives.put("long", Long.TYPE); + _primitiveNamesToPrimitives.put("short", Short.TYPE); + _primitiveNamesToPrimitives.put("void", Void.TYPE); + + _primitiveNamesToWrapperNames = new HashMap<>(9); + _primitiveNamesToWrapperNames.put("boolean", "Boolean"); + _primitiveNamesToWrapperNames.put("byte", "Byte"); + _primitiveNamesToWrapperNames.put("char", "Character"); + _primitiveNamesToWrapperNames.put("double", "Double"); + _primitiveNamesToWrapperNames.put("float", "Float"); + _primitiveNamesToWrapperNames.put("int", "Integer"); + _primitiveNamesToWrapperNames.put("long", "Long"); + _primitiveNamesToWrapperNames.put("short", "Short"); + _primitiveNamesToWrapperNames.put("void", "Void"); + + _wrapperToPrimitiveNames = new HashMap<>(9); + _wrapperToPrimitiveNames.put(Boolean.class, "boolean"); + _wrapperToPrimitiveNames.put(Byte.class, "byte"); + _wrapperToPrimitiveNames.put(Character.class, "char"); + _wrapperToPrimitiveNames.put(Double.class, "double"); + _wrapperToPrimitiveNames.put(Float.class, "float"); + _wrapperToPrimitiveNames.put(Integer.class, "int"); + _wrapperToPrimitiveNames.put(Long.class, "long"); + _wrapperToPrimitiveNames.put(Short.class, "short"); + _wrapperToPrimitiveNames.put(Void.class, "void"); } /** @@ -106,7 +100,7 @@ public static String getPackageName (final String className) final int index = className.lastIndexOf('.'); return ((index != -1) ? - className.substring(0, index) : ""); // NOI18N + className.substring(0, index) : ""); } return null; @@ -134,9 +128,9 @@ public static String getShortClassName (final String className) * @param primitive the primitive class to be used for lookup. * @return the associated wrapper class. */ - public static Class getWrapperClass (Class primitive) + public static Class getWrapperClass (Class primitive) { - return (Class)_primitiveToWrappers.get(primitive); + return _primitiveToWrappers.get(primitive); } /** Returns the primitive class associated with the supplied primitive @@ -144,9 +138,9 @@ public static Class getWrapperClass (Class primitive) * @param primitiveName the name of the primitive to be used for lookup. * @return the associated primitive class. */ - public static Class getPrimitiveClass (String primitiveName) + public static Class getPrimitiveClass (String primitiveName) { - return (Class)_primitiveNamesToPrimitives.get(primitiveName); + return _primitiveNamesToPrimitives.get(primitiveName); } /** Returns the name of the wrapper class associated with the supplied @@ -156,7 +150,7 @@ public static Class getPrimitiveClass (String primitiveName) */ public static String getWrapperName (String primitiveName) { - return (String)_primitiveNamesToWrapperNames.get(primitiveName); + return _primitiveNamesToWrapperNames.get(primitiveName); } /** Returns the name of the primitive type associated with the supplied @@ -164,9 +158,9 @@ public static String getWrapperName (String primitiveName) * @param wrapper the wrapper class to be used for lookup. * @return the associated primitive type name. */ - public static String getPrimitiveName (Class wrapper) + public static String getPrimitiveName (Class wrapper) { - return (String)_wrapperToPrimitiveNames.get(wrapper); + return _wrapperToPrimitiveNames.get(wrapper); } /** Returns the Boolean wrapper object for true or false diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/LogHelperUtility.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/LogHelperUtility.java deleted file mode 100644 index cabd325030d..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/LogHelperUtility.java +++ /dev/null @@ -1,46 +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.spi.persistence.utility; - - -import com.sun.jdo.spi.persistence.utility.logging.LogHelper; -import com.sun.jdo.spi.persistence.utility.logging.Logger; - -/** LogHelper for utility package. - * @author Dave Bristor - */ -public class LogHelperUtility { - /** The component name for this component - */ - private static final String componentName = "utility"; // NOI18N - - /** The class loader for this component - */ - private static final ClassLoader loader = - LogHelperUtility.class.getClassLoader(); - - /** The bundle name for this component - */ - private static final String bundleName = - "com.sun.jdo.spi.persistence.utility.Bundle"; // NOI18N - - /** Return the logger for this component - */ - public static Logger getLogger() { - return LogHelper.getLogger(componentName, bundleName, loader); - } -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/MergedBundle.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/MergedBundle.java index c6c4fd970f7..6fdf63c2a44 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/MergedBundle.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/MergedBundle.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 */ -/* - * MappingContext.java - * - * Created on January 28, 2002, 6:30 PM - */ - package com.sun.jdo.spi.persistence.utility; import java.util.ArrayList; @@ -32,9 +27,10 @@ import java.util.ResourceBundle; import java.util.Set; -/** Special resource bundle which delegates to two others. +/** + * Special resource bundle which delegates to two others. * Ideally could just set the parent on the first, but this is protected, - * so it might not work. It's still unclear whether that approach would work + * so it might not work. It's still unclear whether that approach would work * in this subclass because it may break the localization fall through * mechanism if used. * Note: This code is copied from NbBundle in the openide sources with @@ -45,54 +41,48 @@ * - removing locale code * - creating the merged set of keys using jdk classes and not nb utils * - * @author Rochelle Raccah - * @version %I% + * @author Rochelle Raccah 2002 */ -public class MergedBundle extends ResourceBundle -{ +public class MergedBundle extends ResourceBundle { + private final ResourceBundle _mainBundle, _parentBundle; - public MergedBundle (ResourceBundle mainBundle, - ResourceBundle parentBundle) - { + public MergedBundle(ResourceBundle mainBundle, ResourceBundle parentBundle) { _mainBundle = mainBundle; _parentBundle = parentBundle; } - public Enumeration getKeys () { return mergeKeys(); } - private Enumeration mergeKeys () - { - Set noDuplicatesMerge = - new HashSet(getCollection(_mainBundle.getKeys())); + @Override + public Enumeration getKeys() { + return mergeKeys(); + } - noDuplicatesMerge.addAll(getCollection(_parentBundle.getKeys())); + private Enumeration mergeKeys() { + Set noDuplicatesMerge = new HashSet<>(getCollection(_mainBundle.getKeys())); + noDuplicatesMerge.addAll(getCollection(_parentBundle.getKeys())); return Collections.enumeration(noDuplicatesMerge); } - private Collection getCollection (Enumeration enumeration) - { - List returnList = new ArrayList(); - if (enumeration != null) - { - while (enumeration.hasMoreElements()) + private Collection getCollection(Enumeration enumeration) { + List returnList = new ArrayList<>(); + if (enumeration != null) { + while (enumeration.hasMoreElements()) { returnList.add(enumeration.nextElement()); + } } - return returnList; } - protected Object handleGetObject (String key) - throws MissingResourceException - { - try - { + + @Override + protected Object handleGetObject(String key) throws MissingResourceException { + try { return _mainBundle.getObject(key); - } - catch (MissingResourceException mre) // try the other bundle - { + } catch (MissingResourceException mre) { + // try the other bundle return _parentBundle.getObject(key); } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/NullSemaphore.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/NullSemaphore.java index 59c73121bad..66ece3b1e7d 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/NullSemaphore.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/NullSemaphore.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,7 +17,8 @@ package com.sun.jdo.spi.persistence.utility; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; +import java.lang.System.Logger.Level; /** Implements a simple semaphore that does not do any * semaphore-ing. That is, the methods just immediately return. @@ -26,40 +28,35 @@ // db13166: I would rather we use Doug Lea's stuff, but don't want to // introduce that magnitude of change at this point in time. public class NullSemaphore implements Semaphore { - /** Where to log messages about locking operations + + /** + * Where to log messages about locking operations */ - private static final Logger _logger = LogHelperUtility.getLogger(); + private static final Logger LOG = System.getLogger(NullSemaphore.class.getName()); - /** For logging, indicates on whose behalf locking is done. + /** + * For logging, indicates on whose behalf locking is done. */ private final String _owner; public NullSemaphore(String owner) { _owner = owner; - - if (_logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {_owner}; - _logger.finest("utility.nullsemaphore.constructor",items); // NOI18N - } + LOG.log(Level.DEBUG, "NullSemaphore constructor() for {0}.", _owner); } - /** Does nothing. + /** + * Does nothing. */ + @Override public void acquire() { - - if (_logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {_owner}; - _logger.finest("utility.nullsemaphore.acquire",items); // NOI18N - } + LOG.log(Level.DEBUG, "NullSemaphore.acquire() for {0}.", _owner); } - /** Does nothing. + /** + * Does nothing. */ + @Override public void release() { - - if (_logger.isLoggable(Logger.FINEST)) { - Object[] items = new Object[] {_owner}; - _logger.finest("utility.nullsemaphore.release",items); // NOI18N - } + LOG.log(Level.DEBUG, "NullSemaphore.release() for {0}.", _owner); } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/SemaphoreImpl.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/SemaphoreImpl.java index c1be6c8e992..c0f6e67a961 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/SemaphoreImpl.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/SemaphoreImpl.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,11 +17,9 @@ package com.sun.jdo.spi.persistence.utility; -import com.sun.jdo.spi.persistence.utility.logging.Logger; +import java.lang.System.Logger; -import java.util.ResourceBundle; - -import org.glassfish.persistence.common.I18NHelper; +import static java.lang.System.Logger.Level.DEBUG; /** Implements a simple semaphore. @@ -31,9 +30,8 @@ // db13166: I would rather we use Doug Lea's stuff, but don't want to // introduce that magnitude of change at this point in time. public class SemaphoreImpl implements Semaphore { - /** Where to log messages about locking operations - */ - private static final Logger _logger = LogHelperUtility.getLogger(); + + private static final Logger LOG = System.getLogger(SemaphoreImpl.class.getName()); /** For logging, indicates on whose behalf locking is done. */ @@ -51,12 +49,6 @@ public class SemaphoreImpl implements Semaphore { */ private int _counter = 0; - /** - * I18N message handler - */ - private final static ResourceBundle messages = - I18NHelper.loadBundle(SemaphoreImpl.class); - public SemaphoreImpl(String owner) { _owner = owner; @@ -64,13 +56,10 @@ public SemaphoreImpl(String owner) { /** Acquire a lock. */ + @Override public void acquire() { - boolean debug = _logger.isLoggable(Logger.FINEST); - - if (debug) { - Object[] items = new Object[] {_owner, Thread.currentThread(),new Integer(_counter)}; - _logger.finest("utility.semaphoreimpl.acquire",items); // NOI18N - } + LOG.log(DEBUG, "SemaphoreImpl.acquire() for {0}, thread = {1} with _lockCounter = {2}.", _owner, + Thread.currentThread(), _counter); synchronized (_lock) { // @@ -91,23 +80,18 @@ public void acquire() { _holder = Thread.currentThread(); _counter++; - if (debug) { - Object[] items = new Object[] {_owner, Thread.currentThread(),new Integer(_counter)}; - _logger.finest("utility.semaphoreimpl.gotlock",items); // NOI18N - } + LOG.log(DEBUG, "SemaphoreImpl.acquire() for {0}, got for thread = {1} with _lockCounter = {2}.", _owner, + Thread.currentThread(), _counter); } } } /** Release a lock. */ + @Override public void release() { - boolean debug = _logger.isLoggable(Logger.FINEST); - - if (debug) { - Object[] items = new Object[] {_owner, Thread.currentThread(),new Integer(_counter)}; - _logger.finest("utility.semaphoreimpl.release",items); // NOI18N - } + LOG.log(DEBUG, "SemaphoreImpl.release() for {0}, thread = {1} with _lockCounter = {2}.", _owner, + Thread.currentThread(), _counter); synchronized (_lock) { // @@ -120,10 +104,8 @@ public void release() { _lock.notify(); } } else { - throw new IllegalMonitorStateException( - I18NHelper.getMessage(messages, - "utility.semaphoreimpl.wrongthread", // NOI18N - new Object[] {_owner, Thread.currentThread()})); + throw new IllegalMonitorStateException("SemaphoreImpl.release() wrong thread for " + _owner + + ", thread = " + Thread.currentThread() + "."); } } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/StringHelper.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/StringHelper.java index bf9585eac8c..fd6684e17a1 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/StringHelper.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/StringHelper.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 */ -/* - * StringHelper.java - * - * Created on March 3, 2000 - */ - package com.sun.jdo.spi.persistence.utility; import java.util.ArrayList; @@ -59,11 +54,13 @@ public static String arrayToSeparatedList (List list, int beginIndex, { int i, count = (endIndex + 1); - if ((count > beginIndex) && (list.size() >= count)) + if ((count > beginIndex) && (list.size() >= count)) { result.append(list.get(beginIndex)); + } - for (i = beginIndex + 1; i < count; i++) + for (i = beginIndex + 1; i < count; i++) { result.append(separator + list.get(i)); + } } return result.toString(); @@ -113,17 +110,16 @@ public static String arrayToSeparatedList (List list) * @param separator The separator to be used to tokenize strings. * @return an array representing the tokenized list. */ - public static List separatedListToArray (String list, String separator) - { - ArrayList result = new ArrayList(); + public static List separatedListToArray(String list, String separator) { + ArrayList result = new ArrayList<>(); - if (list != null) - { + if (list != null) { StringTokenizer st = new StringTokenizer(list, separator); int i, size = st.countTokens(); - for (i = 0; i < size; i++) + for (i = 0; i < size; i++) { result.add(st.nextToken()); + } } return result; @@ -166,8 +162,9 @@ public static String intArrayToSeparatedList(int[] intArray, int beginIndex, if (intArray != null) { int count = (endIndex + 1); - if ((count > beginIndex) && (intArray.length >= count)) + if ((count > beginIndex) && (intArray.length >= count)) { result.append(intArray[beginIndex]); + } for (int i = beginIndex + 1; i < count; i++) { result.append(separator); @@ -195,8 +192,9 @@ public static boolean isEmpty (String aString) */ public static String getCapitalizedString (String aString) { - if (isEmpty(aString)) + if (isEmpty(aString)) { return aString; + } return Character.toUpperCase(aString.charAt(0)) + aString.substring(1); } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakHashSet.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakHashSet.java index a9f9e807885..93f6a5814e7 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakHashSet.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakHashSet.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 @@ -25,13 +26,13 @@ * A weak HashSet. An element stored in the WeakHashSet might be garbage collected, * if there is no strong reference to this element. */ -public class WeakHashSet - extends HashSet -{ +public class WeakHashSet extends HashSet { + + private static final long serialVersionUID = -4493040266028957440L; /** * Helps to detect garbage collected values. */ - ReferenceQueue queue = new ReferenceQueue(); + ReferenceQueue queue = new ReferenceQueue<>(); /** * Returns an iterator over the elements in this set. The elements @@ -39,28 +40,31 @@ public class WeakHashSet * * @return an Iterator over the elements in this set. */ - public Iterator iterator () - { + @Override + public Iterator iterator() { // remove garbage collected elements processQueue(); // get an iterator of the superclass WeakHashSet - final Iterator i = super.iterator(); + final Iterator i = super.iterator(); + + return new Iterator<>() { - return new Iterator () { - public boolean hasNext () - { + @Override + public boolean hasNext() { return i.hasNext(); } - public Object next () - { + + @Override + public Object next() { // unwrap the element - return getReferenceObject((WeakReference)i.next()); + return getReferenceObject((WeakReference) i.next()); } - public void remove () - { + + @Override + public void remove() { // remove the element from the HashSet i.remove(); } @@ -73,58 +77,58 @@ public void remove () * @param o element whose presence in this set is to be tested. * @return true if this set contains the specified element. */ - public boolean contains (Object o) - { + @Override + public boolean contains(Object o) { return super.contains(WeakElement.create(o)); } + /** * Adds the specified element to this set if it is not already * present. * * @param o element to be added to this set. * @return true if the set did not already contain the specified - * element. + * element. */ - public boolean add (Object o) - { + @Override + public boolean add(Object o) { processQueue(); return super.add(WeakElement.create(o, this.queue)); } + /** * Removes the given element from this set if it is present. * * @param o object to be removed from this set, if present. * @return true if the set contained the specified element. */ - public boolean remove (Object o) - { + @Override + public boolean remove(Object o) { boolean ret = super.remove(WeakElement.create(o)); processQueue(); return ret; } + /** * A convenience method to return the object held by the * weak reference or null if it does not exist. */ - private final Object getReferenceObject (WeakReference ref) - { + private final Object getReferenceObject(WeakReference ref) { return ((ref != null) ? ref.get() : null); } + /** * Removes all garbage collected values with their keys from the map. * Since we don't know how much the ReferenceQueue.poll() operation * costs, we should call it only in the put() method. */ - private final void processQueue () - { + private final void processQueue() { WeakElement wv = null; - - while ((wv = (WeakElement)this.queue.poll()) != null) - { + while ((wv = (WeakElement) this.queue.poll()) != null) { super.remove(wv); } } @@ -136,53 +140,61 @@ private final void processQueue () * It redefines equals and hashCode which delegate to the corresponding methods * of the wrapped element. */ - static private class WeakElement - extends WeakReference - { - private int hash; /* Hashcode of key, stored here since the key - may be tossed by the GC */ - - private WeakElement (Object o) - { + static private class WeakElement extends WeakReference { + + private int hash; /* + * Hashcode of key, stored here since the key + * may be tossed by the GC + */ + + private WeakElement(Object o) { super(o); hash = o.hashCode(); } - private WeakElement (Object o, ReferenceQueue q) - { + + private WeakElement(Object o, ReferenceQueue q) { super(o, q); hash = o.hashCode(); } - private static WeakElement create (Object o) - { + + private static WeakElement create(Object o) { return (o == null) ? null : new WeakElement(o); } - private static WeakElement create (Object o, ReferenceQueue q) - { + + private static WeakElement create(Object o, ReferenceQueue q) { return (o == null) ? null : new WeakElement(o, q); } - /* A WeakElement is equal to another WeakElement iff they both refer to objects - that are, in turn, equal according to their own equals methods */ - public boolean equals (Object o) - { - if (this == o) + + /* + * A WeakElement is equal to another WeakElement iff they both refer to objects + * that are, in turn, equal according to their own equals methods + */ + @Override + public boolean equals(Object o) { + if (this == o) { return true; - if (!(o instanceof WeakElement)) + } + if (!(o instanceof WeakElement)) { return false; + } Object t = this.get(); - Object u = ((WeakElement)o).get(); - if ((t == null) || (u == null)) + Object u = ((WeakElement) o).get(); + if ((t == null) || (u == null)) { return false; - if (t == u) + } + if (t == u) { return true; + } return t.equals(u); } - public int hashCode () - { + + @Override + public int hashCode() { return hash; } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakValueHashMap.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakValueHashMap.java index 6d18a21e4e9..93b8b5932f7 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakValueHashMap.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/WeakValueHashMap.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,29 +30,34 @@ /** * A WeakValueHashMap is implemented as a HashMap that maps keys to - * WeakValues. Because we don't have access to the innards of the + * WeakValues. Because we don't have access to the innards of the * HashMap, we have to wrap/unwrap value objects with WeakValues on - * every operation. Fortunately WeakValues are small, short-lived + * every operation. Fortunately WeakValues are small, short-lived * objects, so the added allocation overhead is tolerable. This * implementaton directly extends java.util.HashMap. * - * @author Markus Fuchs - * @see java.util.HashMap - * @see java.lang.ref.WeakReference + * @author Markus Fuchs + * @see java.util.HashMap + * @see java.lang.ref.WeakReference */ +public class WeakValueHashMap extends HashMap { -public class WeakValueHashMap extends HashMap { + private static final long serialVersionUID = 7836788274746992673L; /** * Reference queue for cleared WeakValues. * We do not expect instance of this class to be serialized. Marking a non serializable member as transient to make findbugs happy. */ - private transient ReferenceQueue queue = new ReferenceQueue(); + private transient ReferenceQueue queue = new ReferenceQueue<>(); + /** stores the value collection */ + private transient Collection values; + /** * Returns the number of key-value mappings in this map.

    * @return the number of key-value mappings in this map. */ + @Override public int size() { // delegate to entrySet, as super.size() also counts WeakValues return entrySet().size(); @@ -61,6 +67,7 @@ public int size() { * Returns true if this map contains no key-value mappings.

    * @return true if this map contains no key-value mappings. */ + @Override public boolean isEmpty() { return size() == 0; } @@ -72,6 +79,7 @@ public boolean isEmpty() { * @return true if this map contains a mapping for the specified * key. */ + @Override public boolean containsKey(Object key) { // need to clean up gc'ed values before invoking super method processQueue(); @@ -84,6 +92,7 @@ public boolean containsKey(Object key) { * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to this value. */ + @Override public boolean containsValue(Object value) { return super.containsValue(WeakValue.create(value)); } @@ -93,12 +102,13 @@ public boolean containsValue(Object value) { * @param key key whose associated value, if any, is to be returned * @return the value to which this map maps the specified key. */ - public Object get(Object key) { + @Override + public V get(Object key) { // We don't need to remove garbage collected values here; // if they are garbage collected, the get() method returns null; // the next put() call with the same key removes the old value // automatically so that it can be completely garbage collected - return getReferenceObject((WeakReference) super.get(key)); + return getReferenceObject((WeakReference) super.get(key)); } /** @@ -109,7 +119,8 @@ public Object get(Object key) { * if there was no mapping for key or the value has been garbage * collected by the garbage collector. */ - public Object put(Object key, Object value) { + @Override + public Object put(K key, Object value) { // If the map already contains an equivalent key, the new key // of a (key, value) pair is NOT stored in the map but the new // value only. But as the key is strongly referenced by the @@ -121,8 +132,7 @@ public Object put(Object key, Object value) { // clean up calls on different operations. processQueue(); - WeakValue oldValue = - (WeakValue)super.put(key, WeakValue.create(key, value, queue)); + WeakValue oldValue = (WeakValue) super.put(key, WeakValue.create(key, value, queue)); return getReferenceObject(oldValue); } @@ -133,15 +143,16 @@ public Object put(Object key, Object value) { * if there was no mapping for key or the value has been garbage * collected by the garbage collector. */ - public Object remove(Object key) { - return getReferenceObject((WeakReference) super.remove(key)); + @Override + public V remove(Object key) { + return getReferenceObject((WeakReference) super.remove(key)); } /** * A convenience method to return the object held by the * weak reference or null if it does not exist. */ - private final Object getReferenceObject(WeakReference ref) { + private final V getReferenceObject(WeakReference ref) { return (ref == null) ? null : ref.get(); } @@ -151,9 +162,9 @@ private final Object getReferenceObject(WeakReference ref) { * costs, we should not call it every map operation. */ private void processQueue() { - WeakValue wv = null; + WeakValue wv = null; - while ((wv = (WeakValue) this.queue.poll()) != null) { + while ((wv = (WeakValue) this.queue.poll()) != null) { // "super" is not really necessary but use it // to be on the safe side super.remove(wv.key); @@ -167,38 +178,44 @@ private void processQueue() { * the value to the key, so that we are able to remove the key if * the value is garbage collected. */ - private static class WeakValue extends WeakReference { + private static class WeakValue extends WeakReference { + /** * It's the same as the key in the map. We need the key to remove * the value if it is garbage collected. */ - private Object key; + private K key; - private WeakValue(Object value) { + private WeakValue(V value) { super(value); } + /** - * Creates a new weak reference without adding it to a - * ReferenceQueue. + * Creates a new weak reference without adding it to a {@link ReferenceQueue}. */ - private static WeakValue create(Object value) { - if (value == null) return null; - else return new WeakValue(value); + private static WeakValue create(V value) { + if (value == null) { + return null; + } + return new WeakValue<>(value); } - private WeakValue(Object key, Object value, ReferenceQueue queue) { + + private WeakValue(K key, V value, ReferenceQueue queue) { super(value, queue); this.key = key; } + /** * Creates a new weak reference and adds it to the given queue. */ - private static WeakValue create(Object key, Object value, - ReferenceQueue queue) { - if (value == null) return null; - else return new WeakValue(key, value, queue); + private static WeakValue create(K key, V value, ReferenceQueue queue) { + if (value == null) { + return null; + } + return new WeakValue<>(key, value, queue); } /** @@ -206,21 +223,26 @@ private static WeakValue create(Object key, Object value, * to objects that are, in turn, equal according to their own * equals methods. */ + @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; + } - if (!(obj instanceof WeakValue)) + if (!(obj instanceof WeakValue)) { return false; + } Object ref1 = this.get(); - Object ref2 = ((WeakValue) obj).get(); + Object ref2 = ((WeakValue) obj).get(); - if (ref1 == ref2) + if (ref1 == ref2) { return true; + } - if ((ref1 == null) || (ref2 == null)) + if ((ref1 == null) || (ref2 == null)) { return false; + } return ref1.equals(ref2); } @@ -228,6 +250,7 @@ public boolean equals(Object obj) { /** * */ + @Override public int hashCode() { Object ref = this.get(); @@ -239,25 +262,31 @@ public int hashCode() { * Internal class for entries. This class wraps/unwraps the * values of the Entry objects returned from the underlying map. */ - private class Entry implements Map.Entry { - private Map.Entry ent; - private Object value; /* Strong reference to value, so that the - GC will leave it alone as long as this - Entry exists */ + private class Entry implements Map.Entry { + private Map.Entry ent; + /** + * Strong reference to value, so that the + * GC will leave it alone as long as this + * Entry exists + */ + private Object value; - Entry(Map.Entry ent, Object value) { + Entry(Map.Entry ent, Object value) { this.ent = ent; this.value = value; } - public Object getKey() { + @Override + public K getKey() { return ent.getKey(); } + @Override public Object getValue() { return value; } + @Override public Object setValue(Object value) { // This call changes the map. Please see the comment on // the put method for the correctness remark. @@ -271,17 +300,19 @@ private boolean valEquals(Object o1, Object o2) { return (o1 == null) ? (o2 == null) : o1.equals(o2); } + @Override public boolean equals(Object o) { - if (!(o instanceof Map.Entry)) return false; - Map.Entry e = (Map.Entry) o; - return (valEquals(ent.getKey(), e.getKey()) - && valEquals(value, e.getValue())); + if (!(o instanceof Map.Entry)) { + return false; + } + Map.Entry e = (Map.Entry) o; + return valEquals(ent.getKey(), e.getKey()) && valEquals(value, e.getValue()); } + @Override public int hashCode() { Object k; - return ((((k = ent.getKey()) == null) ? 0 : k.hashCode()) - ^ ((value == null) ? 0 : value.hashCode())); + return ((((k = ent.getKey()) == null) ? 0 : k.hashCode()) ^ ((value == null) ? 0 : value.hashCode())); } } @@ -290,37 +321,42 @@ public int hashCode() { * Internal class for entry sets to unwrap/wrap WeakValues stored * in the map. */ - private class EntrySet extends AbstractSet { + private class EntrySet extends AbstractSet> { - public Iterator iterator() { + @Override + public Iterator> iterator() { // remove garbage collected elements processQueue(); - return new Iterator() { - Iterator hashIterator = hashEntrySet.iterator(); - Entry next = null; + return new Iterator<>() { + Iterator> hashIterator = hashEntrySet.iterator(); + Entry next; + @Override public boolean hasNext() { if (hashIterator.hasNext()) { // since we removed garbage collected elements, // we can simply return the next entry. - Map.Entry ent = (Map.Entry) hashIterator.next(); - WeakValue wv = (WeakValue) ent.getValue(); - Object v = (wv == null) ? null : wv.get(); - next = new Entry(ent, v); + Map.Entry ent = hashIterator.next(); + WeakValue wv = (WeakValue) ent.getValue(); + Object v = wv == null ? null : wv.get(); + next = new Entry<>(ent, v); return true; } return false; } - public Object next() { - if ((next == null) && !hasNext()) + @Override + public Entry next() { + if ((next == null) && !hasNext()) { throw new NoSuchElementException(); - Entry e = next; + } + Entry e = next; next = null; return e; } + @Override public void remove() { hashIterator.remove(); } @@ -328,32 +364,37 @@ public void remove() { }; } + @Override public boolean isEmpty() { return !(iterator().hasNext()); } + @Override public int size() { int j = 0; - for (Iterator i = iterator(); i.hasNext(); i.next()) j++; + for (Iterator i = iterator(); i.hasNext(); i.next()) { + j++; + } return j; } + @Override public boolean remove(Object o) { - if (!(o instanceof Map.Entry)) return false; - Map.Entry e = (Map.Entry) o; + if (!(o instanceof Map.Entry)) { + return false; + } + Map.Entry e = (Map.Entry) o; Object ek = e.getKey(); Object ev = e.getValue(); Object hv = WeakValueHashMap.this.get(ek); if (hv == null) { // if the map's value is null, we have to check, if the // entry's value is null and the map contains the key - if ((ev == null) && WeakValueHashMap.this.containsKey(ek)) { + if (ev == null && WeakValueHashMap.this.containsKey(ek)) { WeakValueHashMap.this.remove(ek); return true; - } else { - return false; } - // otherwise, simply compare the values + return false; } else if (hv.equals(ev)) { WeakValueHashMap.this.remove(ek); return true; @@ -362,15 +403,17 @@ public boolean remove(Object o) { return false; } + @Override public int hashCode() { int h = 0; - for (Iterator i = hashEntrySet.iterator(); i.hasNext(); ) { - Map.Entry ent = (Map.Entry) i.next(); + for (Iterator> i = hashEntrySet.iterator(); i.hasNext();) { + Map.Entry ent = i.next(); Object k; - WeakValue wv = (WeakValue) ent.getValue(); - if (wv == null) continue; - h += ((((k = ent.getKey()) == null) ? 0 : k.hashCode()) - ^ wv.hashCode()); + Object wv = ent.getValue(); + if (wv == null) { + continue; + } + h += ((((k = ent.getKey()) == null) ? 0 : k.hashCode()) ^ wv.hashCode()); } return h; } @@ -379,14 +422,15 @@ public int hashCode() { // internal helper variable, because we can't access // entrySet from the superclass inside the EntrySet class - private Set hashEntrySet = null; + private Set> hashEntrySet; // stores the EntrySet instance - private Set entrySet = null; + private EntrySet entrySet; /** * Returns a Set view of the mappings in this map.

    * @return a Set view of the mappings in this map. */ + @Override public Set entrySet() { if (entrySet == null) { hashEntrySet = super.entrySet(); @@ -395,48 +439,55 @@ public Set entrySet() { return entrySet; } - // stores the value collection - private transient Collection values = null; - /** * Returns a Collection view of the values contained * in this map.

    * @return a Collection view of the values contained * in this map. */ - public Collection values() { + @Override + public Collection values() { // delegates to entrySet, because super method returns // WeakValues instead of value objects - if (values == null) { - values = new AbstractCollection() { - public Iterator iterator() { - return new Iterator() { - private Iterator i = entrySet().iterator(); - - public boolean hasNext() { - return i.hasNext(); - } + if (values == null) { + values = new AbstractCollection<>() { - public Object next() { - return ((Entry)i.next()).getValue(); - } + public Iterator iterator() { + return new Iterator<>() { - public void remove() { - i.remove(); - } + private Iterator> i = entrySet().iterator(); + + @Override + public boolean hasNext() { + return i.hasNext(); + } + + + @Override + public Object next() { + return i.next().getValue(); + } + + + @Override + public void remove() { + i.remove(); + } }; } - public int size() { - return WeakValueHashMap.this.size(); - } - public boolean contains(Object v) { - return WeakValueHashMap.this.containsValue(v); + public int size() { + return WeakValueHashMap.this.size(); + } + + + public boolean contains(Object v) { + return WeakValueHashMap.this.containsValue(v); + } + }; } - }; - } - return values; + return values; } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/JavaClassWriterHelper.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/JavaClassWriterHelper.java index 44734aef127..f46a33841c4 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/JavaClassWriterHelper.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/JavaClassWriterHelper.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 */ -/* - * JavaClassWriterHelper.java - * - * Created on December 03, 2001 - */ - package com.sun.jdo.spi.persistence.utility.generator; import com.sun.jdo.spi.persistence.utility.JavaTypeHelper; @@ -32,66 +27,66 @@ /* * This is the utility class for helper strings and type convertion. * - * @author Marina Vatkina + * @author Marina Vatkina 2001 */ public class JavaClassWriterHelper extends JavaTypeHelper { - public final static String javaExtension_ = ".java"; // NOI18N - public final static String void_ = "void"; // NOI18N - public final static String boolean_ = "boolean"; // NOI18N - public final static String byte_ = "byte"; // NOI18N - public final static String byteArray_ = "byte[]"; // NOI18N - public final static String param_ = "param"; // NOI18N - public final static String param0_ = "param0"; // NOI18N - public final static String null_ = "null"; // NOI18N - public final static String home_ = "home"; // NOI18N - public final static String delim_ = ";"; // NOI18N - public final static String paramInitializer_ = "\"\" + "; // NOI18N - public final static String paramSeparator_ = ", "; // NOI18N - public final static String paramList_ = ","; // NOI18N - public final static String paramConcatenator_ = " + \", \" + "; // NOI18N - public final static String space_ = " "; // NOI18N - public final static String none_ = ""; // NOI18N - public final static String escapedEmptyString_ = "\"\""; // NOI18N - public final static String dot_ = "."; // NOI18N - public final static String parenleft_ = "("; // NOI18N - public final static String parenright_ = ")"; // NOI18N - public final static String parenthesis_ = "()"; // NOI18N - public final static String new_ = "new"; // NOI18N - public final static String endLine_ = "\n"; // NOI18N - public final static String true_ = "true"; // NOI18N - public final static String false_ = "false"; // NOI18N - public final static String Collection_ = "java.util.Collection"; // NOI18N - public final static String Set_ = "java.util.Set"; // NOI18N - public final static String PersistenceCapable_ = "com.sun.jdo.api.persistence.support.PersistenceCapable"; // NOI18N - public final static String brackets_ = "[]"; // NOI18N - public final static String get_ = "get"; // NOI18N - public final static String set_ = "set"; // NOI18N - public final static String Oid_ = ".Oid"; // NOI18N - public final static String Helper_ = "_JDOHelper"; // NOI18N - public final static String returnNull_ = "return null;"; // NOI18N - public final static String fileName_ = "fileName"; // NOI18N - public final static String int_ = "int"; // NOI18N - public final static String String_ = "java.lang.String"; // NOI18N - public final static String Class_ = "java.lang.Class"; // NOI18N - public final static String Date_ = "java.util.Date"; // NOI18N - public final static String SqlDate_ = "java.sql.Date"; // NOI18N - public final static String SqlTime_ = "java.sql.Time"; // NOI18N - public final static String SqlTimestamp_ = "java.sql.Timestamp"; // NOI18N + public final static String javaExtension_ = ".java"; + public final static String void_ = "void"; + public final static String boolean_ = "boolean"; + public final static String byte_ = "byte"; + public final static String byteArray_ = "byte[]"; + public final static String param_ = "param"; + public final static String param0_ = "param0"; + public final static String null_ = "null"; + public final static String home_ = "home"; + public final static String delim_ = ";"; + public final static String paramInitializer_ = "\"\" + "; + public final static String paramSeparator_ = ", "; + public final static String paramList_ = ","; + public final static String paramConcatenator_ = " + \", \" + "; + public final static String space_ = " "; + public final static String none_ = ""; + public final static String escapedEmptyString_ = "\"\""; + public final static String dot_ = "."; + public final static String parenleft_ = "("; + public final static String parenright_ = ")"; + public final static String parenthesis_ = "()"; + public final static String new_ = "new"; + public final static String endLine_ = "\n"; + public final static String true_ = "true"; + public final static String false_ = "false"; + public final static String Collection_ = "java.util.Collection"; + public final static String Set_ = "java.util.Set"; + public final static String PersistenceCapable_ = "com.sun.jdo.api.persistence.support.PersistenceCapable"; + public final static String brackets_ = "[]"; + public final static String get_ = "get"; + public final static String set_ = "set"; + public final static String Oid_ = ".Oid"; + public final static String Helper_ = "_JDOHelper"; + public final static String returnNull_ = "return null;"; + public final static String fileName_ = "fileName"; + public final static String int_ = "int"; + public final static String String_ = "java.lang.String"; + public final static String Class_ = "java.lang.Class"; + public final static String Date_ = "java.util.Date"; + public final static String SqlDate_ = "java.sql.Date"; + public final static String SqlTime_ = "java.sql.Time"; + public final static String SqlTimestamp_ = "java.sql.Timestamp"; // This variable is used to construct both the type and method name // e.g. setObjectField(), so it should be kept in a short version. - public final static String Object_ = "Object"; // NOI18N + public final static String Object_ = "Object"; - public final static String[] super_ = new String[] {"super();"}; // NOI18N + public final static String[] super_ = new String[] {"super();"}; // This String[] is used internally to replace "\t" with the element of this array // that represents the corresponding indentation in spaces. private final static String[] indentation_ = new String[] { - " ", // NOI18N - " ", // NOI18N - " ", // NOI18N - " "}; // NOI18N + " ", + " ", + " ", + " "}; /** * Converts method body into String array. @@ -105,10 +100,11 @@ public static String[] getBodyAsStrings(String body) { while(st.hasMoreTokens()) { String s = st.nextToken(); int i = s.lastIndexOf('\t'); - if (i > -1) - rc[ii] = indentation_[i] + s.substring(i + 1); - else - rc[ii] = s; + if (i > -1) { + rc[ii] = indentation_[i] + s.substring(i + 1); + } else { + rc[ii] = s; + } ii++; } @@ -123,8 +119,8 @@ public static String[] getBodyAsStrings(String body) { * @param cls the primitive Class to find Object wrapper for. * @return Object type Class. */ - public static Class getWrapperType(Class cls) { - Class rc = getWrapperClass(cls); + public static Class getWrapperType(Class cls) { + Class rc = getWrapperClass(cls); if (rc == null) { // not a primitive rc = cls; } @@ -140,7 +136,7 @@ public static Class getWrapperType(Class cls) { * @return A String containing the expression for wrapping the * primitive datatype in its corresponding wrapperclass */ - public static String getWrapperExpr(Class exprType, String expr) { + public static String getWrapperExpr(Class exprType, String expr) { StringBuffer wrapped = new StringBuffer(); @@ -160,7 +156,7 @@ public static String getWrapperExpr(Class exprType, String expr) { * @param primitiveType the class object of the primitive type. * @return the name of the method to access the primitive value of the wrapper */ - public static String getUnwrapMethodName(Class primitiveType) + public static String getUnwrapMethodName(Class primitiveType) { return primitiveType.getName() + "Value()"; //NOI18N } @@ -174,7 +170,7 @@ public static String getUnwrapMethodName(Class primitiveType) * the primitive type for. * @return name of the primitive type as String. */ - public static String getPrimitiveType(Class cls) { + public static String getPrimitiveType(Class cls) { String rc = getPrimitiveName(cls); if (rc == null) { // not an Object rc = cls.getName(); @@ -189,7 +185,7 @@ public static String getPrimitiveType(Class cls) { * @return exception type names as String[]. */ public static String[] getExceptionNames(Method m) { - Class[] cls = m.getExceptionTypes(); + Class[] cls = m.getExceptionTypes(); String[] rc = new String[cls.length]; for (int ii = 0; ii < cls.length; ii++) { rc[ii] = cls[ii].getName(); @@ -204,14 +200,16 @@ public static String[] getExceptionNames(Method m) { * @return list of method parameter types as String */ public static String getParameterTypesList(Method m) { - if (m == null) - return none_; + if (m == null) { + return none_; + } StringBuffer buf = new StringBuffer(); - Class[] paramTypes = m.getParameterTypes(); + Class[] paramTypes = m.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { - if (i > 0) + if (i > 0) { buf.append(paramList_); + } buf.append(getTypeRepr(paramTypes[i])); } return buf.toString(); @@ -240,8 +238,9 @@ public static String getParametersListWithSeparator(Method m, String sep) { StringBuffer rc = new StringBuffer(); for (int ii = 0; ii < count; ii++) { - if (ii > 0) + if (ii > 0) { rc.append(sep); + } rc.append(param_ + ii); } @@ -255,16 +254,16 @@ public static String getParametersListWithSeparator(Method m, String sep) { * @param writer the Class writer. * @throws IOException if writer fails to add a field. */ - public static void addFields(String prop, int modifiers, JavaClassWriter writer) - throws IOException{ + public static void addFields(String prop, int modifiers, JavaClassWriter writer) throws IOException { String[] v = getBodyAsStrings(prop); for (int i = 0; i < v.length; i++) { StringTokenizer st = new StringTokenizer(v[i], space_); String type = st.nextToken(); String name = st.nextToken(); StringBuffer value = new StringBuffer(); - while(st.hasMoreTokens()) - value.append(st.nextToken() + space_); + while(st.hasMoreTokens()) { + value.append(st.nextToken() + space_); + } int l = value.length(); value.deleteCharAt(l - 1); // last space @@ -282,8 +281,7 @@ public static void addFields(String prop, int modifiers, JavaClassWriter writer) * @param modifiers field modifiers for these fields. * @throws IOException if writer fails to add a field. */ - public static void addPrivateField(String prop, int modifiers, JavaClassWriter writer) - throws IOException{ + public static void addPrivateField(String prop, int modifiers, JavaClassWriter writer) throws IOException { addFields(prop, Modifier.PRIVATE + modifiers, writer); } @@ -367,7 +365,7 @@ public static void addGenericMethod(Method m, String mname, JavaClassWriter writer) throws IOException{ - Class[] types = m.getParameterTypes(); + Class[] types = m.getParameterTypes(); int count = types.length; String[] parameterTypes = new String[count]; String[] parameterNames = new String[count]; @@ -379,8 +377,9 @@ public static void addGenericMethod(Method m, String mname, String[] exceptionTypes = getExceptionNames(m); int modifiers = m.getModifiers(); - if (Modifier.isAbstract(modifiers)) + if (Modifier.isAbstract(modifiers)) { modifiers -= Modifier.ABSTRACT; + } writer.addMethod(mname, // name modifiers, // modifiers @@ -396,7 +395,7 @@ public static void addGenericMethod(Method m, String mname, * Returns the String representation of the specified class instance. * An array is represented as the name of the element type followed by []. */ - public static String getTypeRepr(Class clazz) + public static String getTypeRepr(Class clazz) { return (clazz.isArray() ? getTypeRepr(clazz.getComponentType()) + brackets_ : diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/FormattedWriter.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/FormattedWriter.java index 34a3c99d03e..8ff033c4ccc 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/FormattedWriter.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/FormattedWriter.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,145 +15,137 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * FormattedWriter.java - * - * Created on November 14, 2001, 5:50 PM - */ - package com.sun.jdo.spi.persistence.utility.generator.io; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; - /** - * - * @author raccah + * @author raccah 2001 */ -class FormattedWriter -{ - static private final String lineSeparator = - System.getProperty("line.separator"); - static private final String indent = " "; // NOI18N +class FormattedWriter { + + static private final String lineSeparator = System.lineSeparator(); + static private final String indent = " "; private StringBuffer _buffer; private int _initialIndents = 0; /** Creates new FormattedWriter */ - FormattedWriter () - { + FormattedWriter() { } - private StringBuffer getBuffer () - { - if (_buffer == null) + + private StringBuffer getBuffer() { + if (_buffer == null) { _buffer = new StringBuffer(); + } return _buffer; } - /** Returns a string representation of the FormattedWriter. + + /** + * Returns a string representation of the FormattedWriter. + * * @return The string representation of the internal StringBuffer - * used by this object. + * used by this object. */ - public String toString () { return getBuffer().toString(); } + @Override + public String toString() { + return getBuffer().toString(); + } + - void writeComments (final String[] comments) - { + void writeComments(final String[] comments) { final int n = (comments != null ? comments.length : 0); - for (int i = 0; i < n; i++) - { + for (int i = 0; i < n; i++) { final String s = comments[i]; - writeln("// " + (s != null ? s : "")); // NOI18N + writeln("// " + (s != null ? s : "")); } } - private void _write (final int indents, final String s) - { + + private void _write(final int indents, final String s) { final StringBuffer buffer = getBuffer(); - if (!s.equals(lineSeparator)) - { - for (int i = 0; i < indents; i++) + if (!s.equals(lineSeparator)) { + for (int i = 0; i < indents; i++) { buffer.append(indent); + } } buffer.append(s); } - void write (final int indents, final String s) - { + + void write(final int indents, final String s) { _write(indents + _initialIndents, s); } - void write (final String s) - { + + void write(final String s) { _write(0, s); } - void writeln (final int indents, final String s) - { - if (_initialIndents > 0) - _write(_initialIndents, ""); // NOI18N + + void writeln(final int indents, final String s) { + if (_initialIndents > 0) { + _write(_initialIndents, ""); + } _write(indents, s + lineSeparator); } - void writeln (final String s) - { - writeln(0, s); - } - void writeln () - { - writeln(0, ""); // NOI18N + void writeln(final String s) { + writeln(0, s); } - void writeList (final int indents, final List list, - final boolean addSeparator) - { - if ((list != null) && (list.size() > 0)) - { - Iterator iterator = list.iterator(); - while (iterator.hasNext()) - { - indent(indents, iterator.next().toString()); + void writeln() { + writeln(0, ""); + } - if (addSeparator) - writeln(); - } - if (!addSeparator) + void writeList(final int indents, final List list, final boolean addSeparator) { + if (list == null || list.isEmpty()) { + return; + } + Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + indent(indents, iterator.next().toString()); + if (addSeparator) { writeln(); + } + } + if (!addSeparator) { + writeln(); } } - void writeList (final int indents, final List list) - { + + void writeList(final int indents, final List list) { writeList(indents, list, false); } - void writeList (final List list) - { + + void writeList(final List list) { writeList(0, list); } - private void indent (final int indents, final String s) - { - if (s.indexOf(lineSeparator) != -1) - { - StringTokenizer tokenizer = - new StringTokenizer(s, lineSeparator, true); - while (tokenizer.hasMoreTokens()) + private void indent(final int indents, final String s) { + if (s.contains(lineSeparator)) { + StringTokenizer tokenizer = new StringTokenizer(s, lineSeparator, true); + while (tokenizer.hasMoreTokens()) { write(indents, tokenizer.nextToken()); - } - else + } + } else { write(indents, s); + } } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaClassWriter.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaClassWriter.java index aca17cf8ff1..2221c5bd80a 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaClassWriter.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaClassWriter.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 */ -/* - * IOJavaClassWriter.java - * - * Created on November 12, 2001, 4:59 PM - */ - package com.sun.jdo.spi.persistence.utility.generator.io; import com.sun.jdo.spi.persistence.utility.StringHelper; @@ -43,23 +38,23 @@ * interspersed among each other in exactly the order they were added (no * member categories). * - * @author raccah + * @author raccah 2001 */ public final class IOJavaClassWriter implements JavaClassWriter { - private static final String FIELD = "FIELD"; // NOI18N - private static final String INITIALIZER = "INITIALIZER"; // NOI18N - private static final String CONSTRUCTOR = "CONSTRUCTOR"; // NOI18N - private static final String METHOD = "METHOD"; // NOI18N - private static final String INNER_CLASS = "INNER_CLASS"; // NOI18N - private static final String MIXED = "MIXED"; // NOI18N - private static final String COMMA_SEPARATOR = ", "; // NOI18N + private static final String FIELD = "FIELD"; + private static final String INITIALIZER = "INITIALIZER"; + private static final String CONSTRUCTOR = "CONSTRUCTOR"; + private static final String METHOD = "METHOD"; + private static final String INNER_CLASS = "INNER_CLASS"; + private static final String MIXED = "MIXED"; + private static final String COMMA_SEPARATOR = ", "; private boolean _maintainCategories; private String _superclass; private String _classDeclarationBlock; - private List _interfaces = new ArrayList(); - private Map _members = new HashMap(); + private List _interfaces = new ArrayList<>(); + private Map> _members = new HashMap<>(); /** Creates a new instance of IOJavaClassWriter which maintains the * order of member input but groups them by category. @@ -92,6 +87,7 @@ public IOJavaClassWriter (boolean maintainCategories) * to make use of this comment. * @see java.lang.reflect.Modifier */ + @Override public void setClassDeclaration (final int modifiers, final String className, final String[] comments) { @@ -101,7 +97,7 @@ public void setClassDeclaration (final int modifiers, writerHelper.writeComments(comments); writerHelper.writeln(modifierString + ((modifierString.length() > 0) - ? " " : "") + "class " + className); // NOI18N + ? " " : "") + "class " + className); _classDeclarationBlock = writerHelper.toString(); } @@ -110,6 +106,7 @@ public void setClassDeclaration (final int modifiers, * be package style (that is - it can contain . but not / or $). * @param name The name of the superclass. */ + @Override public void setSuperclass (final String name) { _superclass = name; @@ -118,10 +115,12 @@ public void setSuperclass (final String name) /** Adds an interface to the list of those implemented by this class. * @param name The name of the interface. */ + @Override public void addInterface (final String name) { - if (!StringHelper.isEmpty(name)) + if (!StringHelper.isEmpty(name)) { _interfaces.add(name); + } } /** Adds a field to the list of those declared by this class. Note @@ -138,6 +137,7 @@ public void addInterface (final String name) * implementations will choose to make use of this comment. * @see java.lang.reflect.Modifier */ + @Override public void addField (final String name, final int modifiers, String type, final String initialValue, final String[] comments) { @@ -147,7 +147,7 @@ public void addField (final String name, final int modifiers, String type, writerHelper.writeComments(comments); writerHelper.writeln(fieldString + ((initialValue != null) ? - (" = " + initialValue) : "") + ';'); // NOI18N + (" = " + initialValue) : "") + ';'); getMemberList(FIELD).add(writerHelper.toString()); } @@ -162,6 +162,7 @@ public void addField (final String name, final int modifiers, String type, * by the implementation. Note that not all implementations will choose * to make use of this comment. */ + @Override public void addInitializer (boolean isStatic, String[] body, String[] comments) { @@ -171,15 +172,16 @@ public void addInitializer (boolean isStatic, String[] body, writerHelper.writeComments(comments); // header - writerHelper.writeln(isStatic ? "static" : ""); // NOI18N - writerHelper.writeln("{"); // NOI18N + writerHelper.writeln(isStatic ? "static" : ""); + writerHelper.writeln("{"); // implementation - for (int i = 0; i < n; i++) + for (int i = 0; i < n; i++) { writerHelper.writeln(1, body[i]); + } // end - writerHelper.writeln("}"); // NOI18N + writerHelper.writeln("}"); getMemberList(INITIALIZER).add(writerHelper.toString()); } @@ -202,6 +204,7 @@ public void addInitializer (boolean isStatic, String[] body, * to make use of this comment. * @see java.lang.reflect.Modifier */ + @Override public void addConstructor (final String name, final int modifiers, final String[] parameterNames, final String[] parameterTypes, final String[] exceptions, final String[] body, final String[] comments) @@ -228,6 +231,7 @@ public void addConstructor (final String name, final int modifiers, * to make use of this comment. * @see java.lang.reflect.Modifier */ + @Override public void addMethod (final String name, final int modifiers, final String returnType, final String[] parameterNames, final String[] parameterTypes, final String[] exceptions, @@ -240,22 +244,25 @@ public void addMethod (final String name, final int modifiers, /** Adds an inner class to this class. * @param classWriter The definition of the inner class. */ + @Override public void addClass (final JavaClassWriter classWriter) { - if (classWriter != null) - getMemberList(INNER_CLASS).add(classWriter); + if (classWriter != null) { + getMemberList(INNER_CLASS).add(classWriter.toString()); + } } /** Returns a string representation of this object. * @return The string representation of the generated class. */ + @Override public String toString () { final FormattedWriter writerHelper = new FormattedWriter(); writeClassDeclaration(writerHelper); // class declaration writeMembers(writerHelper); // members - writerHelper.writeln("}"); // NOI18N // closing + writerHelper.writeln("}"); // closing writerHelper.writeln(); return writerHelper.toString(); @@ -274,17 +281,19 @@ private void addMethod (final String name, final int modifiers, writerHelper.writeComments(comments); // signature==null if we have an instance initializer - if (signature.length() > 0) + if (signature.length() > 0) { writerHelper.writeln(signature); + } - writerHelper.writeln("{"); // NOI18N + writerHelper.writeln("{"); // implementation - for (int i = 0; i < n; i++) + for (int i = 0; i < n; i++) { writerHelper.writeln(1, body[i]); + } // end - writerHelper.writeln("}"); // NOI18N + writerHelper.writeln("}"); methodList.add(writerHelper.toString()); } @@ -296,31 +305,33 @@ static private String createMethodSignature (final String name, int i, count = (parameterNames != null ? parameterNames.length : 0); final FormattedWriter writerHelper = new FormattedWriter(); - if (modifiers != 0) + if (modifiers != 0) { writerHelper.write(Modifier.toString(modifiers) + ' '); + } writerHelper.write(((returnType != null) ? - returnType + " " : "") + name); // NOI18N + returnType + " " : "") + name); // parameters - writerHelper.write(" ("); // NOI18N + writerHelper.write(" ("); for (i = 0; i < count; i++) { writeListElement(i, count, parameterTypes[i] + ' ' + parameterNames[i], writerHelper); } - writerHelper.write(")"); // NOI18N + writerHelper.write(")"); // exceptions count = (exceptions != null ? exceptions.length : 0); if (count > 0) { writerHelper.writeln(); - writerHelper.write(1, "throws "); // NOI18N + writerHelper.write(1, "throws "); - for (i = 0; i < count; i++) + for (i = 0; i < count; i++) { writeListElement(i, count, exceptions[i], writerHelper); + } } return writerHelper.toString(); @@ -331,28 +342,25 @@ static private void writeListElement (int i, int count, String string, { int indent = ((i == 0) ? 0 : 1); - if (i == (count - 1)) + if (i == (count - 1)) { writerHelper.write(indent, string); - else + } else { writerHelper.writeln(indent, string + COMMA_SEPARATOR); + } } - private List getMemberList (String memberType) - { - Object memberList = null; - if (!_maintainCategories) + private List getMemberList(String memberType) { + List memberList = null; + if (!_maintainCategories) { memberType = MIXED; - + } memberList = _members.get(memberType); - if (memberList == null) - { - memberList = new ArrayList(); - + if (memberList == null) { + memberList = new ArrayList<>(); _members.put(memberType, memberList); } - - return (List)memberList; + return memberList; } private void writeClassDeclaration (FormattedWriter writerHelper) @@ -361,19 +369,20 @@ private void writeClassDeclaration (FormattedWriter writerHelper) writerHelper.write(_classDeclarationBlock); // extends - if (_superclass != null) - writerHelper.writeln(1, "extends " + _superclass); // NOI18N + if (_superclass != null) { + writerHelper.writeln(1, "extends " + _superclass); + } // implements if ((_interfaces != null) && (_interfaces.size() > 0)) { - writerHelper.write(1, "implements "); // NOI18N + writerHelper.write(1, "implements "); writerHelper.write(StringHelper.arrayToSeparatedList( _interfaces, COMMA_SEPARATOR)); writerHelper.writeln(); } - writerHelper.writeln("{"); // NOI18N + writerHelper.writeln("{"); } private void writeMembers (FormattedWriter writerHelper) @@ -385,8 +394,8 @@ private void writeMembers (FormattedWriter writerHelper) writerHelper.writeList(1, getMemberList(CONSTRUCTOR)); writerHelper.writeList(1, getMemberList(METHOD)); writerHelper.writeList(1, getMemberList(INNER_CLASS)); - } - else + } else { writerHelper.writeList(1, getMemberList(MIXED), true); + } } } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaFileWriter.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaFileWriter.java index bf8899e25d8..8ba300622d5 100644 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaFileWriter.java +++ b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/generator/io/IOJavaFileWriter.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 */ -/* - * IOJavaFileWriter.java - * - * Created on November 14, 2001, 5:19 PM - */ - package com.sun.jdo.spi.persistence.utility.generator.io; import com.sun.jdo.spi.persistence.utility.generator.JavaClassWriter; @@ -42,18 +37,17 @@ * Use this interface in conjunction with one or more {@link JavaClassWriter} * instances to describe the class(es) in a java file. * - * @author raccah + * @author raccah 2001 */ -public class IOJavaFileWriter implements JavaFileWriter -{ +public class IOJavaFileWriter implements JavaFileWriter { + /** I18N message handler */ - private static final ResourceBundle _messages = - I18NHelper.loadBundle(IOJavaFileWriter.class); + private static final ResourceBundle _messages = I18NHelper.loadBundle(IOJavaFileWriter.class); private File _file; private String _packageBlock; - private List _importStatements = new ArrayList(); - private List _classes = new ArrayList(); + private List _importStatements = new ArrayList<>(); + private List _classes = new ArrayList<>(); /** Creates a new instance of IOJavaFileWriter. * @param file The file object which will be used at save time. @@ -75,6 +69,7 @@ public IOJavaFileWriter (File file) * by the implementation. Note that not all implementations will choose * to make use of this comment. */ + @Override public void setPackage (final String packageName, final String[] comments) { final FormattedWriter writerHelper = new FormattedWriter(); @@ -97,13 +92,15 @@ public void setPackage (final String packageName, final String[] comments) * by the implementation. Note that not all implementations will choose * to make use of this comment. */ + @Override public void addImport (final String importName, final String[] comments) { final FormattedWriter writerHelper = new FormattedWriter(); writerHelper.writeComments(comments); - if (importName != null && importName.length() > 0) + if (importName != null && importName.length() > 0) { writerHelper.writeln("import " + importName + ';'); // NOI18N + } _importStatements.add(writerHelper.toString()); } @@ -111,10 +108,12 @@ public void addImport (final String importName, final String[] comments) /** Adds a class to this source file. * @param classWriter The definition of the class. */ + @Override public void addClass (final JavaClassWriter classWriter) { - if (classWriter != null) + if (classWriter != null) { _classes.add(classWriter); + } } /** Saves the file by writing out the source contents to whatever @@ -122,6 +121,7 @@ public void addClass (final JavaClassWriter classWriter) * constructor of the implementation class. * @throws IOException If the file cannot be saved. */ + @Override public void save () throws IOException { if (_file != null) @@ -155,17 +155,19 @@ public void save () throws IOException /** Returns a string representation of this object. * @return The string representation of the generated file. */ + @Override public String toString () { final FormattedWriter writerHelper = new FormattedWriter(); // package block writerHelper.writeln(); - if (_packageBlock != null) + if (_packageBlock != null) { writerHelper.write(_packageBlock); + } - writerHelper.writeList(_importStatements); // imports - writerHelper.writeList(_classes); // classes + writerHelper.writeList(_importStatements); + writerHelper.writeList(_classes); return writerHelper.toString(); } diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLogger.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLogger.java deleted file mode 100644 index b04cab83f45..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLogger.java +++ /dev/null @@ -1,949 +0,0 @@ -/* - * Copyright (c) 2024 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 - * 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 - */ - -/* - * AbstractLogger.java - * - * Created on May 14, 2002, 12:35 PM - */ - -package com.sun.jdo.spi.persistence.utility.logging; - -import com.sun.jdo.spi.persistence.utility.StringHelper; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.text.MessageFormat; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.MissingResourceException; -import java.util.Properties; -import java.util.ResourceBundle; - -import org.glassfish.persistence.common.I18NHelper; - -import static org.glassfish.embeddable.GlassFishVariable.JAVA_HOME; - -/** - * This class provides a default implementation of the - * com.sun.jdo.spi.persistence.utility.logging.Logger interface which - * implements most methods and/or delegates them to a few - * abstract methods which subclasses must override. - * - * @author Rochelle Raccah - * @version %I% - */ -abstract public class AbstractLogger implements Logger -{ - /** I18N message handler for this class */ - private static final ResourceBundle _messages = - I18NHelper.loadBundle(AbstractLogger.class); - - /** Default level if none supplied */ - private static final int _defaultLevel = INFO; - - /** Level Separator for Logger Level specification */ - private static final char _levelSeparator='.'; - - private static Map _levelNamesToValues; - - private static boolean _hasLoggingProperties = true; - private static Properties _loggingProperties; - - /** Resource bundle for this (named) logger */ - private final ResourceBundle _bundle; - - /** Name for this logger */ - private final String _loggerName; - - /** Level for this logger */ - private final int _level; - - static - { - _levelNamesToValues = new HashMap(); - _levelNamesToValues.put("ALL", Integer.valueOf(ALL)); // NOI18N - _levelNamesToValues.put("FINEST", Integer.valueOf(FINEST)); // NOI18N - _levelNamesToValues.put("FINER", Integer.valueOf(FINER)); // NOI18N - _levelNamesToValues.put("FINE", Integer.valueOf(FINE)); // NOI18N - _levelNamesToValues.put("CONFIG", Integer.valueOf(CONFIG)); // NOI18N - _levelNamesToValues.put("INFO", Integer.valueOf(INFO)); // NOI18N - _levelNamesToValues.put("WARNING", Integer.valueOf(WARNING)); // NOI18N - _levelNamesToValues.put("SEVERE", Integer.valueOf(SEVERE)); // NOI18N - _levelNamesToValues.put("OFF", Integer.valueOf(OFF)); // NOI18N - } - - /** Creates a new AbstractLogger. The supplied class loader or the - * loader which loaded this class must be able to load the bundle. - * @param loggerName the full domain name of this logger - * @param bundleName the bundle name for message translation - * @param loader the loader used for looking up the bundle file - * and possibly the logging.properties or alternative file - */ - public AbstractLogger (String loggerName, String bundleName, - ClassLoader loader) - { - _loggerName = loggerName; - _level = readLoggingLevel(loggerName); - _bundle = I18NHelper.loadBundle(bundleName, loader); - } - - /** Get the message bundle for the AbstractLogger itself. - */ - protected static ResourceBundle getMessages () { return _messages; } - - private static Map getLevelNameMap () { return _levelNamesToValues; } - - // mostly copied from LogManager's readConfiguration() in jdk1.4 - private static synchronized Properties getLoggingProperties () - { - if (_hasLoggingProperties && (_loggingProperties == null)) - { - String fileName = - System.getProperty("java.util.logging.config.file"); - - if (fileName == null) - { - fileName = System.getProperty(JAVA_HOME.getSystemPropertyName()); - - if (fileName != null) - { - File file = new File(fileName, "lib"); - - file = new File(file, "logging.properties"); - - try - { - fileName = file.getCanonicalPath(); - } - catch (IOException ioe) - { - fileName = null; - } - } - } - - if (fileName != null) - { - InputStream inputStream = null; - - try - { - Properties properties = new Properties(); - BufferedInputStream bufferedInputStream = null; - - inputStream = new FileInputStream(fileName); - bufferedInputStream = new BufferedInputStream(inputStream); - properties.load(bufferedInputStream); - _loggingProperties = properties; - } - catch (Exception e) - { - _hasLoggingProperties = false; - } - finally - { - if (inputStream != null) - { - try - { - inputStream.close(); - } - catch (IOException ioe) - { - // couldn't close it for some reason - } - } - } - } else { - _hasLoggingProperties = false; - } - } - - return _loggingProperties; - } - - /** Return the string name of a level given its int value. - * @return a string representing the level - */ - public static String toString (int level) - { - String bundleKey = null; - - switch (level) - { - case Logger.OFF: - bundleKey = "utility.level_off"; // NOI18N - break; - case Logger.SEVERE: - bundleKey = "utility.level_severe"; // NOI18N - break; - case Logger.WARNING: - bundleKey = "utility.level_warning"; // NOI18N - break; - case Logger.INFO: - bundleKey = "utility.level_info"; // NOI18N - break; - case Logger.CONFIG: - bundleKey = "utility.level_config"; // NOI18N - break; - case Logger.FINE: - bundleKey = "utility.level_fine"; // NOI18N - break; - case Logger.FINER: - bundleKey = "utility.level_finer"; // NOI18N - break; - case Logger.FINEST: - bundleKey = "utility.level_finest"; // NOI18N - break; - case Logger.ALL: - bundleKey = "utility.level_all"; // NOI18N - break; - } - - return ((bundleKey != null) ? - I18NHelper.getMessage(getMessages(), bundleKey) : null); - } - - /** Get the message bundle for the named instance of the logger. - */ - protected ResourceBundle getBundle () { return _bundle; } - - public int getLevel () { return _level; } - - private int readLoggingLevel (String loggerName) - { - String value = findLevelMatch(loggerName); - int level = _defaultLevel; - - if (value != null) - { - Object lookupValue = null; - - value = value.trim(); - lookupValue = getLevelNameMap().get(value); - - if (lookupValue != null) { - level = ((Integer)lookupValue).intValue(); - } else // maybe a number was specified - { - try - { - level = Integer.parseInt(value); - } - catch (NumberFormatException nfe) - { - // level will be the default - } - } - } - - return level; - } - - /** Find the best matched logging level from the logging properties - *@param loggerName the name of the hierarchical - *@return a String representing the level value - */ - private String findLevelMatch (String loggerName) - { - Properties properties = getLoggingProperties(); - String value = null; - - if (properties != null) - { - while (value == null) - { - int lastIndex = loggerName.lastIndexOf(_levelSeparator); - - value = properties.getProperty(loggerName + ".level"); // NOI18N - - if (loggerName.trim().length() > 0) - { - loggerName = ((lastIndex == -1) ? "" : // NOI18N - loggerName.substring(0, lastIndex)); - } else { - return value; - } - } - } - - return value; - } - - /** Return whether logging is enabled at the FINE level. This method - * is not exact because to make it accurately reflect the logging level - * we would have to include the JDK 1.4 java.util.logging.Level class. - * This method does not delegate to isLoggable(FINE) for performance - * reasons. - * @return whether logging is enabled at the fine level. - */ - @Override - public boolean isLoggable () { return (FINE >= getLevel()); } - - /** - * Check if a message of the given level would actually be logged - * by this logger. This check is based on the Logger's effective level, - * which may be inherited from its parent. - * - * @return true if the given message level is currently being logged. - * @param levelValue the level to check - */ - @Override - public boolean isLoggable (int levelValue) - { - return (levelValue >= getLevel()); - } - - /** - * Log a method entry. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY", log level - * FINER, and the given sourceMethod and sourceClass is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - */ - @Override - public void entering (String sourceClass, String sourceMethod) - { - entering(sourceClass, sourceMethod, (Object[])null); - } - - /** - * Log a method entry, with one parameter. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY {0}", log level - * FINER, and the given sourceMethod, sourceClass, and parameter - * is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - * @param param1 parameter to the method being entered - */ - @Override - public void entering (String sourceClass, String sourceMethod, - Object param1) - { - if (isLoggable(FINER)) { - entering(sourceClass, sourceMethod, new Object[]{param1}); - } - } - - /** - * Log a method entry, with an array of parameters. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY" (followed by a - * format {N} indicator for each entry in the parameter array), - * log level FINER, and the given sourceMethod, sourceClass, and - * parameters is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - * @param params array of parameters to the method being entered - */ - @Override - public void entering (String sourceClass, String sourceMethod, - Object params[]) - { - if (isLoggable(FINER)) - { - MessageFormat messageFormat = null; - String messageKey = null; - String[] args = null; - - if ((params != null) && (params.length > 0)) - { - messageKey = "entering_method_params"; // NOI18N - args = new String[]{sourceClass, sourceMethod, - StringHelper.arrayToSeparatedList(Arrays.asList(params))}; - } - else - { - messageKey = "entering_method"; // NOI18N - args = new String[]{sourceClass, sourceMethod}; - } - - messageFormat = new MessageFormat( - getMessages().getString(messageKey)); - finer(messageFormat.format(args)); - } - } - - /** - * Log a method return. - *

    - * This is a convenience method that can be used to log returning - * from a method. A LogRecord with message "RETURN", log level - * FINER, and the given sourceMethod and sourceClass is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method - */ - @Override - public void exiting (String sourceClass, String sourceMethod) - { - exiting(sourceClass, sourceMethod, null); - } - - /** - * Log a method return, with result object. - *

    - * This is a convenience method that can be used to log returning - * from a method. A LogRecord with message "RETURN {0}", log level - * FINER, and the gives sourceMethod, sourceClass, and result - * object is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method - * @param result Object that is being returned - */ - @Override - public void exiting (String sourceClass, String sourceMethod, Object result) - { - if (isLoggable(FINER)) - { - MessageFormat messageFormat = null; - String messageKey = null; - Object[] args = null; - - if (result != null) - { - messageKey = "exiting_method_return"; // NOI18N - args = new Object[]{sourceClass, sourceMethod, result}; - } - else - { - messageKey = "exiting_method"; // NOI18N - args = new Object[]{sourceClass, sourceMethod}; - } - - messageFormat = new MessageFormat( - getMessages().getString(messageKey)); - finer(messageFormat.format(args)); - } - } - - /** - * Log throwing an exception. - *

    - * This is a convenience method to log that a method is - * terminating by throwing an exception. The logging is done - * using the FINER level. - *

    - * If the logger is currently enabled for the given message - * level then the given arguments are stored in a LogRecord - * which is forwarded to all registered output handlers. The - * LogRecord's message is set to "THROW". - *

    - * Note that the thrown argument is stored in the LogRecord thrown - * property, rather than the LogRecord parameters property. Thus is it - * processed specially by output Formatters and is not treated - * as a formatting parameter to the LogRecord message property. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method. - * @param thrown The Throwable that is being thrown. - */ - @Override - public void throwing (String sourceClass, String sourceMethod, - Throwable thrown) - { - if (isLoggable(FINER)) - { - MessageFormat messageFormat = new MessageFormat( - getMessages().getString("throwing_method")); - - log(FINER, messageFormat.format( - new String[]{sourceClass, sourceMethod}), thrown); - } - } - - /** - * Log a SEVERE message. - *

    - * If the logger is currently enabled for the SEVERE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void severe (String msg) { log(SEVERE, msg); } - - /** - * Log a WARNING message. - *

    - * If the logger is currently enabled for the WARNING message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void warning (String msg) { log(WARNING, msg); } - - /** - * Log an INFO message. - *

    - * If the logger is currently enabled for the INFO message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void info (String msg) { log(INFO, msg); } - - /** - * Log a CONFIG message. - *

    - * If the logger is currently enabled for the CONFIG message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void config (String msg) { log(CONFIG, msg); } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void log (int level, String msg) - { - if (isLoggable(level)) { - logInternal(level, getMessage(msg)); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - @Override - public void log (int level, String msg, Object o1) - { - if (isLoggable(level)) { - log(level, msg, new Object[]{o1}); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - @Override - public void log (int level, String msg, Object[] o) - { - if (isLoggable(level)) - { - int count = ((o == null) ? 0 : o.length); - String formattedMessage = msg; - - if (count > 0) - { - MessageFormat messageFormat = - new MessageFormat(getBundle().getString(msg)); - - if (messageFormat != null) { - formattedMessage = messageFormat.format(o); - } - } else { - formattedMessage = getMessage(msg); - } - - logInternal(level, formattedMessage); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - @Override - public void log (int level, String msg, Object o1, Object o2) - { - if (isLoggable(level)) { - log(level, msg, new Object[]{o1, o2}); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - @Override - public void log (int level, String msg, Object o1, Object o2, Object o3) - { - if (isLoggable(level)) { - log(level, msg, new Object[]{o1, o2, o3}); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message, and the exception dump, - * is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param thrown The exception to log - */ - @Override - abstract public void log (int level, String msg, Throwable thrown); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void fine (String msg) { log(FINE, msg); } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - @Override - public void fine (String msg, Object o1) { log(FINE, msg, o1); } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - @Override - public void fine (String msg, Object[] o) { log(FINE, msg, o); } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - @Override - public void fine (String msg, Object o1, Object o2) - { - log(FINE, msg, o1, o2); - } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - @Override - public void fine (String msg, Object o1, Object o2, Object o3) - { - log(FINE, msg, o1, o2, o3); - } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void finer (String msg) { log(FINER, msg); } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - @Override - public void finer (String msg, Object[] o) { log(FINER, msg, o); } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - @Override - public void finer (String msg, Object o1) { log(FINER, msg, o1); } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - @Override - public void finer (String msg, Object o1, Object o2) - { - log(FINER, msg, o1, o2); - } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - @Override - public void finer (String msg, Object o1, Object o2, Object o3) - { - log(FINER, msg, o1, o2, o3); - } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - @Override - public void finest (String msg) { log(FINEST, msg); } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - @Override - public void finest (String msg, Object[] o) { log(FINEST, msg, o); } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - @Override - public void finest (String msg, Object o1) { log(FINEST, msg, o1); } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - @Override - public void finest (String msg, Object o1, Object o2) - { - log(FINEST, msg, o1, o2); - } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - @Override - public void finest (String msg, Object o1, Object o2, Object o3) - { - log(FINEST, msg, o1, o2, o3); - } - - /** - * Get the name for this logger. - * @return logger name. Will be null for anonymous Loggers. - */ - @Override - public String getName () { return _loggerName; } - - /** Prepare a printable version of this instance. - * @return the String representation of this object - */ - @Override - public String toString () - { - StringBuffer buffer = new StringBuffer(getClass().getName()); - - buffer.append(": "); //NOI18N - buffer.append(" name: "); //NOI18N - buffer.append(getName()); - buffer.append(", logging level: "); //NOI18N - buffer.append(toString(getLevel())); - - return buffer.toString(); - } - - /** - * This method returns a string from the bundle file if possible, - * treating the message argument as the key. If no such key is found - * in the bundle, the message itself is returned. - * - * @return a message either used as itself or searched in the bundle file. - * @param message the message which is used as a key to search the bundle - */ - protected String getMessage (String message) - { - try - { - return getBundle().getString(message); - } - catch (MissingResourceException e) - { - return message; - } - - } - - /** - * This method returns a string with a formatted prefix which - * depends on the level. - * - * @return a formatted string with a level prefix. - * @param level the level to print - * @param message the message to print - * @see AbstractLogger#toString - */ - protected String getMessageWithPrefix (int level, String message) - { - MessageFormat messageFormat = new MessageFormat( - getMessages().getString("logging_prefix")); // NOI18N - - return messageFormat.format( - new String[]{toString(level), message}); - } - - /** - * This method does the actual logging. It is expected that if a - * check for isLoggable is desired for performance reasons, it has - * already been done, as it should not be done here. - * @param level the level to print - * @param message the message to print - */ - abstract protected void logInternal (int level, String message); -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLoggerFactory.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLoggerFactory.java deleted file mode 100644 index 6031eb3cc65..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/AbstractLoggerFactory.java +++ /dev/null @@ -1,97 +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 - */ - -/* - * AbstractLoggerFactory.java - * - * Created on May 13, 2002, 10:15 PM - */ - -package com.sun.jdo.spi.persistence.utility.logging; - -import java.util.HashMap; -import java.util.Map; - -/** - * - * @author Rochelle Raccah - * @version %I% - */ -abstract public class AbstractLoggerFactory implements LoggerFactory -{ - private final static String _domainPrefix = "com.sun.jdo."; //NOI18N - - private final static Map _loggerCache = new HashMap(); - - private static final String _bundleName = - "com.sun.jdo.spi.persistence.utility.logging.Bundle"; // NOI18N - - - /** Get the error logger which is used to log things during creation of - * loggers. - */ - protected static Logger getErrorLogger () - { - return LogHelper.getLogger("", _bundleName, // NOI18N - AbstractLoggerFactory.class.getClassLoader()); - } - - /** Get a Logger. The class that implements this interface is responsible - * for creating a logger for the named component. - * The bundle name and class loader are passed to allow the implementation - * to properly find and construct the internationalization bundle. - * @param relativeLoggerName the relative name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - public synchronized Logger getLogger (String relativeLoggerName, - String bundleName, ClassLoader loader) - { - String absoluteLoggerName = getAbsoluteLoggerName(relativeLoggerName); - Logger value = (Logger)_loggerCache.get(absoluteLoggerName); - - if (value == null) - { - value = createLogger(absoluteLoggerName, bundleName, loader); - - if (value != null) - _loggerCache.put(absoluteLoggerName, value); - } - - return value; - } - - /** Create a new Logger. Subclasses are responsible for creating a - * logger for the named component. The bundle name and class loader - * are passed to allow the implementation to properly find and - * construct the internationalization bundle. - * @param absoluteLoggerName the absolute name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - abstract protected Logger createLogger (String absoluteLoggerName, - String bundleName, ClassLoader loader); - - protected String getDomainRoot () { return _domainPrefix; } - - protected String getAbsoluteLoggerName (String relativeLoggerName) - { - return (relativeLoggerName.startsWith("java") ? //NOI18N - relativeLoggerName : (getDomainRoot() + relativeLoggerName)); - } -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Bundle.properties b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Bundle.properties deleted file mode 100644 index 1d6369eb436..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Bundle.properties +++ /dev/null @@ -1,71 +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 -# - - -############################################################################### -# -# Message ID Range: JDO82000 - JDO82999 -############################################################################### - - -# values for displaying log levels: -utility.level_off=OFF -utility.level_severe=SEVERE -utility.level_warning=WARNING -utility.level_info=INFO -utility.level_config=CONFIG -utility.level_fine=FINE -utility.level_finer=FINER -utility.level_finest=FINEST -utility.level_all=ALL - -#{0}=class name -#{1}=method name -entering_method=ENTRY: {0} {1} - -#{0}=class name -#{1}=method name -#{2}=a single method parameter or comma separated list of parameters -entering_method_params=ENTRY: {0} {1} {2} - -#{0}=class name -#{2}=method name -exiting_method=RETURN: {0} {1} - -#{0}=class name -#{1}=method name -#{2}=return result -exiting_method_return=RETURN: {0} {1} {2} - -#{0}=class name -#{1}=method name -throwing_method=THROW: {0} {1} - -#{0}=level from utility.level_* above -#{1}=logging message -logging_prefix={0}: {1} - -#{0}=logger name -errorlogger.create.exception=JDO82000: Exception creating logger {0} -JDO82000.diag.cause.1=System was not able to create specified logger. -JDO82000.diag.cause.2=Error loading message bundle that corresponds to this logger. -JDO82000.diag.check.1=Check that the classpath settings are not corrupted. -JDO82000.diag.check.2=Check error log for the detailed reason. - -#{0}=logger name -errorlogger.filehandler.initialize.exception=JDO82001: Exception while initializing FileHandler for logger {0} -#{0}=logger name -errorlogger.formatter.initialize.exception=JDO82002: Exception while initializing formatter for logger {0} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LogHelper.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LogHelper.java deleted file mode 100644 index 38ff3124716..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LogHelper.java +++ /dev/null @@ -1,88 +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.spi.persistence.utility.logging; - -/** This class manages the logging facility for JDO components. It is the - * class that keeps track of the log factory in use for getting loggers - * for use in JDO components. - *

    - * This class has no JDK 1.4 dependencies. - *

    - * The log factory is responsible for constructing the loggers and for - * ensuring that there is only one logger per component. - * - * @author Craig Russell - * @version 1.0 - */ - -public class LogHelper { - - /** Flag to tell we are running in JDK 1.4 and can use - * java.util.logging.Logger implementation. - */ - protected static boolean jdk14 = isJDK14(); - - /** LoggerFactory registered for creating new loggers. - */ - protected static LoggerFactory loggerFactory = null; - - /** Get a Logger. This call is delegated to the registered LoggerFactory. - * If there is no registered LoggerFactory, then initialize one based on - * whether we are running in JDK 1.4 (or higher). - * The bundle name and class loader are passed to allow the implementation - * to properly find and construct the internationalization bundle. - * This method is synchronized to avoid race conditions where two threads - * access a component using the same Logger at the same time. - * @param loggerName the relative name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - public synchronized static Logger getLogger(String loggerName, String bundleName, ClassLoader loader) { - // if an implementation has not registered a LoggerFactory, use a standard one. - if (loggerFactory == null) { - if (jdk14) { - loggerFactory = new LoggerFactoryJDK14(); - } else { - loggerFactory = new LoggerFactoryJDK13(); - } - } - return loggerFactory.getLogger(loggerName, bundleName, loader); - } - - /** Register a LoggerFactory for use in managed environments or - * for special situations. This - * factory will be delegated to for all getLogger requests. - * @param factory the LoggerFactory to use for all getLogger requests - */ - public static void registerLoggerFactory (LoggerFactory factory) { - loggerFactory = factory; - } - - /** Check to see if the JDK 1.4 logging environment is available. - * @return true if JDK 1.4 logging is available - */ - public static boolean isJDK14() { - try { - Class.forName("java.util.logging.Logger"); //NOI18N - return true; - } catch (ClassNotFoundException ex) { - return false; - } - } - -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Logger.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Logger.java deleted file mode 100644 index c2f56958b89..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/Logger.java +++ /dev/null @@ -1,556 +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.spi.persistence.utility.logging; - -/** This interface provides an isolation layer between the JDO components - * that need logging services and the implementation of those services. - *

    - * The JDO Logger interface contains a small number of convenience methods - * in addition to a subset of the - * methods in the java.util.logging.Logger class, and can therefore - * be implemented in a very straightforward way by a subclass of the - * java.util.logging.Logger class. - * There is one instance of the implementing class for each subsystem - * in JDO. - *

    - * This interface has no JDK 1.4 dependencies. - */ - -public interface Logger { - - /** Levels are defined as ints to avoid including the java.util.logging.Level - * class in this package. - */ - - /** - * OFF is a special level that can be used to turn off logging. - */ - public static final int OFF = Integer.MAX_VALUE; - - /** - * SEVERE is a message level indicating a serious failure. - *

    - * In general SEVERE messages should describe events that are - * of considerable importance and which will prevent normal - * program execution. They should be reasonably intelligible - * to end users and to system administrators. - */ - public static final int SEVERE = 1000; - - /** - * WARNING is a message level indicating a potential problem. - *

    - * In general WARNING messages should describe events that will - * be of interest to end users or system managers, or which - * indicate potential problems. - */ - public static final int WARNING = 900; - - /** - * INFO is a message level for informational messages. - *

    - * Typically INFO messages will be written to the console - * or its equivalent. So the INFO level should only be - * used for reasonably significant messages that will - * make sense to end users and system admins. - */ - public static final int INFO = 800; - - /** - * CONFIG is a message level for static configuration messages. - *

    - * CONFIG messages are intended to provide a variety of static - * configuration information, to assist in debugging problems - * that may be associated with particular configurations. - * For example, CONFIG message might include the CPU type, - * the graphics depth, the GUI look-and-feel, etc. - */ - public static final int CONFIG = 700; - - /** - * FINE is a message level providing tracing information. - *

    - * All of FINE, FINER, and FINEST are intended for relatively - * detailed tracing. The exact meaning of the three levels will - * vary between subsystems, but in general, FINEST should be used - * for the most voluminous detailed output, FINER for somewhat - * less detailed output, and FINE for the lowest volume (and - * most important) messages. - *

    - * In general the FINE level should be used for information - * that will be broadly interesting to developers who do not have - * a specialized interest in the specific subsystem. - *

    - * FINE messages might include things like minor (recoverable) - * failures. Issues indicating potential performance problems - * are also worth logging as FINE. - */ - public static final int FINE = 500; - - /** - * FINER indicates a fairly detailed tracing message. - * By default logging calls for entering, returning, or throwing - * an exception are traced at this level. - */ - public static final int FINER = 400; - - /** - * FINEST indicates a highly detailed tracing message - */ - public static final int FINEST = 300; - - /** - * ALL indicates that all messages should be logged. - */ - public static final int ALL = Integer.MIN_VALUE; - - /** Test if this logger is logging messages. This is a test for - * log level FINE, FINER, or FINEST. If the log message is expensive to construct, - * this method should be used to determine whether it is a waste of time. - * We don't expose isLoggable(Level) because Level is not available in - * JDK 1.3. Once this is not an issue, we can add isLoggable(Level). - * @return if FINE, FINER, or FINEST is currently being logged - */ - public boolean isLoggable(); - - /** Test if this logger is logging messages at the specific level. - * If the log message is expensive to construct, - * this method should be used to determine whether it is a waste of time. - * We don't expose isLoggable(Level) because Level is not available in - * JDK 1.3. Once this is not an issue, we can add isLoggable(Level). - * @return if this level is currently being logged - * @param level The level to be tested */ - public boolean isLoggable(int level); - - - //====================================================================== - // Start of convenience methods for logging. - //====================================================================== - - /** - * Log a method entry. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY", log level - * FINER, and the given sourceMethod and sourceClass is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - */ - public void entering(String sourceClass, String sourceMethod); - - /** - * Log a method entry, with one parameter. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY {0}", log level - * FINER, and the given sourceMethod, sourceClass, and parameter - * is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - * @param param1 parameter to the method being entered - */ - public void entering(String sourceClass, String sourceMethod, Object param1); - - /** - * Log a method entry, with an array of parameters. - *

    - * This is a convenience method that can be used to log entry - * to a method. A LogRecord with message "ENTRY" (followed by a - * format {N} indicator for each entry in the parameter array), - * log level FINER, and the given sourceMethod, sourceClass, and - * parameters is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of method that is being entered - * @param params array of parameters to the method being entered - */ - public void entering(String sourceClass, String sourceMethod, Object params[]); - - /** - * Log a method return. - *

    - * This is a convenience method that can be used to log returning - * from a method. A LogRecord with message "RETURN", log level - * FINER, and the given sourceMethod and sourceClass is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method - */ - public void exiting(String sourceClass, String sourceMethod); - - - /** - * Log a method return, with result object. - *

    - * This is a convenience method that can be used to log returning - * from a method. A LogRecord with message "RETURN {0}", log level - * FINER, and the gives sourceMethod, sourceClass, and result - * object is logged. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method - * @param result Object that is being returned - */ - public void exiting(String sourceClass, String sourceMethod, Object result); - - /** - * Log throwing an exception. - *

    - * This is a convenience method to log that a method is - * terminating by throwing an exception. The logging is done - * using the FINER level. - *

    - * If the logger is currently enabled for the given message - * level then the given arguments are stored in a LogRecord - * which is forwarded to all registered output handlers. The - * LogRecord's message is set to "THROW". - *

    - * Note that the thrown argument is stored in the LogRecord thrown - * property, rather than the LogRecord parameters property. Thus is it - * processed specially by output Formatters and is not treated - * as a formatting parameter to the LogRecord message property. - *

    - * @param sourceClass name of class that issued the logging request - * @param sourceMethod name of the method. - * @param thrown The Throwable that is being thrown. - */ - public void throwing(String sourceClass, String sourceMethod, Throwable thrown); - - /** - * Log a SEVERE message. - *

    - * If the logger is currently enabled for the SEVERE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void severe(String msg); - - /** - * Log a WARNING message. - *

    - * If the logger is currently enabled for the WARNING message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void warning(String msg); - - /** - * Log an INFO message. - *

    - * If the logger is currently enabled for the INFO message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void info(String msg); - - /** - * Log a CONFIG message. - *

    - * If the logger is currently enabled for the CONFIG message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void config(String msg); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - */ - public void log(int level, String msg); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void log(int level, String msg, Object[] o); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1, Object o2); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1, Object o2, Object o3); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message, and the exception dump, - * is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param thrown The exception to log - */ - public void log(int level, String msg, Throwable thrown ); - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void fine(String msg); - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1); - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void fine(String msg, Object[] o); - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1, Object o2); - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1, Object o2, Object o3); - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void finer(String msg); - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void finer(String msg, Object[] o); - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1); - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1, Object o2); - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1, Object o2, Object o3); - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - */ - public void finest(String msg); - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void finest(String msg, Object[] o); - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1); - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1, Object o2); - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1, Object o2, Object o3); - - //================================================================ - // End of convenience methods - //================================================================ - - /** - * Get the name for this logger. - * @return logger name. Will be null for anonymous Loggers. - */ - public String getName(); - -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactory.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactory.java deleted file mode 100644 index 5e200c549f1..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactory.java +++ /dev/null @@ -1,41 +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.spi.persistence.utility.logging; - -/** This interface provides for isolation between the JDO components that - * need logging services and the implementation of the service. - *

    - * This interface has no JDK 1.4 dependencies. - * - * @author Craig Russell - * @version 1.0 - */ - -public interface LoggerFactory { - - /** Get a Logger. The class that implements this interface is responsible - * for creating a logger for the named component. - * The bundle name and class loader are passed to allow the implementation - * to properly find and construct the internationalization bundle. - * @param loggerName the relative name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - Logger getLogger (String loggerName, String bundleName, ClassLoader loader); -} - diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK13.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK13.java deleted file mode 100644 index bd6a3bef998..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK13.java +++ /dev/null @@ -1,46 +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.spi.persistence.utility.logging; - -/** This is a factory which constructs Loggers suitable for JDK1.3. - * - * @author Craig Russell - * @version 1.0 - */ -public class LoggerFactoryJDK13 extends AbstractLoggerFactory -{ - /** Creates new LoggerFactoryJDK13 */ - public LoggerFactoryJDK13 () - { - } - - /** Create a new Logger. Subclasses are responsible for creating a - * logger for the named component. The bundle name and class loader - * are passed to allow the implementation to properly find and - * construct the internationalization bundle. - * @param absoluteLoggerName the absolute name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - protected Logger createLogger (String absoluteLoggerName, - String bundleName, ClassLoader loader) - { - return new LoggerJDK13(absoluteLoggerName, bundleName, loader); - } -} - diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK14.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK14.java deleted file mode 100644 index 8ad7ca820ae..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerFactoryJDK14.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * 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 - * 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.spi.persistence.utility.logging; - -import java.text.MessageFormat; -import java.util.ResourceBundle; -import java.util.logging.FileHandler; -import java.util.logging.Formatter; -import java.util.logging.Level; -import java.util.logging.LogManager; -import java.util.logging.SimpleFormatter; - -import org.glassfish.persistence.common.I18NHelper; - -/** - * - * @author Craig Russell - * @version 1.0 - */ - -public class LoggerFactoryJDK14 extends AbstractLoggerFactory { - - /** I18N message handler for this class */ - private static final ResourceBundle _messages = - I18NHelper.loadBundle(LoggerFactoryJDK14.class); - - /** Get the message bundle for the AbstractLogger itself. - */ - protected static ResourceBundle getMessages () { return _messages; } - - /** Creates new LoggerFactory */ - public LoggerFactoryJDK14() { - } - - protected LoggerJDK14 findLogger(String absoluteLoggerName) { - return (LoggerJDK14) - LogManager.getLogManager().getLogger(absoluteLoggerName); - } - - /** Create a new Logger. create a logger for the named component. - * The bundle name and class loader are passed to allow the implementation - * to properly find and construct the internationalization bundle. - * This operation is executed as a privileged action to allow - * permission access for the following operations: - * - * LogManager.getLogManager().addLogger - this might do checkAccess. - * new FileHandler - * FileHandler.setLevel - * FileHandler.setFormatter - * Logger.addHandler - * - * @param absoluteLoggerName the absolute name of this logger - * @param bundleName the fully qualified name of the resource bundle - * @param loader the class loader used to load the resource bundle, or null - * @return the logger - */ - @Override - protected Logger createLogger (final String absoluteLoggerName, - final String bundleName, final ClassLoader loader) { - LoggerJDK14 logger = null; - ClassLoader pushed = Thread.currentThread().getContextClassLoader(); - if (loader != null) { - setContextClassLoader(loader); - } - try { - logger = createLogger(absoluteLoggerName, bundleName); - LogManager.getLogManager().addLogger(logger); - configureFileHandler(logger); - - return logger; - } catch (Exception ex) { - MessageFormat messageFormat = new MessageFormat(getMessages().getString("errorlogger.create.exception")); - getErrorLogger().log(Logger.SEVERE, messageFormat.format(new String[] {absoluteLoggerName}), ex); - } finally { - setContextClassLoader(pushed); - } - return logger; - } - - /** - * This method throws SecurityException if a security manager exists and if - * the caller does not have LoggingPermission("control")) or the - * calling code is not placed in the doPrivileged() block. - */ - protected void setContextClassLoader (final ClassLoader loader) { - if (loader != null) { - Thread.currentThread().setContextClassLoader (loader); - } - } //setContextClassLoader - - - protected LoggerJDK14 createLogger (String absoluteLoggerName, String - bundleName) { - LoggerJDK14 result = new LoggerJDK14(absoluteLoggerName, bundleName); - return result; - } - - /** - * This method throws SecurityException if a security manager exists and if - * the caller does not have LoggingPermission("control")) or the - * calling code is not placed in the doPrivileged() block. - */ - protected void configureFileHandler(LoggerJDK14 logger) { - String name = logger.getName(); - String baseName = name + ".FileHandler"; //NOI18N - LogManager logManager = LogManager.getLogManager(); - - String pattern = logManager.getProperty(baseName + ".pattern"); //NOI18N - if(pattern != null) { - //If pattern != null, create and attach a FileHandler to logger. - //Look various properties . If not found, fall back to - //defaults - - int defaultLimit = 0; - String limit = logManager.getProperty(baseName + ".limit"); //NOI18N - if(limit != null) { - try { - defaultLimit = Integer.parseInt(limit); - if(defaultLimit < 0) { - defaultLimit = 0; - } - } - catch (NumberFormatException e) { - } - } - - int defaultCount = 1; - String count = logManager.getProperty(baseName + ".count"); //NOI18N - if(count != null) { - try { - defaultCount = Integer.parseInt(count); - if(defaultCount < 1) { - defaultCount = 1; - } - } - catch (NumberFormatException e) { - } - } - - boolean defaultAppend = false; - String append = logManager.getProperty(baseName + ".append"); //NOI18N - if(append != null) { - defaultAppend = Boolean.valueOf(append).booleanValue(); - } - - FileHandler fileHandler = null; - try { - fileHandler = new FileHandler(pattern, defaultLimit, - defaultCount, defaultAppend); - } - catch(Exception e) { - MessageFormat messageFormat = new MessageFormat( getMessages().getString( - "errorlogger.filehandler.initialize.exception")); //NOI18N - - getErrorLogger().log(Logger.WARNING, - messageFormat.format(new String[]{name}), e); - } - - if(fileHandler != null) { - //Initialize various attributes for the new fileHandler - //--Level - String level = logManager.getProperty(baseName + ".level"); //NOI18N - if (level != null) { - try { - fileHandler.setLevel(Level.parse(level) ); - } - catch(IllegalArgumentException e) { - } - } - - //--Formatter - Formatter defaultFormatter = null; - //Initialize various attributes for the new fileHandler - String formatter = logManager.getProperty(baseName + ".formatter"); //NOI18N - if(formatter != null) { - try { - Class clz = ClassLoader.getSystemClassLoader().loadClass(formatter); - defaultFormatter = (Formatter) clz.newInstance(); - } catch (Exception e) { - // We got one of a variety of exceptions in creating the - // class or creating an instance. - // Drop through. - MessageFormat messageFormat = new MessageFormat( - getMessages().getString("errorlogger.formatter.initialize.exception")); - - getErrorLogger().log(Logger.WARNING, messageFormat.format(new String[]{name}), e); - } - - } - - if (defaultFormatter == null) { - defaultFormatter = new SimpleFormatter(); - } - - try { - fileHandler.setFormatter(defaultFormatter); - } - catch(IllegalArgumentException e) { - } - - logger.addHandler(fileHandler); - - } //if(fileHandler != null) - - } //if(pattern != null) - - } -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK13.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK13.java deleted file mode 100644 index 38d169192f0..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK13.java +++ /dev/null @@ -1,90 +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 - */ - -/* - * LoggerJDK13.java - * - * Created on May 15, 2002, 2:00 PM - */ - -package com.sun.jdo.spi.persistence.utility.logging; - -import java.io.PrintStream; - -/** - * This class provides an implementation of the - * com.sun.jdo.spi.persistence.utility.Logger interface which - * subclasses the AbstractLogger and provides an implementation of - * its abstract methods which logs to a PrintStream (System.out). - * Note that this logger doesn't explicitly flush the PrintStream and - * depends on the JVM for flushing. - * - * @author Rochelle Raccah - * @version %I% - */ -public class LoggerJDK13 extends AbstractLogger -{ - private static final PrintStream _printStream = System.out; - - /** Creates a new LoggerJDK13. The supplied class loader or the - * loader which loaded this class must be able to load the bundle. - * @param loggerName the full domain name of this logger - * @param bundleName the bundle name for message translation - * @param loader the loader used for looking up the bundle file - * and possibly the logging.properties or alternative file - */ - public LoggerJDK13 (String loggerName, String bundleName, - ClassLoader loader) - { - super(loggerName, bundleName, loader); - } - - private static PrintStream getPrintStream () { return _printStream; } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message, and the exception dump, - * is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param thrown The exception to log - */ - public synchronized void log (int level, String msg, Throwable thrown) - { - if (isLoggable(level)) - { - logInternal(level, getMessage(msg)); - thrown.printStackTrace(getPrintStream()); - } - } - - /** - * This method does the actual logging. It is expected that if a - * check for isLoggable is desired for performance reasons, it has - * already been done, as it should not be done here. This - * implementation uses a print stream for logging. - * @param level the level to print - * @param message the message to print - */ - protected synchronized void logInternal (int level, String message) - { - getPrintStream().println(getMessageWithPrefix(level, message)); - } -} diff --git a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK14.java b/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK14.java deleted file mode 100644 index 2beca30b6bb..00000000000 --- a/appserver/persistence/cmp/utility/src/main/java/com/sun/jdo/spi/persistence/utility/logging/LoggerJDK14.java +++ /dev/null @@ -1,476 +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.spi.persistence.utility.logging; - -import java.util.logging.Level; - -/** - * This class is used with JDK 1.4 (and higher) programs to log messages from - * jdo components. It extends a java.util.logging.Logger which does - * the actual logging. - * - * @author Craig Russell - * @version 1.0 - */ -public class LoggerJDK14 extends java.util.logging.Logger implements Logger { - - /** Class that issued logging call; set by inferCaller. */ - protected String sourceClassName; - - /** Method that issued logging call; set by inferCaller. */ - protected String sourceMethodName; - - /** Creates new LoggerJDK14. The Thread context class loader or the - * loader which loaded this class must be able to load the bundle. - * @param loggerName the full domain name of this logger - * @param bundleName the bundle name for message translation - */ - public LoggerJDK14(String loggerName, String bundleName) { - super (loggerName, bundleName); - } - - /** Return whether logging is enabled - * at the FINE level. This method - * is not exact because to make it - * accurately reflect the logging level - * we would have to include the JDK 1.4 - * java.util.logging.Level class. - * @return whether logging is enabled at the fine level. - */ - public boolean isLoggable() { - return isLoggable(Level.FINE); - } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void fine(String msg, Object[] o) { - if (isLoggable(Level.FINE)) { - inferCaller(); - logp(Level.FINE, sourceClassName, sourceMethodName, msg, o); - } - } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1) { - if (isLoggable(Level.FINE)) { - inferCaller(); - logp(Level.FINE, sourceClassName, sourceMethodName, msg, o1); - } - } - - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1, Object o2) { - if (isLoggable(Level.FINE)) { - inferCaller(); - logp(Level.FINE, sourceClassName, sourceMethodName, msg, new Object[]{o1, o2}); - } - } - - /** - * Log a FINE message. - *

    - * If the logger is currently enabled for the FINE message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void fine(String msg, Object o1, Object o2, Object o3) { - if (isLoggable(Level.FINE)) { - inferCaller(); - logp(Level.FINE, sourceClassName, sourceMethodName, msg, new Object[]{o1, o2, o3}); - } - } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void finer(String msg, Object[] o) { - if (isLoggable(Level.FINER)) { - inferCaller(); - logp(Level.FINER, sourceClassName, sourceMethodName, msg, o); - } - } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1) { - if (isLoggable(Level.FINER)) { - inferCaller(); - logp(Level.FINER, sourceClassName, sourceMethodName, msg, o1); - } - } - - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1, Object o2) { - if (isLoggable(Level.FINER)) { - inferCaller(); - logp(Level.FINER, sourceClassName, sourceMethodName, msg, - new Object[]{o1, o2}); - } - } - - /** - * Log a FINER message. - *

    - * If the logger is currently enabled for the FINER message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void finer(String msg, Object o1, Object o2, Object o3) { - if (isLoggable(Level.FINER)) { - inferCaller(); - logp(Level.FINER, sourceClassName, sourceMethodName, msg, - new Object[]{o1, o2, o3}); - } - } - - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void finest(String msg, Object[] o) { - if (isLoggable(Level.FINEST)) { - inferCaller(); - logp(Level.FINEST, sourceClassName, sourceMethodName, msg, o); - } - } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1) { - if (isLoggable(Level.FINEST)) { - inferCaller(); - logp(Level.FINEST, sourceClassName, sourceMethodName, msg, o1); - } - } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1, Object o2) { - if (isLoggable(Level.FINEST)) { - inferCaller(); - logp(Level.FINEST, sourceClassName, sourceMethodName, msg, - new Object[]{o1, o2}); - } - } - - /** - * Log a FINEST message. - *

    - * If the logger is currently enabled for the FINEST message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void finest(String msg, Object o1, Object o2, Object o3) { - if (isLoggable(Level.FINEST)) { - inferCaller(); - logp(Level.FINEST, sourceClassName, sourceMethodName, msg, - new Object[]{o1, o2, o3}); - } - } - - /** Prepare a printable version of this instance. - * @return the String representation of this object - */ - public String toString() { - StringBuffer buf = new StringBuffer ("LoggerJDK14: "); //NOI18N - buf.append (" name: "); buf.append (getName()); //NOI18N - buf.append (", super: "); buf.append (super.toString()); //NOI18N - buf.append (", logging level: "); buf.append (getLevel()); //NOI18N - return buf.toString(); - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1) { - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg, o1); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1, Object o2) { - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg, new Object[]{o1, o2}); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o1 A parameter to be inserted into the message - * @param o2 A parameter to be inserted into the message - * @param o3 A parameter to be inserted into the message - */ - public void log(int level, String msg, Object o1, Object o2, Object o3) { - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg, - new Object[] {o1, o2, o3}); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param o Objects to be inserted into the message - */ - public void log(int level, String msg, Object[] o) { - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg, o); - } - } - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - */ - public void log(int level, String msg) { - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg); - } - } - - - /** - * Log a message. - *

    - * If the logger is currently enabled for the message - * level then the given message, and the exception dump, - * is forwarded to all the - * registered output Handler objects. - *

    - * @param level The level for this message - * @param msg The string message (or a key in the message catalog) - * @param thrown The exception to log - */ - public void log(int level, String msg, Throwable thrown ){ - Level lvl = convertLevel(level); - if (isLoggable(lvl)) { - inferCaller(); - logp(lvl, sourceClassName, sourceMethodName, msg, thrown); - } - } - - /** - * Check if a message of the given level would actually be logged - * by this logger. This check is based on the Loggers effective level, - * which may be inherited from its parent. - * - * @return true if the given message level is currently being logged. - * @param levelValue the level to check - */ - public boolean isLoggable(int levelValue) { - return isLoggable(convertLevel(levelValue)); - } - - /** Convert an int level used by jdo logger to the Level instance used - * by JDK 1.4 logger. - * This is done to allow components to use logging outside the JDK 1.4 - * environment. - * @param level the level to convert - * @return the Level instance corresponding to the int level - */ - protected Level convertLevel(int level) { - switch (level) { - case 300: return Level.FINEST; - case 400: return Level.FINER; - case 500: return Level.FINE; - case 700: return Level.CONFIG; - case 800: return Level.INFO; - case 900: return Level.WARNING; - case 1000: return Level.SEVERE; - default: return Level.CONFIG; - } - } - - /** - * Method to infer the caller's class name and method name. - * The method analyses the current stack trace, to find the method that - * issued the logger call. It stores the callers class and method name - * into fields sourceClassName and sourceMethodName. - */ - protected void inferCaller() { - // Get the stack trace. - StackTraceElement[] stack = (new Throwable()).getStackTrace(); - // Search for the first frame before the "Logger" class. - for(int ix = 0; ix < stack.length; ix++) { - StackTraceElement frame = stack[ix]; - String cname = frame.getClassName(); - if (!isLoggerClass(cname)) { - // We've found the relevant frame. - sourceClassName = cname; - sourceMethodName = frame.getMethodName(); - return; - } - } - } - - /** - * This method is a helper method for {@link #inferCaller}. It returns - * true if the specified class name denotes a logger class - * that should be ignored when analysing the stack trace to infer the - * caller of a log message. - * @param className the class name to be checked. - * @return true if the specified name denotes a logger class; - * false otherwise. - */ - protected boolean isLoggerClass(String className) - { - return "com.sun.jdo.spi.persistence.utility.logging.LoggerJDK14". //NOI18N - equals(className); - } -} diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanHomeImpl.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanHomeImpl.java index 75001df837e..fc61e8ad745 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanHomeImpl.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanHomeImpl.java @@ -32,7 +32,7 @@ */ public class EntityBeanHomeImpl extends EJBHomeInvocationHandler { - EntityBeanHomeImpl(EjbDescriptor ejbDescriptor, Class homeIntfClass) throws Exception { + EntityBeanHomeImpl(EjbDescriptor ejbDescriptor, Class homeIntfClass) throws Exception { super(ejbDescriptor, homeIntfClass); } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanLocalHomeImpl.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanLocalHomeImpl.java index caac9781c84..9c49cfce618 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanLocalHomeImpl.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityBeanLocalHomeImpl.java @@ -34,7 +34,7 @@ */ public class EntityBeanLocalHomeImpl extends EJBLocalHomeInvocationHandler { - protected EntityBeanLocalHomeImpl(EjbDescriptor ejbDescriptor, Class localHomeIntf) throws Exception { + protected EntityBeanLocalHomeImpl(EjbDescriptor ejbDescriptor, Class localHomeIntf) throws Exception { super(ejbDescriptor, localHomeIntf); } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java index 3b7b7b42029..5ffbcf37a0a 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/EntityContainer.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2022, 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 @@ -144,9 +144,9 @@ public class EntityContainer extends BaseContainer implements CacheListener { - private final ThreadLocal ejbServant = new ThreadLocal() { + private final ThreadLocal ejbServant = new ThreadLocal<>() { @Override - protected Object initialValue() { + protected EJBObjectImpl initialValue() { return null; } }; @@ -167,7 +167,7 @@ protected Object initialValue() { protected EJBObjectCache ejbLocalObjectStore; // protected LIFOChannel channel = null; - protected Stack passivationCandidates = new Stack(); + protected Stack passivationCandidates = new Stack<>(); // table of EJBs (Contexts) in READY state, key is primary key protected Cache readyStore; @@ -264,7 +264,7 @@ protected void preInitialize(EjbDescriptor desc, ClassLoader loader) { @Override protected void setEJBMetaData() throws Exception { EjbEntityDescriptor ed = (EjbEntityDescriptor) ejbDescriptor; - Class primaryKeyClass = loader.loadClass(ed.getPrimaryKeyClassName()); + Class primaryKeyClass = loader.loadClass(ed.getPrimaryKeyClassName()); metadata = new EJBMetaDataImpl(ejbHomeStub, homeIntf, remoteIntf, primaryKeyClass); } @@ -286,7 +286,7 @@ protected void validateTxAttr(MethodDescriptor md, int txAttr) throws EJBExcepti } @Override - protected void adjustHomeTargetMethodInfo(InvocationInfo invInfo, String methodName, Class[] paramTypes) throws NoSuchMethodException { + protected void adjustHomeTargetMethodInfo(InvocationInfo invInfo, String methodName, Class[] paramTypes) throws NoSuchMethodException { if (invInfo.startsWithCreate) { String extraCreateChars = methodName.substring("create".length()); invInfo.targetMethod2 = ejbClass.getMethod("ejbPostCreate" + extraCreateChars, paramTypes); @@ -295,12 +295,12 @@ protected void adjustHomeTargetMethodInfo(InvocationInfo invInfo, String methodN } @Override - protected EJBHomeInvocationHandler getEJBHomeInvocationHandler(Class homeIntfClass) throws Exception { + protected EJBHomeInvocationHandler getEJBHomeInvocationHandler(Class homeIntfClass) throws Exception { return new EntityBeanHomeImpl(ejbDescriptor, homeIntfClass); } @Override - protected EJBLocalHomeInvocationHandler getEJBLocalHomeInvocationHandler(Class homeIntfClass) throws Exception { + protected EJBLocalHomeInvocationHandler getEJBLocalHomeInvocationHandler(Class homeIntfClass) throws Exception { return new EntityBeanLocalHomeImpl(ejbDescriptor, homeIntfClass); } @@ -830,7 +830,7 @@ public Object postFind(EjbInvocation inv, Object primaryKeys, Object[] findParam if (primaryKeys instanceof Enumeration) { // create Enumeration of objrefs from Enumeration of primaryKeys - Enumeration e = (Enumeration) primaryKeys; + Enumeration e = (Enumeration) primaryKeys; // this is a portable Serializable Enumeration ObjrefEnumeration objrefs = new ObjrefEnumeration(); while (e.hasMoreElements()) { @@ -850,9 +850,9 @@ public Object postFind(EjbInvocation inv, Object primaryKeys, Object[] findParam return objrefs; } else if (primaryKeys instanceof Collection) { // create Collection of objrefs from Collection of primaryKeys - Collection c = (Collection) primaryKeys; - Iterator it = c.iterator(); - ArrayList objrefs = new ArrayList(); // a Serializable Collection + Collection c = (Collection) primaryKeys; + Iterator it = c.iterator(); + ArrayList objrefs = new ArrayList<>(); // a Serializable Collection while (it.hasNext()) { Object primaryKey = it.next(); Object ref; @@ -989,7 +989,7 @@ protected void removeBean(EJBLocalRemoteObject ejbo, Method removeMethod, boolea // Method must be a remove method defined on one of : // jakarta.ejb.EJBHome, jakarta.ejb.EJBObject, jakarta.ejb.EJBLocalHome, // jakarta.ejb.EJBLocalObject - Class declaringClass = removeMethod.getDeclaringClass(); + Class declaringClass = removeMethod.getDeclaringClass(); i.isHome = ((declaringClass == jakarta.ejb.EJBHome.class) || (declaringClass == jakarta.ejb.EJBLocalHome.class)); try { @@ -1480,7 +1480,7 @@ protected void postInvokeNoTx(EjbInvocation inv) { @Override protected void adjustInvocationInfo(InvocationInfo invInfo, Method method, int txAttr, boolean flushEnabled, String methodIntf, - Class originalIntf) throws EJBException { + Class originalIntf) throws EJBException { invInfo.isHomeFinder = isHomeFinder(method); } @@ -1489,7 +1489,7 @@ protected void adjustInvocationInfo(InvocationInfo invInfo, Method method, int t // Note: this method object is of the EJB's remote/home/local interfaces, // not the EJB class. private final boolean isHomeFinder(Method method) { - Class methodClass = method.getDeclaringClass(); + Class methodClass = method.getDeclaringClass(); if (isRemote) { if ((hasRemoteHomeView && methodClass.isAssignableFrom(homeIntf)) && (methodClass != EJBHome.class) && (!method.getName().startsWith("create"))) { @@ -1727,7 +1727,7 @@ private EJBObjectImpl internalGetEJBObjectImpl(Object primaryKey, byte[] streamK // This is necessary to prevent infinite recursion // because PRO.narrow calls is_a which calls the // ProtocolMgr which calls getEJBObject. - ejbObjImpl = (EJBObjectImpl) ejbServant.get(); + ejbObjImpl = ejbServant.get(); if (ejbObjImpl != null) { return ejbObjImpl; } @@ -2198,7 +2198,7 @@ protected void doConcreteContainerShutdown(boolean appBeingUndeployed) { // destroy all EJBObject refs try { - Iterator elements = ejbObjectStore.values(); + Iterator elements = ejbObjectStore.values(); while (elements.hasNext()) { EJBObjectImpl ejbObjImpl = (EJBObjectImpl) elements.next(); try { @@ -2580,7 +2580,7 @@ protected class LocalEJBObjectCacheVictimHandler implements EJBObjectCacheListen protected Object lock = new Object(); protected boolean addedTask = false; - protected ArrayList keys = new ArrayList(16); + protected ArrayList keys = new ArrayList<>(16); protected LocalEJBObjectCacheVictimHandler() { } @@ -2592,7 +2592,7 @@ public void handleOverflow(Object key) { } @Override - public void handleBatchOverflow(ArrayList paramKeys) { + public void handleBatchOverflow(ArrayList paramKeys) { int size = paramKeys.size(); synchronized (lock) { for (int i = 0; i < size; i++) { @@ -2624,7 +2624,7 @@ public void run() { // We need to set the context class loader for this (deamon) thread!! currentThread.setContextClassLoader(myClassLoader); - ArrayList localKeys = null; + ArrayList localKeys = null; do { synchronized (lock) { int size = keys.size(); @@ -2633,7 +2633,7 @@ public void run() { } localKeys = keys; - keys = new ArrayList(16); + keys = new ArrayList<>(16); } int maxIndex = localKeys.size(); diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCache.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCache.java index 66004430f28..4d22c5e76dd 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCache.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCache.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 @@ -18,23 +19,22 @@ import com.sun.appserv.util.cache.Cache; +import java.util.Properties; + /** * An interface for accessing EJB(Local)Object caches * * @author Mahesh Kannan */ +public interface EJBObjectCache extends Cache { -public interface EJBObjectCache - extends Cache -{ - public Object get(Object key, boolean incrementRefCount); + public Object get(K key, boolean incrementRefCount); - public Object put(Object key, Object value, boolean incrementRefCount); + public Object put(K key, V value, boolean incrementRefCount); - public Object remove(Object key, boolean decrementRefCount); + public Object remove(K key, boolean decrementRefCount); - public void init(int maxEntries, int numberOfVictimsToSelect, - long timeout, float loadFactor, java.util.Properties props); + public void init(int maxEntries, int numberOfVictimsToSelect, long timeout, float loadFactor, Properties props); public void setEJBObjectCacheListener(EJBObjectCacheListener listener); } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCacheListener.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCacheListener.java index 52f9da8e3ea..678b1169683 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCacheListener.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/EJBObjectCacheListener.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,6 +29,6 @@ public interface EJBObjectCacheListener { public void handleOverflow(Object key); - public void handleBatchOverflow(ArrayList keys); + public void handleBatchOverflow(ArrayList keys); } diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/FIFOEJBObjectCache.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/FIFOEJBObjectCache.java index 9543fc3c2d4..06f33411e7b 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/FIFOEJBObjectCache.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/FIFOEJBObjectCache.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025 Contributors to the Eclipse Foundation. All rights reserved. + * Copyright (c) 2022, 2026 Contributors to the Eclipse Foundation. All rights reserved. * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -32,22 +32,17 @@ * * @author Mahesh Kannan */ -public class FIFOEJBObjectCache - extends LruEJBCache - implements EJBObjectCache -{ +public class FIFOEJBObjectCache extends LruEJBCache implements EJBObjectCache { + protected int maxCacheSize; protected String name; protected EJBObjectCacheListener listener; protected Object refCountLock = new Object(); protected int totalRefCount = 0; - protected static final boolean _printRefCount = - Boolean.getBoolean("cache.printrefcount"); - + protected static final boolean _printRefCount = Boolean.getBoolean("cache.printrefcount"); - private static final Logger _logger = - LogDomains.getLogger(FIFOEJBObjectCache.class, LogDomains.EJB_LOGGER); + private static final Logger _logger = LogDomains.getLogger(FIFOEJBObjectCache.class, LogDomains.EJB_LOGGER); /** * default constructor @@ -65,6 +60,7 @@ public FIFOEJBObjectCache(String name, long timeout) { this.name = name; } + @Override public void init(int maxEntries, int numberOfVictimsToSelect, long timeout, float loadFactor, Properties props) { @@ -74,54 +70,67 @@ public void init(int maxEntries, int numberOfVictimsToSelect, long timeout, _logger.log(Level.FINE, name + ": FIFOEJBObject cache created...."); } + @Override public void setEJBObjectCacheListener(EJBObjectCacheListener listener) { this.listener = listener; } - public Object get(Object key) { + @Override + public V get(K key) { int hashCode = hash(key); return internalGet(hashCode, key, false); } - public Object get(Object key, boolean incrementRefCount) { + @Override + public V get(K key, boolean incrementRefCount) { int hashCode = hash(key); return internalGet(hashCode, key, incrementRefCount); } - public Object put(Object key, Object value) { + @Override + public V put(K key, V value) { int hashCode = hash(key); return internalPut(hashCode, key, value, -1, false); } - public Object put(Object key, Object value, boolean incrementRefCount) { + @Override + public V put(K key, V value, boolean incrementRefCount) { int hashCode = hash(key); return internalPut(hashCode, key, value, -1, incrementRefCount); } - public Object remove(Object key) { + @Override + public V remove(K key) { return internalRemove(key, true); } - public Object remove(Object key, boolean decrementRefCount) { + @Override + public V remove(K key, boolean decrementRefCount) { return internalRemove(key, decrementRefCount); } + @Override protected boolean isThresholdReached() { return listSize > maxCacheSize; } - protected void itemAccessed(CacheItem item) { } - protected void itemRemoved(CacheItem item) { + @Override + protected void itemAccessed(CacheItem item) { + } + + + @Override + protected void itemRemoved(CacheItem item) { // LruCacheItem(more specifically EJBObjectCacheItem) should always be used in conjunction with FIFOEJBObjectCache assert item instanceof LruCacheItem; - LruCacheItem l = (LruCacheItem) item; + LruCacheItem l = (LruCacheItem) item; // remove the item from the LRU list synchronized (this) { @@ -130,21 +139,23 @@ protected void itemRemoved(CacheItem item) { return; } - LruCacheItem prev = l.getLPrev(); - LruCacheItem next = l.getLNext(); + LruCacheItem prev = l.getLPrev(); + LruCacheItem next = l.getLNext(); l.setTrimmed(true); // patch up the neighbors and make sure head/tail are correct - if (prev != null) + if (prev != null) { prev.setLNext(next); - else + } else { head = next; + } - if (next != null) + if (next != null) { next.setLPrev(prev); - else + } else { tail = prev; + } l.setLNext(null); l.setLPrev(null); @@ -153,12 +164,11 @@ protected void itemRemoved(CacheItem item) { } } - protected Object internalGet(int hashCode, Object key, - boolean incrementRefCount) { + protected V internalGet(int hashCode, K key, boolean incrementRefCount) { int index = getIndex(hashCode); - Object value = null; - CacheItem item = null; + V value = null; + CacheItem item = null; synchronized (bucketLocks[index]) { item = buckets[index]; @@ -175,7 +185,7 @@ protected Object internalGet(int hashCode, Object key, if (incrementRefCount) { // EJBObjectCacheItem should always be used in conjunction with FIFOEJBObjectCache assert item instanceof EJBObjectCacheItem; - EJBObjectCacheItem eoItem = (EJBObjectCacheItem) item; + EJBObjectCacheItem eoItem = (EJBObjectCacheItem) item; eoItem.refCount++; if (_printRefCount) { incrementReferenceCount(); @@ -187,23 +197,22 @@ protected Object internalGet(int hashCode, Object key, } } - if (item != null) + if (item != null) { incrementHitCount(); - else + } else { incrementMissCount(); + } return value; } - protected Object internalPut(int hashCode, Object key, Object value, - int size, boolean incrementRefCount) - { + protected V internalPut(int hashCode, K key, V value, int size, boolean incrementRefCount) { int index = getIndex(hashCode); - CacheItem item, oldItem = null, overflow = null; - EJBObjectCacheItem newItem = null; - Object oldValue = null; + CacheItem item, oldItem = null, overflow = null; + EJBObjectCacheItem newItem = null; + V oldValue = null; // lookup the item synchronized (bucketLocks[index]) { @@ -216,12 +225,11 @@ protected Object internalPut(int hashCode, Object key, Object value, // if there was no item in the cache, insert the given item if (oldItem == null) { - newItem = (EJBObjectCacheItem) - createItem(hashCode, key, value, size); + newItem = (EJBObjectCacheItem) createItem(hashCode, key, value, size); newItem.setTrimmed(incrementRefCount); // add the item at the head of the bucket list - newItem.setNext( buckets[index] ); + newItem.setNext(buckets[index]); buckets[index] = newItem; if (incrementRefCount) { @@ -235,9 +243,10 @@ protected Object internalPut(int hashCode, Object key, Object value, } else { oldValue = oldItem.getValue(); if (incrementRefCount) { - // EJBObjectCacheItem should always be used in conjunction with FIFOEJBObjectCache + // EJBObjectCacheItem should always be used in conjunction with + // FIFOEJBObjectCache assert oldItem instanceof EJBObjectCacheItem; - EJBObjectCacheItem oldEJBO = (EJBObjectCacheItem) oldItem; + EJBObjectCacheItem oldEJBO = (EJBObjectCacheItem) oldItem; oldEJBO.refCount++; if (_printRefCount) { incrementReferenceCount(); @@ -261,25 +270,25 @@ protected Object internalPut(int hashCode, Object key, Object value, public void print() { System.out.println("EJBObjectCache:: size: " + getEntryCount() + "; listSize: " + listSize); - for (LruCacheItem run = head; run!=null; run=run.getLNext()) { + for (LruCacheItem run = head; run!=null; run=run.getLNext()) { System.out.print("("+run.getKey()+", "+run.getValue()+") "); } System.out.println(); } - protected Object internalRemove(Object key, boolean decrementRefCount) { + protected V internalRemove(K key, boolean decrementRefCount) { int hashCode = hash(key); int index = getIndex(hashCode); - CacheItem prev = null, item = null; + CacheItem prev = null, item = null; synchronized (bucketLocks[index]) { for (item = buckets[index]; item != null; item = item.getNext()) { if (hashCode == item.getHashCode() && key.equals(item.getKey())) { // EJBObjectCacheItem should always be used in conjunction with FIFOEJBObjectCache assert item instanceof EJBObjectCacheItem; - EJBObjectCacheItem eoItem = (EJBObjectCacheItem) item; + EJBObjectCacheItem eoItem = (EJBObjectCacheItem) item; if (decrementRefCount) { if (eoItem.refCount > 0) { eoItem.refCount--; @@ -326,23 +335,22 @@ protected void trimItem(CacheItem item) { } */ - protected CacheItem createItem(int hashCode, Object key, Object value, - int size) { - return new EJBObjectCacheItem(hashCode, key, value, size); + @Override + protected CacheItem createItem(int hashCode, K key, V value, int size) { + return new EJBObjectCacheItem<>(hashCode, key, value, size); } - protected static class EJBObjectCacheItem - extends LruCacheItem { + protected static class EJBObjectCacheItem extends LruCacheItem { protected int refCount; - protected EJBObjectCacheItem(int hashCode, Object key, Object value, - int size) { + protected EJBObjectCacheItem(int hashCode, K key, V value, int size) { super(hashCode, key, value, size); } } - public Map getStats() { - Map map = new HashMap(); + @Override + public Map getStats() { + Map map = new HashMap<>(); StringBuffer sbuf = new StringBuffer(); sbuf.append("(totalRef=").append(totalRefCount).append("; "); @@ -358,6 +366,7 @@ public Map getStats() { return map; } + @Override public void trimExpiredEntries(int maxCount) { int count = 0; @@ -384,10 +393,11 @@ public void trimExpiredEntries(int maxCount) { if (item != tail) { lastItem.setLPrev(null); - if (item != null) + if (item != null) { item.setLNext(null); - else + } else { head = null; + } lastItem = tail; // record the old tail tail = item; @@ -398,7 +408,7 @@ public void trimExpiredEntries(int maxCount) { if (count > 0) { - ArrayList localVictims = new ArrayList(count); + ArrayList localVictims = new ArrayList<>(count); // trim the items from the BaseCache from the old tail backwards for (item = lastItem; item != null; item = item.getLPrev()) { localVictims.add(item.getKey()); diff --git a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/UnboundedEJBObjectCache.java b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/UnboundedEJBObjectCache.java index 9c4d255112c..7c50a792bda 100644 --- a/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/UnboundedEJBObjectCache.java +++ b/appserver/persistence/entitybean-container/src/main/java/org/glassfish/persistence/ejb/entitybean/container/cache/UnboundedEJBObjectCache.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,14 +29,15 @@ * * @author Mahesh Kannan */ -public class UnboundedEJBObjectCache - extends BaseCache - implements EJBObjectCache -{ +public class UnboundedEJBObjectCache extends BaseCache implements EJBObjectCache { + /** * default constructor */ - public UnboundedEJBObjectCache(String name) { super(); } + public UnboundedEJBObjectCache(String name) { + super(); + } + /** * constructor with specified timeout @@ -44,34 +46,42 @@ public UnboundedEJBObjectCache(String name, long timeout) { super(); } + + @Override public void init(int maxEntries, int numberOfVictimsToSelect, long timeout, float loadFactor, Properties props) { super.init(maxEntries, loadFactor, props); } - public Object get(Object key, boolean incrementRefCount) { + @Override + public V get(K key, boolean incrementRefCount) { return super.get(key); } - public Object put(Object key, Object value, boolean linkWithLru) { + @Override + public V put(K key, V value, boolean linkWithLru) { return super.put(key, value); } - public Object remove(Object key, boolean decrementRefCount) { + @Override + public V remove(K key, boolean decrementRefCount) { return super.remove(key); } + @Override public void setEJBObjectCacheListener(EJBObjectCacheListener listener) { //do nothing } - protected void trimItem(CacheItem item) { + @Override + protected void trimItem(CacheItem item) { } - public Map getStats() { - Map map = new HashMap(); + @Override + public Map getStats() { + Map map = new HashMap<>(); StringBuffer sbuf = new StringBuffer(); sbuf.append("(listSize = 0") .append("; cacheSize = ").append(getEntryCount()) diff --git a/appserver/persistence/jnosql-jakarta-persistence-osgi-bundle/pom.xml b/appserver/persistence/jnosql-jakarta-persistence-osgi-bundle/pom.xml index ea302162e6e..f4cf32f7539 100644 --- a/appserver/persistence/jnosql-jakarta-persistence-osgi-bundle/pom.xml +++ b/appserver/persistence/jnosql-jakarta-persistence-osgi-bundle/pom.xml @@ -164,26 +164,7 @@ maven-antrun-plugin - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b2 - - - ant - ant - - - - - diff --git a/appserver/pom.xml b/appserver/pom.xml index 8b75ecb3663..251d6dbf8da 100644 --- a/appserver/pom.xml +++ b/appserver/pom.xml @@ -97,8 +97,8 @@ 2.0 - 6.7 - 6.7 + 2.9.0 + 2.9.0 10.17.1.0 ${derby.version} 1.6.3 @@ -600,12 +600,12 @@ org.glassfish.external - dbschema + dbschema-osgi ${dbschema.version} org.glassfish.external - schema2beans + schema2beans-osgi ${schema2beans.version} diff --git a/appserver/resources/resources-runtime/src/main/java/org/glassfish/resources/module/ResourcesDeployer.java b/appserver/resources/resources-runtime/src/main/java/org/glassfish/resources/module/ResourcesDeployer.java index 08ecb1e4d3b..5dd9d6b94e6 100644 --- a/appserver/resources/resources-runtime/src/main/java/org/glassfish/resources/module/ResourcesDeployer.java +++ b/appserver/resources/resources-runtime/src/main/java/org/glassfish/resources/module/ResourcesDeployer.java @@ -750,7 +750,7 @@ private ResourceDeployer getResourceDeployer(Object resource){ } /** - * Event listener to listen to application undeploy validation and + * Event listener to listen to application undeploy validation and * if preserveResources flag is set, cache the <resources> * config for persisting it in domain.xml */ diff --git a/appserver/security/core-ee/pom.xml b/appserver/security/core-ee/pom.xml index 62228ba86a8..f7e2533576f 100644 --- a/appserver/security/core-ee/pom.xml +++ b/appserver/security/core-ee/pom.xml @@ -1,6 +1,7 @@ - + diff --git a/appserver/tests/appserv-tests/devtests/security/ldap/opends/login.conf b/appserver/tests/appserv-tests/devtests/security/ldap/opends/login.conf index 59939f00941..e7a7fc6fed2 100644 --- a/appserver/tests/appserv-tests/devtests/security/ldap/opends/login.conf +++ b/appserver/tests/appserv-tests/devtests/security/ldap/opends/login.conf @@ -23,10 +23,6 @@ ldapRealm { org.glassfish.security.services.impl.LDAPLoginModule required; }; -solarisRealm { - com.sun.enterprise.security.auth.login.SolarisLoginModule required; -}; - jdbcRealm { com.sun.enterprise.security.ee.authentication.glassfish.jdbc.JDBCLoginModule required; }; diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/README b/appserver/tests/appserv-tests/devtests/security/solarisRealm/README deleted file mode 100644 index b70b912f7e0..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/README +++ /dev/null @@ -1,9 +0,0 @@ -It is important to note that S1AS must be run as root if Solaris realm is used. - -The default setting assumes that there is a Solaris login guest -with password guest123. - -If a different Solaris password is used for testing, please modify build.xml. - -If a different Solaris user/password is used for testing, then please modify -descriptor/sun-application.xml and build.xml. diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.properties b/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.properties deleted file mode 100644 index f6e27a83498..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.properties +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.xml deleted file mode 100644 index 5001c8b3b66..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/build.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - - - -]> - - - - - &commonSetup; - &commonBuild; - &commonRun; - &testProperties; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/MANIFEST.MF b/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/MANIFEST.MF deleted file mode 100644 index d6c7e78d35f..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/MANIFEST.MF +++ /dev/null @@ -1,4 +0,0 @@ -Manifest-Version: 1.0 -Created-By: Apache Ant 1.5 -Main-Class: shopping.RpaClient - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/RpaClient.java b/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/RpaClient.java deleted file mode 100644 index b7f3c8e24a4..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/client/RpaClient.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2002, 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 shopping; - -import java.io.*; -import java.util.*; -import jakarta.ejb.EJBHome; -import javax.naming.*; -import javax.rmi.PortableRemoteObject; -import org.omg.CORBA.ORB; -import com.sun.enterprise.security.LoginContext; -//import com.sun.enterprise.security.LoginException; -import java.rmi.RemoteException; -import java.security.*; - -import com.sun.ejte.ccl.reporter.SimpleReporterAdapter; - -public class RpaClient { - private static SimpleReporterAdapter stat = - new SimpleReporterAdapter("appserv-tests"); - - public static void main (String[] args) { - - RpaClient client = new RpaClient(args); - client.doTest(); - } - - public RpaClient(String[] args) { - //super(args); - } - - public String doTest() { - - RpaRemote hr=null; - String res=null; - Context ic = null; - LoginContext lc=null; - RpaHome home=null; - String testId = "Sec::Solaris Realm"; - try{ - stat.addDescription("Security::Solaris Realm"); - ic = new InitialContext(); - // create EJB using factory from container - java.lang.Object objref = ic.lookup("rpaLoginBean"); - - System.err.println("Looked up home!!"); - - home = (RpaHome)PortableRemoteObject.narrow( - objref, RpaHome.class); - System.err.println("Narrowed home!!"); - - hr = home.create("LizHurley"); - System.out.println("Got the EJB!!"); - - // invoke 3 overloaded methods on the EJB - System.out.println ("Calling authorized method - addItem"); - hr.addItem("lipstick", 30); - hr.addItem("mascara", 40); - hr.addItem("lipstick2", 50); - hr.addItem("sandals", 200); - System.out.println(hr.getTotalCost()); - hr.deleteItem("lipstick2"); - java.lang.String[] shoppingList = hr.getItems(); - System.out.println("Shopping list for LizHurley"); - for (int i=0; i - - - - - rpaLoginBean-client - Stateful Login Bean checking j2eelogin.name and j2eelogin.password properties - - ejb/rpaLoginBean - Session - shopping.RpaHome - shopping.RpaRemote - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/application.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/application.xml deleted file mode 100644 index a736f9795ee..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/application.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - rpaLoginBean - - rpaLoginBean-ejb.jar - - - rpaLoginBean-client.jar - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/ejb-jar.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/ejb-jar.xml deleted file mode 100644 index 1461e61711c..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/ejb-jar.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - Ejb1 - - - rpaLoginBean - rpaLoginBean - shopping.RpaHome - shopping.RpaRemote - shopping.RpaBean - Stateful - Container - - EMP - Employee - - - STAFF - Employee - - - - - - - - - Employee - - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application-client.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application-client.xml deleted file mode 100644 index d22ee2bbabc..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application-client.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - -ejb/rpaLoginBean -rpaLoginBean - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application.xml deleted file mode 100644 index f836d91d62c..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-application.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - 0 - - Administrator - shingwai - - - Employee - guest - - - Manager - guest - - solaris - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-ejb-jar.xml b/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-ejb-jar.xml deleted file mode 100644 index dd0a6e830f8..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/descriptor/sun-ejb-jar.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - -0 - -rpaLoginBean -rpaLoginBean - - -supported -supported -supported -supported - - -username_password -solaris -true - - -supported - - - - - - - diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaBean.java b/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaBean.java deleted file mode 100644 index 68c1872bfc1..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaBean.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2017, 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 - */ - -/* - * ShoppingEJB.java - * - * Created on May 15, 2003, 5:16 PM - */ - -package shopping; - -import jakarta.ejb.SessionContext; -import jakarta.ejb.SessionBean; -import java.util.Vector; -import java.lang.String; -import java.util.Iterator; -import jakarta.ejb.EJBException; -import java.rmi.RemoteException; -/** - * - * @author Harpreet - * @version - */ - -public class RpaBean implements SessionBean { - - private String shopper = "anonymous"; - private int totalPrice = 0; - - private int totalItems = 0; - - private Vector items; - - private Vector itemPrice; - - private SessionContext sc = null; - - /** Creates a new instance of ShoppingEJB */ - public void ejbCreate(String shopperName) { - shopper = shopperName; - items = new Vector(); - itemPrice = new Vector(); - } - - public void addItem(java.lang.String item, int price) throws EJBException, - RemoteException{ - items.add(item); - itemPrice.add(new Integer(price)); - totalItems++; - totalPrice += price; - System.out.println(" Shopping Cart: Shopper "+ shopper +" has bought " - + item +" for price ="+ price +" .Total Items = "+totalItems + - " .TotalPrice = " + totalPrice); - - System.out.println("Caller Princial = "+sc.getCallerPrincipal()); - } - - public void deleteItem(java.lang.String item) throws EJBException, - RemoteException{ - int index = items.indexOf(item); - items.remove(item); - Integer price = (Integer) itemPrice.get(index); - System.out.println("Shopping Cart: Removing item "+ item +" @price "+ - price.intValue()); - totalPrice -= price.shortValue(); - itemPrice.remove(index); - System.out.println(" Shopping Cart: Shopper "+ shopper +" .Total Items = "+totalItems + - " .TotalPrice = " + totalPrice); - System.out.println("Caller Princial = "+sc.getCallerPrincipal()); - } - - public double getTotalCost() throws EJBException{ - System.out.println("Caller Princial = "+sc.getCallerPrincipal()); - - return totalPrice; - } - - public String[] getItems() throws EJBException{ - System.out.println("Caller Princial = "+sc.getCallerPrincipal()); - - Iterator it = items.iterator(); - int sz = items.size(); - String[] itemNames = new String[sz]; - for(int i=0; it.hasNext();){ - itemNames[i++] = new String( (String)it.next()); - } - return itemNames; - } - - public void ejbActivate() { - System.out.println("In Rpa ejbActivate"); - } - - - public void ejbPassivate() { - System.out.println("In Rpa ejbPassivate"); - } - - - public void ejbRemove() { - System.out.println("In Rpa ejbRemove"); - } - - - public void setSessionContext(jakarta.ejb.SessionContext sessionContext) { - sc = sessionContext; - } - -} diff --git a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaRemote.java b/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaRemote.java deleted file mode 100644 index 43a39911fcf..00000000000 --- a/appserver/tests/appserv-tests/devtests/security/solarisRealm/shopping/RpaRemote.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2017, 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 - */ - -/* - * Rpa.java - * - * Created on May 15, 2003, 5:09 PM - */ - -package shopping; -import jakarta.ejb.EJBObject; -/** - * Shopping Cart Stateful Session Bean. Just tests -Dj2eelogin.name - * -Dj2eelogin.password system properties. - * @author hsingh - */ -public interface RpaRemote extends EJBObject { - - public void addItem(java.lang.String item, int price) throws java.rmi.RemoteException; - - public void deleteItem(java.lang.String item) throws java.rmi.RemoteException; - - public double getTotalCost() throws java.rmi.RemoteException; - - public java.lang.String[] getItems() throws java.rmi.RemoteException; -} diff --git a/appserver/tests/embedded/maven-plugin/pom.xml b/appserver/tests/embedded/maven-plugin/pom.xml index 44c23cb1ca7..39d54df2db6 100644 --- a/appserver/tests/embedded/maven-plugin/pom.xml +++ b/appserver/tests/embedded/maven-plugin/pom.xml @@ -190,7 +190,7 @@ org.apache.maven maven-plugin-api - 3.9.14 + 3.9.15 diff --git a/appserver/tests/gftest.sh b/appserver/tests/gftest.sh index d5dda10bf46..289d4264b63 100755 --- a/appserver/tests/gftest.sh +++ b/appserver/tests/gftest.sh @@ -53,7 +53,7 @@ if [ ! -z "${JENKINS_HOME}" ] ; then export M2_REPO="${M2_REPO:=$MVN_REPOSITORY}" echo "Preparing dependencies ..." - mvn clean package -f ${APS_HOME}/lib/pom.xml + mvn clean package -f ${APS_HOME}/lib/pom.xml -Psnapshots fi "$@" diff --git a/appserver/tests/quicklook/pom.xml b/appserver/tests/quicklook/pom.xml index f6005b9cd22..5473ef6a4e5 100644 --- a/appserver/tests/quicklook/pom.xml +++ b/appserver/tests/quicklook/pom.xml @@ -152,19 +152,19 @@ - org.apache.ant - ant - 1.10.9 + org.glassfish.external + ant-osgi + 1.10.17 org.apache.ant ant-junit - 1.10.9 + 1.10.17 org.apache.ant ant-apache-regexp - 1.10.9 + 1.10.17 runtime diff --git a/appserver/tests/tck/activation/pom.xml b/appserver/tests/tck/activation/pom.xml index 8bf70b8394c..751399af2ca 100644 --- a/appserver/tests/tck/activation/pom.xml +++ b/appserver/tests/tck/activation/pom.xml @@ -99,24 +99,6 @@ maven-antrun-plugin - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/tests/tck/authentication/pom.xml b/appserver/tests/tck/authentication/pom.xml index 7154272c9a9..afb659259ab 100644 --- a/appserver/tests/tck/authentication/pom.xml +++ b/appserver/tests/tck/authentication/pom.xml @@ -202,24 +202,6 @@ maven-antrun-plugin false - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/tests/tck/authorization/pom.xml b/appserver/tests/tck/authorization/pom.xml index c20d70be3b6..97b3fdf6580 100644 --- a/appserver/tests/tck/authorization/pom.xml +++ b/appserver/tests/tck/authorization/pom.xml @@ -203,24 +203,6 @@ maven-antrun-plugin false - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/tests/tck/faces/pom.xml b/appserver/tests/tck/faces/pom.xml index a016c944e24..fbf4aeb83c0 100644 --- a/appserver/tests/tck/faces/pom.xml +++ b/appserver/tests/tck/faces/pom.xml @@ -113,24 +113,6 @@ maven-antrun-plugin false - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/tests/tck/pages_debugging/pom.xml b/appserver/tests/tck/pages_debugging/pom.xml index cadb8f31568..5b93fbae9fc 100644 --- a/appserver/tests/tck/pages_debugging/pom.xml +++ b/appserver/tests/tck/pages_debugging/pom.xml @@ -112,24 +112,6 @@ maven-antrun-plugin - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/tests/tck/pages_tags/pom.xml b/appserver/tests/tck/pages_tags/pom.xml index 1e8575d0d1a..c6a5b84a522 100644 --- a/appserver/tests/tck/pages_tags/pom.xml +++ b/appserver/tests/tck/pages_tags/pom.xml @@ -124,24 +124,6 @@ maven-antrun-plugin - - - org.apache.ant - ant - ${ant.version} - - - ant-contrib - ant-contrib - 1.0b3 - - - ant - ant - - - - ${skipITs} diff --git a/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/api/JavaEETransactionManager.java b/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/api/JavaEETransactionManager.java index 3690b1fb34f..b8307ec744f 100644 --- a/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/api/JavaEETransactionManager.java +++ b/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/api/JavaEETransactionManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2022, 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 @@ -30,6 +30,7 @@ import jakarta.transaction.TransactionManager; import java.rmi.RemoteException; +import java.util.ArrayList; import java.util.List; import javax.transaction.xa.XAResource; @@ -178,7 +179,7 @@ void postInvoke(ComponentInvocation curr, ComponentInvocation prev) * Returns a list of resource handles held by the component */ - List getExistingResourceList(Object instance, ComponentInvocation inv); + List getExistingResourceList(Object instance, ComponentInvocation inv); void registerComponentResource(TransactionalResource h); @@ -236,7 +237,7 @@ void begin(int timeout) * Returns the list of ActiveTransactions. Called by Admin framework * The ArrayList contains TransactionAdminBean */ - java.util.ArrayList getActiveTransactions(); + ArrayList getActiveTransactions(); /* * Called by Admin Framework. Forces the given transaction to be rolled back diff --git a/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/spi/JavaEETransactionManagerDelegate.java b/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/spi/JavaEETransactionManagerDelegate.java index af8843f12b7..c0b8cdaf4b0 100644 --- a/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/spi/JavaEETransactionManagerDelegate.java +++ b/appserver/transaction/internal-api/src/main/java/com/sun/enterprise/transaction/spi/JavaEETransactionManagerDelegate.java @@ -158,7 +158,7 @@ public void resume(Transaction tx) public void setTransactionManager(JavaEETransactionManager tm); /** - * Returns true if this delegate supports XA resources. + * Returns true if this delegate supports XA resources. */ public boolean supportsXAResource(); diff --git a/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionImpl.java b/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionImpl.java index 4ab10e5f266..7cfced1456f 100644 --- a/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionImpl.java +++ b/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionImpl.java @@ -142,7 +142,7 @@ static synchronized private void initializeTimer() { this.javaEETM = javaEETM; this.txId = txIdCounter.incrementAndGet(); this.xid = new JavaEEXid(txId); - this.resourceTable = new HashMap(); + this.resourceTable = new HashMap<>(); localTxStatus = Status.STATUS_ACTIVE; startTime = System.currentTimeMillis(); if (LOG.isLoggable(Level.FINE)) { diff --git a/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionManagerSimplified.java b/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionManagerSimplified.java index 11acba9206b..d369c1132c4 100644 --- a/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionManagerSimplified.java +++ b/appserver/transaction/jta/src/main/java/com/sun/enterprise/transaction/JavaEETransactionManagerSimplified.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Contributors to the Eclipse Foundation + * Copyright (c) 2021, 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 @@ -18,7 +18,6 @@ package com.sun.enterprise.transaction; import com.sun.appserv.util.cache.BaseCache; -import com.sun.appserv.util.cache.Cache; import com.sun.enterprise.config.serverbeans.ModuleMonitoringLevels; import com.sun.enterprise.transaction.api.JavaEETransaction; import com.sun.enterprise.transaction.api.JavaEETransactionManager; @@ -49,11 +48,12 @@ import java.rmi.RemoteException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Hashtable; import java.util.Iterator; import java.util.List; -import java.util.Map; +import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; @@ -107,7 +107,7 @@ public class JavaEETransactionManagerSimplified implements JavaEETransactionMana // to be inherited by child threads. private final ThreadLocal transactions; - private final ThreadLocal localCallCounter; + private final ThreadLocal localCallCounter; private final ThreadLocal delegates; // If multipleEnlistDelists is set to true, with in the transaction, for the same @@ -122,14 +122,14 @@ public class JavaEETransactionManagerSimplified implements JavaEETransactionMana private int purgeCancelledTtransactions = 0; // admin and monitoring related parameters - private static final Hashtable statusMap = new Hashtable(); - private final List activeTransactions = Collections.synchronizedList(new ArrayList()); + private static final Hashtable statusMap = new Hashtable<>(); + private final List activeTransactions = Collections.synchronizedList(new ArrayList<>()); private boolean monitoringEnabled = false; private TransactionServiceProbeProvider monitor; - private Hashtable txnTable = null; + private Hashtable txnTable; - private Cache resourceTable; + private BaseCache> resourceTable; private final Timer _timer = new Timer("transaction-manager", true); @@ -149,7 +149,7 @@ public class JavaEETransactionManagerSimplified implements JavaEETransactionMana public JavaEETransactionManagerSimplified() { transactions = new ThreadLocal<>(); - localCallCounter = new ThreadLocal(); + localCallCounter = new ThreadLocal<>(); delegates = new ThreadLocal<>(); } @@ -189,9 +189,8 @@ private void initProperties() { // ignore } - resourceTable = new BaseCache(); - ((BaseCache) resourceTable).init(maxEntries, loadFactor, null); - // END IASRI 4705808 TTT001 + resourceTable = new BaseCache<>(); + resourceTable.init(maxEntries, loadFactor, null); if (habitat != null) { TransactionService txnService = habitat.getService(TransactionService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME); @@ -218,14 +217,9 @@ private void initProperties() { } } - // ENF OF BUG 4665539 - if (LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "TM: Tx Timeout = " + transactionTimeout); - } + LOG.log(Level.FINE, () -> "TM: Tx Timeout = " + transactionTimeout); - // START IASRI 4705808 TTT004 -- monitor resource table stats try { - // XXX TODO: if (Boolean.getBoolean("MONITOR_JTA_RESOURCE_TABLE_STATISTICS")) { registerStatisticMonitorTask(); } @@ -407,7 +401,7 @@ public void unregisterComponentResource(TransactionalResource h) { } h.setComponentInstance(null); ComponentInvocation inv = invMgr.getCurrentInvocation(); - List l = getExistingResourceList(instance, inv); + List l = getExistingResourceList(instance, inv); if (l != null) { l.remove(h); @@ -438,17 +432,10 @@ public void startJTSTx(JavaEETransaction t) throws RollbackException, IllegalSta * @return List of resources */ @Override - public List getResourceList(Object instance, ComponentInvocation inv) { + public List getResourceList(Object instance, ComponentInvocation inv) { if (inv == null) { - return new ArrayList(0); + return new ArrayList<>(0); } - List l = null; - - /** - * XXX EJB CONTAINER ONLY XXX -- NEED TO CHECK THE NEW CODE BELOW ** if (inv.getInvocationType() == - * ComponentInvocation.ComponentInvocationType.EJB_INVOCATION) { ComponentContext ctx = inv.context; if (ctx != null) l - * = ctx.getResourceList(); else { l = new ArrayList(0); } } XXX EJB CONTAINER ONLY XXX - **/ ResourceHandler rh = inv.getResourceHandler(); if (LOG.isLoggable(Level.FINE)) { @@ -456,19 +443,20 @@ public List getResourceList(Object instance, ComponentInvocation inv) { + ((rh == null) ? "" : (" ResourceHandler type: " + rh.getClass().getName())) + " ResourceHandler: " + rh); } + List l; if (rh != null) { l = rh.getResourceList(); if (l == null) { - l = new ArrayList(0); + l = new ArrayList<>(0); } } else { Object key = getResourceTableKey(instance, inv); if (key == null) { - return new ArrayList(0); + return new ArrayList<>(0); } - l = (List) resourceTable.get(key); + l = resourceTable.get(key); if (l == null) { - l = new ArrayList(); // FIXME: use an optimum size? + l = new ArrayList<>(); resourceTable.put(key, l); } } @@ -582,11 +570,11 @@ private JavaEETransactionImpl initJavaEETransaction(int timeout) { } @Override - public List getExistingResourceList(Object instance, ComponentInvocation inv) { + public List getExistingResourceList(Object instance, ComponentInvocation inv) { if (inv == null) { return null; } - List l = null; + List l = null; /** * XXX EJB CONTAINER ONLY XXX -- NEED TO CHECK THE NEW CODE BELOW ** if (inv.getInvocationType() == @@ -605,7 +593,7 @@ public List getExistingResourceList(Object instance, ComponentInvocation inv) { } else { Object key = getResourceTableKey(instance, inv); if (key != null) { - l = (List) resourceTable.get(key); + l = resourceTable.get(key); } } return l; @@ -649,7 +637,7 @@ public void componentDestroyed(Object instance, ComponentInvocation inv) { } // Access resourceTable directly to avoid adding an empty list then removing it - List l = (List) resourceTable.remove(getResourceTableKey(instance, inv)); + List l = resourceTable.remove(getResourceTableKey(instance, inv)); processResourceList(l); if (LOG.isLoggable(Level.FINE)) { @@ -685,7 +673,7 @@ public boolean isTimedOut() { @Override public void checkTransactionImport() { // First check if this is a local call - int[] count = (int[]) localCallCounter.get(); + int[] count = localCallCounter.get(); if (count != null && count[0] > 0) { count[0]--; return; @@ -708,7 +696,7 @@ public void checkTransactionExport(boolean isLocal) { if (isLocal) { // Put a counter in TLS indicating this is a local call. // Use int[1] as a mutable java.lang.Integer! - int[] count = (int[]) localCallCounter.get(); + int[] count = localCallCounter.get(); if (count == null) { count = new int[1]; localCallCounter.set(count); @@ -1123,9 +1111,9 @@ public void setDefaultTransactionTimeout(int seconds) { * @see TransactionAdminBean */ @Override - public ArrayList getActiveTransactions() { - ArrayList tranBeans = new ArrayList(); - txnTable = new Hashtable(); + public ArrayList getActiveTransactions() { + ArrayList tranBeans = new ArrayList<>(); + txnTable = new Hashtable<>(); Object[] activeCopy = activeTransactions.toArray(); // get the clone of the active transactions for (Object element : activeCopy) { try { @@ -1182,13 +1170,11 @@ public void forceRollback(String txnId) throws IllegalStateException, SystemExce if (txnTable == null || txnTable.get(txnId) == null) { String result = sm.getString("transaction.monitor.rollback_invalid_id"); throw new IllegalStateException(result); - } else { - if (LOG.isLoggable(Level.FINE)) { - LOG.log(Level.FINE, "TM: Marking txnId " + txnId + " for rollback"); - } - - ((Transaction) txnTable.get(txnId)).setRollbackOnly(); } + if (LOG.isLoggable(Level.FINE)) { + LOG.log(Level.FINE, "TM: Marking txnId " + txnId + " for rollback"); + } + txnTable.get(txnId).setRollbackOnly(); } @@ -1241,23 +1227,29 @@ private void registerStatisticMonitorTask() { class StatisticMonitorTask extends TimerTask { @Override public void run() { - if (resourceTable != null) { - Map stats = resourceTable.getStats(); - Iterator it = stats.entrySet().iterator(); - LOG.log(Level.INFO, "********** JavaEETransactionManager resourceTable stats *****"); - while (it.hasNext()) { - Map.Entry entry = (Map.Entry) it.next(); - LOG.log(Level.INFO, (String) entry.getKey() + ": " + entry.getValue()); + if (resourceTable != null && LOG.isLoggable(Level.INFO)) { + StringBuilder message = new StringBuilder(1024); + message.append("JavaEETransactionManager resourceTable stats:"); + for (Entry entry : resourceTable.getStats().entrySet()) { + message.append('\n').append(entry.getKey()).append(": ").append(toString(entry.getValue())); } + LOG.log(Level.INFO, message.toString()); } } + + private static String toString(Object object) { + if (object == null) { + return null; + } + if (object.getClass().isArray()) { + return Arrays.toString((Object[]) object); + } + return String.valueOf(object); + } } - /****************************************************************************/ - /************************* Helper Methods ***********************************/ - /****************************************************************************/ public static String getStatusAsString(int status) { - return (String) statusMap.get(status); + return statusMap.get(status); } private void delistComponentResources(ComponentInvocation inv, boolean suspend) throws InvocationException { @@ -1265,24 +1257,23 @@ private void delistComponentResources(ComponentInvocation inv, boolean suspend) try { Transaction tran = (Transaction) inv.getTransaction(); if (isTransactionActive(tran)) { - List l = getExistingResourceList(inv.getInstance(), inv); + List l = getExistingResourceList(inv.getInstance(), inv); if (l == null || l.size() == 0) { return; } int flag = (suspend) ? XAResource.TMSUSPEND : XAResource.TMSUCCESS; - Iterator it = l.iterator(); + Iterator it = l.iterator(); while (it.hasNext()) { - TransactionalResource h = (TransactionalResource) it.next(); + TransactionalResource h = it.next(); try { if (h.isEnlisted()) { delistResource(tran, h, flag); } } catch (IllegalStateException ex) { - if (LOG.isLoggable(Level.FINE)) - { + if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "TM: Exception in delistResource", ex); - // ignore error due to tx time out + // ignore error due to tx time out } } catch (Exception ex) { if (LOG.isLoggable(Level.FINE)) { @@ -1332,14 +1323,13 @@ private void enlistComponentResources(ComponentInvocation inv) throws Invocation try { Transaction tran = (Transaction) inv.getTransaction(); if (isTransactionActive(tran)) { - List l = getExistingResourceList(inv.getInstance(), inv); + List l = getExistingResourceList(inv.getInstance(), inv); if (l == null || l.size() == 0) { return; } - Iterator it = l.iterator(); - // END IASRI 4705808 TTT002 + Iterator it = l.iterator(); while (it.hasNext()) { - TransactionalResource h = (TransactionalResource) it.next(); + TransactionalResource h = it.next(); try { enlistResource(tran, h); } catch (Exception ex) { @@ -1351,7 +1341,6 @@ private void enlistComponentResources(ComponentInvocation inv) throws Invocation handleResourceError(h, ex, tran); } } - // END OF IASRI 4658504 } } catch (Exception ex) { LOG.log(Level.SEVERE, "enterprise_distributedtx.excep_in_enlist", ex); @@ -1361,11 +1350,11 @@ private void enlistComponentResources(ComponentInvocation inv) throws Invocation /** * Called by #componentDestroyed() */ - private void processResourceList(List l) { + private void processResourceList(List l) { if (l != null && l.size() > 0) { - Iterator it = l.iterator(); + Iterator it = l.iterator(); while (it.hasNext()) { - TransactionalResource h = (TransactionalResource) it.next(); + TransactionalResource h = it.next(); try { h.closeUserConnection(); } catch (Exception ex) { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CompletionHandler.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CompletionHandler.java index b0a8a823487..6321d2ecd45 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CompletionHandler.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CompletionHandler.java @@ -44,7 +44,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ // CHANGE HISTORY // @@ -66,9 +65,7 @@ interface CompletionHandler { * @param aborted Indicates whether the transaction locally aborted. * @param heuristicDamage Indicates local heuristic damage. * - * @return * - * @see */ abstract void setCompleted( boolean aborted, boolean heuristicDamage ); diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Configuration.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Configuration.java index cf1e8bbe714..72878c6d34e 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Configuration.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Configuration.java @@ -49,7 +49,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ // CHANGE HISTORY // @@ -310,7 +309,6 @@ public static final void setServerName( String name, boolean recoverableServer ) * Non-recoverable servers may not have a name, in which case the method returns * null. * - * @param * @return The server name. */ public static final String getServerName() { @@ -352,7 +350,6 @@ public static final String getServerName(String logPath) { * Non-recoverable servers may not have a name, in which case the method returns * null. * - * @param * @return The server name (byte array). */ public static final byte[] getServerNameByteArray() { @@ -434,7 +431,6 @@ public static final void setORB(org.omg.CORBA.ORB newORB) { /** * Returns the identity of the ORB. * - * @param * @return The ORB. */ public static final org.omg.CORBA.ORB getORB() { @@ -462,7 +458,6 @@ public static final void setFactory(TransactionFactory newFactory, boolean local /** * Returns the identity of the TransactionFactory. * - * @param * @return The TransactionFactory. */ public static final TransactionFactory getFactory() { @@ -475,7 +470,6 @@ public static final TransactionFactory getFactory() { /** * Determines whether we hava a local factory or a remote factory. * - * @param * @return Indicates whether we have a local factory. */ public static final boolean isLocalFactory() { @@ -490,7 +484,6 @@ public static final boolean isLocalFactory() { /** * Determines whether the JTS instance is recoverable. * - * @param * @return Indicates whether the JTS is recoverable. */ public static final boolean isRecoverable() { @@ -518,7 +511,6 @@ public static final void setProxyChecker(ProxyChecker newChecker) { /** * Returns the identity of the ProxyChecker. * - * @param * @return The ProxyChecker. */ public static final ProxyChecker getProxyChecker() { @@ -542,7 +534,6 @@ public static final void setLogFile(LogFile newLogFile) { /** * Returns the identity of the LogFile for the process. * - * @param * @return The LogFile. */ public static final LogFile getLogFile() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ControlImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ControlImpl.java index 5aa7c9f8e20..2da70872f7d 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ControlImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ControlImpl.java @@ -72,7 +72,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -111,11 +110,8 @@ public class ControlImpl extends JControlPOA implements Control { /**Default ControlImpl constructor. * - * @param * - * @return * - * @see */ ControlImpl() { @@ -136,9 +132,7 @@ public class ControlImpl extends JControlPOA implements Control { * @param globalTID The global identifier for the transaction. * @param localTID The local identifier for the transaction. * - * @return * - * @see */ ControlImpl( TerminatorImpl term, CoordinatorImpl coord, @@ -171,12 +165,10 @@ public class ControlImpl extends JControlPOA implements Control { * * @param ref The Control object for the transaction. * - * @return * * @exception Unavailable The required information to set up the Control object * is not available. * - * @see */ ControlImpl( Control ref ) throws Unavailable { @@ -208,11 +200,8 @@ public class ControlImpl extends JControlPOA implements Control { /**Cleans up the state of the object. * - * @param * - * @return * - * @see */ synchronized public void doFinalize() { @@ -243,11 +232,9 @@ synchronized public void doFinalize() { /**Returns the identifier that globally represents the transaction * - * @param * * @return The global identifier. * - * @see */ public GlobalTID getGlobalTID() { return globalTID; @@ -263,7 +250,6 @@ public GlobalTID getGlobalTID() { * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ synchronized public otid_t getGlobalTID( StatusHolder status ) throws SystemException { @@ -302,7 +288,6 @@ synchronized public otid_t getGlobalTID( StatusHolder status ) * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ synchronized public long getLocalTID( StatusHolder status ) throws SystemException { @@ -341,7 +326,6 @@ synchronized public long getLocalTID( StatusHolder status ) * * @return The stacked Control object. * - * @see */ synchronized ControlImpl popControl( StatusHolder status ) { @@ -370,12 +354,10 @@ synchronized ControlImpl popControl( StatusHolder status ) { * @param control The Control object to be stacked. * @param status An object to hold the status value, or null. * - * @return * * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ synchronized void pushControl( ControlImpl control, StatusHolder status ) @@ -410,14 +392,12 @@ synchronized void pushControl( ControlImpl control, * This operation is part of the OMG interface and must not return any * exceptions other than those defined in the OMG interface. * - * @param * * @return The Terminator for the transaction. * * @exception Unavailable The Terminator object is not available. * @exception SystemException The operation failed. * - * @see */ synchronized public Terminator get_terminator() @@ -495,14 +475,12 @@ synchronized public Terminator get_localTerminator() * This operation is part of the OMG interface and must not return * any exceptions other than those defined in the OMG interface. * - * @param * * @return The Coordinator for the transaction. * * @exception Unavailable The Coordinator is not available. * @exception SystemException The operation failed. * - * @see */ synchronized public Coordinator get_coordinator() throws Unavailable, SystemException { @@ -549,14 +527,12 @@ synchronized public Coordinator get_coordinator() * This operation is part of the OMG interface and must not return * any exceptions other than those defined in the OMG interface. * - * @param * * @return The Coordinator for the transaction. * * @exception Unavailable The Coordinator is not available. * @exception SystemException The operation failed. * - * @see */ synchronized public Coordinator get_localCoordinator() throws Unavailable, SystemException { @@ -592,11 +568,9 @@ synchronized public Coordinator get_localCoordinator() * within the context of the current ControlImpl instance have not yet * completed. * - * @param * * @return Indicates there are outgoing requests. * - * @see */ synchronized boolean isOutgoing() { @@ -608,11 +582,9 @@ synchronized boolean isOutgoing() { /**This operation returns a value which indicates that this ControlImpl instance * is associated with one or more threads. * - * @param * * @return Indicates an exisiting association. * - * @see */ synchronized boolean isAssociated() { boolean result = (association != 0); @@ -621,11 +593,9 @@ synchronized boolean isAssociated() { /**This operation returns the number of thread associations * - * @param * * @return Indicates the number of thread associations. * - * @see */ synchronized int numAssociated() { int result = association; @@ -634,11 +604,8 @@ synchronized int numAssociated() { /**Increment the thread association count. * - * @param * - * @return * - * @see */ synchronized void incrementAssociation() { association++; @@ -646,11 +613,9 @@ synchronized void incrementAssociation() { /**Decrement the thread association count. * - * @param * * @return Indicates the association count was above zero. * - * @see */ synchronized boolean decrementAssociation() { boolean result = (association > 0); @@ -660,11 +625,8 @@ synchronized boolean decrementAssociation() { /**Increment the incomplete asynchronous request counter. * - * @param * - * @return * - * @see */ synchronized void incrementOutgoing() { outgoing++; @@ -672,11 +634,9 @@ synchronized void incrementOutgoing() { /**Decrement the incomplete asynchronous request counter. * - * @param * * @return Indicates the request counter was above zero. * - * @see */ synchronized boolean decrementOutgoing() { boolean result = (outgoing > 0); @@ -686,11 +646,9 @@ synchronized boolean decrementOutgoing() { /**Returns the state of the transaction as the Control object knows it. * - * @param * * @return The transaction state. * - * @see */ synchronized public Status getTranState(){ Status result = tranState; @@ -702,9 +660,7 @@ synchronized public Status getTranState(){ * * @param int The new state. * - * @return * - * @see */ synchronized public void setTranState( Status newState ) { tranState = newState; @@ -714,12 +670,10 @@ synchronized public void setTranState( Status newState ) { /**Locates the first stacked ancestor which has not aborted. If there is no * such ancestor the operation returns null. * - * @param * * @return The first stacked Control which does not represent an aborted * transaction. * - * @see */ synchronized ControlImpl popAborted() { @@ -763,11 +717,9 @@ synchronized ControlImpl popAborted() { /**Determines whether the ControlImpl object represents a remote Control object * or a local one. * - * @param * * @return Indicates whether the ControlImpl represents a remote Control. * - * @see */ synchronized boolean representsRemoteControl() { @@ -777,13 +729,11 @@ synchronized boolean representsRemoteControl() { /**Returns the transaction context for the Coordinator. * - * @param * * @return The transaction context. * * @exception Unavailable No transaction context is available. * - * @see */ synchronized PropagationContext getTXContext() throws Unavailable { @@ -813,22 +763,17 @@ synchronized PropagationContext getTXContext() /**Dumps the state of the object. * - * @param * - * @return * - * @see */ void dump() { } /**Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ synchronized final Control object() { if( thisRef == null ) { @@ -865,7 +810,6 @@ synchronized final Control object() { * * @return The ControlImpl object which serves it. * - * @see */ synchronized public static final ControlImpl servant( JControl control ) { ControlImpl result = null; @@ -894,11 +838,8 @@ synchronized public static final ControlImpl servant( JControl control ) { /**Destroys the ControlImpl object. * - * @param * - * @return * - * @see */ synchronized final void destroy() { // GDH: We have no desire to destroy an underlying remote control object, instead we @@ -924,11 +865,8 @@ synchronized final void destroy() { /**Added to prevent null delegate problem. * - * @param * - * @return * - * @see */ public boolean equals(java.lang.Object o) { return this == o; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorImpl.java index 7e8ec609434..601e68b44a3 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorImpl.java @@ -78,7 +78,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLog.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLog.java index 97f4e6411ca..34fe0dd3b94 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLog.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLog.java @@ -66,7 +66,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -134,7 +133,6 @@ class CoordinatorLog extends java.lang.Object implements LogUpcallTarget { * * @return state for the given log location. * - * @see */ static private CoordinatorLogStateHolder getStateHolder(String str) { synchronized (logStateHoldertable) { @@ -158,11 +156,8 @@ static private CoordinatorLogStateHolder getStateHolder(String str) { /**Default CoordinatorLog constructor. * - * @param * - * @return * - * @see */ CoordinatorLog() { @@ -189,11 +184,8 @@ static private CoordinatorLogStateHolder getStateHolder(String str) { /**Default CoordinatorLog destructor. * - * @param * - * @return * - * @see */ synchronized public void doFinalize() { @@ -227,11 +219,8 @@ synchronized public void doFinalize() { * outstanding references to the object being finalized. * * - * @param * - * @return * - * @see */ synchronized private void reUse() { // Arun 9/27/99 @@ -289,9 +278,7 @@ synchronized private void reUse(String logPath) { * * @param localTID The local transaction identifier. * - * @return * - * @see */ CoordinatorLog( Long localTID ) { @@ -318,7 +305,6 @@ synchronized private void reUse(String logPath) { * * @return An object representing the section. * - * @see */ synchronized java.lang.Object createSection( String sectionName ) { @@ -353,7 +339,6 @@ synchronized java.lang.Object createSection( String sectionName ) { * * @return Indicates success of the operation. * - * @see */ synchronized boolean addObject( java.lang.Object sectionObj, @@ -415,7 +400,6 @@ synchronized boolean addObject( java.lang.Object sectionObj, * * @return Indicates success of the operation. * - * @see */ synchronized boolean addData( java.lang.Object sectionObj, @@ -487,7 +471,6 @@ synchronized boolean addData( java.lang.Object sectionObj, * * @return Indicates success of the operation. * - * @see */ boolean write( boolean force ) { @@ -509,11 +492,9 @@ boolean write( boolean force ) { * If the CoordinatorLog has state that has previously been written, it records * the requirement to rewrite, otherwise it does not record the requirement. * - * @param * * @return Indicates success of the operation. * - * @see */ private synchronized boolean requireRewrite() { boolean result = true; @@ -540,11 +521,9 @@ private synchronized boolean requireRewrite() { *

    * This operation discharges the CoordinatorLog's requirement to rewrite. * - * @param * * @return Indicates success of the operation. * - * @see */ private boolean rewrite() { @@ -579,7 +558,6 @@ private boolean rewrite() { * * @return Indicates success of the operation. * - * @see */ private boolean reconstruct( DataInputStream dataInput ) throws IOException { @@ -673,7 +651,6 @@ private boolean reconstruct( DataInputStream dataInput ) * * @return The objects. * - * @see */ java.lang.Object[] getObjects( java.lang.Object sectionObj ) { java.lang.Object[] result = null; @@ -780,7 +757,6 @@ java.lang.Object[] getObjects( java.lang.Object sectionObj ) { * * @return The data. * - * @see */ byte[][] getData( java.lang.Object sectionObj ) { @@ -822,9 +798,7 @@ byte[][] getData( java.lang.Object sectionObj ) { * * @param localTID The new local identifier. * - * @return * - * @see */ synchronized void setLocalTID( Long localTID ) { @@ -865,11 +839,9 @@ synchronized void setLocalTID( Long localTID, String logPath ) { * @param rewrite Indicates if the record is being rewritten. * @param dataOutput The stream to which to data is output. * - * @return * * @exception IOException The format failed. * - * @see */ private void formatSection( CoordinatorLogSection section, boolean rewrite, @@ -992,7 +964,6 @@ private void formatSection( CoordinatorLogSection section, * * @exception IOException The format failed. * - * @see */ private boolean formatLogRecords( boolean forced ) throws IOException { @@ -1059,11 +1030,8 @@ private boolean formatLogRecords( boolean forced ) /**Provides static initialisation of the CoordinatorLog class. * - * @param * - * @return * - * @see */ static { @@ -1082,11 +1050,9 @@ private boolean formatLogRecords( boolean forced ) *

    * If the log has already been opened, the operation uses the opened LogFile. * - * @param * * @return Indicates success of the operation. * - * @see */ private static boolean openLog() { boolean result = false; @@ -1137,11 +1103,9 @@ private static boolean openLog() { *

    * If the log has already been opened, the operation uses the opened LogFile. * - * @param * * @return Indicates success of the operation. * - * @see */ private static boolean openLog(String logPath) { boolean result = false; @@ -1191,11 +1155,9 @@ private static boolean openLog(String logPath) { /**Process the log to build a sequence of CoordinatorLog objects which * represent all logged transactions. * - * @param * * @return The CoordinatorLog objects, or null if there are none. * - * @see */ synchronized static Enumeration getLogged() { @@ -1260,11 +1222,9 @@ synchronized static Enumeration getLogged() { /**Process the log to build a sequence of CoordinatorLog objects which * represent all logged transactions. * - * @param * * @return The CoordinatorLog objects, or null if there are none. * - * @see */ synchronized static Enumeration getLogged(String logPath) { @@ -1335,7 +1295,6 @@ synchronized static Enumeration getLogged(String logPath) { * * @return Indicates success of the operation. * - * @see */ private static boolean addLog(Long localTID, CoordinatorLog clog ) { @@ -1365,7 +1324,6 @@ private static boolean addLog(Long localTID, * * @return Indicates success of the operation. * - * @see */ synchronized static boolean removeLog( Long localTID ) { @@ -1468,11 +1426,8 @@ synchronized static boolean removeLog( Long localTID , String logPath) { * operation to block other logging operations. The start of the keypoint is * in a separate method which is synchronized. * - * @param * - * @return * - * @see */ static void keypoint() { CoordinatorLogStateHolder logStateHolder = defaultLogStateHolder; @@ -1645,9 +1600,7 @@ static void keypoint(String logPath) { * * @param reason The reason for the upcall. * - * @return * - * @see */ public void upcall( int reason ){ @@ -1662,11 +1615,8 @@ public void upcall( int reason ){ /**Destroys the state of the CoordinatorLog class. * - * @param * - * @return * - * @see */ synchronized static void finalizeAll(){ @@ -1753,7 +1703,6 @@ synchronized static void finalizeAll(String logPath){ * * @return Indicates whether keypoint is required. * - * @see */ synchronized static boolean startKeypoint( LogLSN keypointStartLSN ) { @@ -1892,11 +1841,8 @@ synchronized static boolean startKeypoint( LogLSN keypointStartLSN, String logPa /**Dumps the state of the class. * - * @param * - * @return * - * @see */ static void dumpClass() { @@ -1922,7 +1868,6 @@ public static void setKeypointTrigger(int keypoint) * * @author Simon Holdsworth, IBM Corporation * - * @see */ // CHANGE HISTORY // @@ -1943,9 +1888,7 @@ class CoordinatorLogSection extends java.lang.Object { * * @param sectionName The name of the section. * - * @return * - * @see */ CoordinatorLogSection( String sectionName ) { this.sectionName = sectionName; @@ -1953,11 +1896,8 @@ class CoordinatorLogSection extends java.lang.Object { /**Destroys the contents of a CoordinatorLogSection. * - * @param * - * @return * - * @see */ public void doFinalize() { if( unwrittenObjects != null ) @@ -1991,11 +1931,8 @@ public void doFinalize() { * finalize also does not ensure that there are no * outstanding references to the object being finalized. * - * @param * - * @return * - * @see */ synchronized void reUse() { // Arun 9/27/99 @@ -2030,7 +1967,6 @@ synchronized void reUse() { // Arun 9/27/99 * * @author Arun Krishnan * - * @see */ class SectionPool { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLogPool.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLogPool.java index 94c699d2edc..ad34a11905d 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLogPool.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorLogPool.java @@ -43,7 +43,6 @@ * * @author Arun Krishnan * - * @see */ class CoordinatorLogPool { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorResourceImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorResourceImpl.java index 5abe4667042..2ed0af0274c 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorResourceImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorResourceImpl.java @@ -65,7 +65,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -111,9 +110,7 @@ class CoordinatorResourceImpl extends CoordinatorResourcePOA * @param coord The Coordinator for the transaction. * @param subtran Subtransaction indicator. * - * @return * - * @see */ CoordinatorResourceImpl( GlobalTID globalTID, CoordinatorImpl coord, @@ -142,7 +139,6 @@ class CoordinatorResourceImpl extends CoordinatorResourcePOA * @param aborted Indicates the transaction aborted. * @param heuristicDamage Indicates heuristic damage occurred. * - * @return * * @see CompletionHandler */ @@ -164,7 +160,6 @@ public void setCompleted( boolean aborted, *

    * The result from the Coordinator is returned to the caller. * - * @param * * @return The Coordinators vote. * @@ -258,9 +253,7 @@ public Vote prepare() * If the Coordinator does not raise any heuristic exception, the * CoordinatorResourceImpl destroys itself. * - * @param * - * @return * * @exception HeuristicRollback The transaction has already been rolled back. * @exception HeuristicMixed At least one participant in the transaction has @@ -368,9 +361,7 @@ public void commit() * Coordinator did not raise any heuristic exception, the CoordinatorResourceImpl * destroys itself. * - * @param * - * @return * * @exception TRANSACTION_ROLLEDBACK The transaction could not be committed and * has been rolled back. @@ -521,9 +512,7 @@ else if (vote == Vote.VoteRollback) { * If the Coordinator does not raise any heuristic exception, the * CoordinatorResourceImpl destroys itself. * - * @param * - * @return * * @exception HeuristicCommit The transaction has already been committed. * @exception HeuristicMixed At least one participant in the transaction has @@ -620,14 +609,11 @@ else if( heuristicDamage ) { * Informs the CoordinatorResourceImpl that it does not need to retain heuristic * information any longer. * - * @param * - * @return * * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ public void forget() throws SystemException { @@ -654,14 +640,12 @@ public void forget() throws SystemException { * * @param parent The parent Coordinator reference. * - * @return * * @exception TRANSACTION_ROLLEDBACK The transaction could not be committed * and some parts may have rolled back. * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ public void commit_subtransaction( Coordinator parent ) throws TRANSACTION_ROLLEDBACK, SystemException { @@ -741,14 +725,11 @@ public void commit_subtransaction( Coordinator parent ) * The result from the SubCoordinator is returned to the caller. The * CoordinatorResourceImpl destroys itself. * - * @param * - * @return * * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ public void rollback_subtransaction() throws SystemException { @@ -800,9 +781,7 @@ public void rollback_subtransaction() throws SystemException { * * @param key The key for the object. * - * @return * - * @see */ CoordinatorResourceImpl( byte[] key ) { @@ -840,11 +819,9 @@ public void rollback_subtransaction() throws SystemException { /**Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ CoordinatorResource object() { if( thisRef == null ) { @@ -896,11 +873,8 @@ CoordinatorResource object() { /**Destroys the CoordinatorResourceImpl object. * - * @param * - * @return * - * @see */ void destroy() { @@ -938,22 +912,16 @@ void destroy() { /**Dumps the state of the object. * - * @param * - * @return * - * @see */ void dump() { } /**Makes sure this object is set as the Coordinator Terminator * - * @param * - * @return * - * @see */ void makeSureSetAsTerminator() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorSynchronizationImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorSynchronizationImpl.java index 092fae0dcec..b9643a1c221 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorSynchronizationImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorSynchronizationImpl.java @@ -58,7 +58,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -81,11 +80,8 @@ class CoordinatorSynchronizationImpl extends SynchronizationPOA { /**Default CoordinatorSynchronizationImpl constructor. * - * @param * - * @return * - * @see */ CoordinatorSynchronizationImpl() { } @@ -95,9 +91,7 @@ class CoordinatorSynchronizationImpl extends SynchronizationPOA { * * @param coord The Coordinator for the transaction. * - * @return * - * @see */ CoordinatorSynchronizationImpl( TopCoordinator coord ) { @@ -112,14 +106,11 @@ class CoordinatorSynchronizationImpl extends SynchronizationPOA { /**Passes on the before completion operation to the Coordinator. * - * @param * - * @return * * @exception SystemException The operation failed. The minor code provides * a reason for the failure. * - * @see */ public void before_completion() throws SystemException { @@ -142,12 +133,10 @@ public void before_completion() * * @param status The state of the transaction. * - * @return * * @exception SystemException The operation failed. The minor code provides * a reason for the failure. * - * @see */ public void after_completion( Status status ) throws SystemException { @@ -170,11 +159,9 @@ public void after_completion( Status status ) /**Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ Synchronization object() { if( poa == null ) poa = Configuration.getPOA("transient"/*#Frozen*/); @@ -213,11 +200,8 @@ Synchronization object() { /**Destroys the CoordinatorSynchronizationImpl object. * - * @param * - * @return * - * @see */ void destroy() { if( poa != null && @@ -240,7 +224,6 @@ void destroy() { * * @return The CoordinatorSynchronizationImpl object which serves it. * - * @see */ synchronized static final CoordinatorSynchronizationImpl servant(Synchronization sync) { CoordinatorSynchronizationImpl result = null; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorTerm.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorTerm.java index 38941022659..57b3293528a 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorTerm.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CoordinatorTerm.java @@ -57,7 +57,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -82,11 +81,8 @@ class CoordinatorTerm implements CompletionHandler { /**Default CoordinatorTerm constructor. * - * @param * - * @return * - * @see */ CoordinatorTerm() { } @@ -103,9 +99,7 @@ class CoordinatorTerm implements CompletionHandler { * @param coord The Coordinator for the transaction. * @param subtran The subtransaction indicator. * - * @return * - * @see */ CoordinatorTerm( CoordinatorImpl coord, boolean subtran ) { @@ -138,7 +132,6 @@ class CoordinatorTerm implements CompletionHandler { * * @param promptReturn Indicates whether to return promptly. * - * @return * * @exception TRANSACTION_ROLLEDBACK The transaction could not be committed and * has been rolled back. @@ -150,7 +143,6 @@ class CoordinatorTerm implements CompletionHandler { * @exception SystemException An error occurred calling another object. * @exception LogicErrorException An internal logic error occurred. * - * @see */ void commit( boolean promptReturn ) throws HeuristicMixed, HeuristicHazard, TRANSACTION_ROLLEDBACK, @@ -428,9 +420,7 @@ else if (otherExc instanceof INTERNAL) * Uses a private interface to pass the Terminator's rollback request on to * the Coordinator. * - * @param * - * @return * * @exception HeuristicHazard Heuristic action may have been taken by a * participant in the transaction. @@ -440,7 +430,6 @@ else if (otherExc instanceof INTERNAL) * @exception SystemException An error occurred calling another object. * @exception LogicErrorException An internal logic error occurred. * - * @see */ void rollback() throws HeuristicMixed, HeuristicHazard, SystemException, @@ -555,9 +544,7 @@ void rollback() * @param aborted Indicates whether the transaction locally aborted. * @param heuristicDamage Indicates local heuristic damage. * - * @return * - * @see */ public void setCompleted( boolean aborted, @@ -588,11 +575,8 @@ public void setCompleted( boolean aborted, /**Dumps the state of the object. * - * @param * - * @return * - * @see */ void dump() { } diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentImpl.java index 08788d30e36..f14228b4271 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentImpl.java @@ -68,7 +68,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -89,11 +88,8 @@ public class CurrentImpl extends org.omg.CORBA.LocalObject /**Default CurrentImpl constructor. * - * @param * - * @return * - * @see */ CurrentImpl() { @@ -112,9 +108,7 @@ public class CurrentImpl extends org.omg.CORBA.LocalObject * Control that represents the parent transaction is stacked behind the new one, * which becomes the current one. * - * @param * - * @return * * @exception SubtransactionsUnavailable A subtransaction cannot be begun, * either because the Transaction Service does not support nested transactions @@ -123,7 +117,6 @@ public class CurrentImpl extends org.omg.CORBA.LocalObject * current thread of control has pending non-transactional work. * @exception SystemException The operation failed. * - * @see */ @Override public void begin() @@ -293,9 +286,7 @@ public void begin() * Control that represents the parent transaction is stacked behind the new one, * which becomes the current one. * - * @param * - * @return * * @exception SubtransactionsUnavailable A subtransaction cannot be begun, * either because the Transaction Service does not support nested transactions @@ -304,7 +295,6 @@ public void begin() * current thread of control has pending non-transactional work. * @exception SystemException The operation failed. * - * @see */ public void begin(int time_out) throws INVALID_TRANSACTION, SystemException, SubtransactionsUnavailable { @@ -460,7 +450,6 @@ public void begin(int time_out) * @param reportHeuristics Indicates that heuristic exceptions should be * passed back to the caller. * - * @return * * @exception NoTransaction There is no current transaction to commit. * @exception INVALID_TRANSACTION The current transaction has outstanding @@ -475,7 +464,6 @@ public void begin(int time_out) * in the transaction. * @exception SystemException The operation failed. * - * @see */ @Override public void commit( boolean reportHeuristics ) @@ -609,9 +597,7 @@ public void commit( boolean reportHeuristics ) *

    * This operation can only be called if there is a Terminator object available. * - * @param * - * @return * * @exception NoTransaction There is no current transaction to rollback. * @exception INVALID_TRANSACTION The current transaction has outstanding @@ -622,7 +608,6 @@ public void commit( boolean reportHeuristics ) * back. * @exception SystemException The operation failed. * - * @see */ @Override public void rollback() @@ -755,14 +740,11 @@ public void rollback() /**Marks the current transaction such that is cannot be committed and only * rolled back. * - * @param * - * @return * * @exception NoTransaction There is no current transaction to mark rollback- * only. * - * @see */ @Override public void rollback_only() @@ -785,12 +767,10 @@ public void rollback_only() /**Returns the status of the current transaction. * - * @param * * @return The current status of the transaction. If there is no * current transaction, the value StatusNoTransaction is returned. * - * @see */ @Override public Status get_status() { @@ -816,12 +796,10 @@ public Status get_status() { /**Returns a printable string representing the current transaction. * - * @param * * @return The transaction name. If there is no current transaction, * null is returned. * - * @see */ @Override public String get_transaction_name() { @@ -849,9 +827,7 @@ public String get_transaction_name() { * * @param timeout The timeout value in seconds. * - * @return * - * @see */ @Override public void set_timeout( int timeout ) { @@ -870,7 +846,6 @@ public int get_timeout() { /**Returns the current ControlImpl object. * - * @param * * @return The Control object for the current transaction, or null * if there is no current transaction. @@ -878,7 +853,6 @@ public int get_timeout() { * @exception TRANSACTION_ROLLEDBACK The current transaction has been rolled * back. * - * @see */ @Override public Control get_control() @@ -905,12 +879,10 @@ public Control get_control() /**Disassociates the current ControlImpl from the calling thread. * - * @param * * @return The Control object for the suspended transaction. If * there was no transaction, this will be null. * - * @see */ @Override public Control suspend() { @@ -940,7 +912,6 @@ public Control suspend() { * * @param control The Control object to be made current. * - * @return * * @exception InvalidControl The Control object passed as a parameter is * not valid. This may be because the transaction it represents has @@ -948,7 +919,6 @@ public Control suspend() { * @exception INVALID_TRANSACTION The transaction could not be begun as the * current thread of control has pending non-transactional work. * - * @see */ @Override public void resume( Control control ) @@ -1017,9 +987,7 @@ public void resume( Control control ) * * @param immediate Indicates whether to ignore running transactions. * - * @return * - * @see */ synchronized void shutdown( boolean immediate ) { @@ -1032,11 +1000,8 @@ synchronized void shutdown( boolean immediate ) { /**Prevents any further transactional activity in the process. * - * @param * - * @return * - * @see */ static void deactivate() { active = false; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentTransaction.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentTransaction.java index 373cbfa758a..33b9a19f387 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentTransaction.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/CurrentTransaction.java @@ -67,7 +67,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -109,11 +108,8 @@ public class CurrentTransaction { /**Initialises the static state of the CurrentTransaction class. * - * @param * - * @return * - * @see */ static void initialise() { @@ -138,7 +134,6 @@ static void initialise() { * * @return Indicates success of the operation. * - * @see */ static boolean setCurrent(ControlImpl control, boolean stack) { boolean result = false; @@ -241,7 +236,6 @@ static boolean setCurrent(ControlImpl control, boolean stack) { * * @return The current Control object. * - * @see */ static ControlImpl endCurrent( boolean unstack ) { @@ -348,7 +342,6 @@ public static boolean isTxAssociated() { * * @return The current Control object. * - * @see */ private static ControlImpl endAborted( boolean[/*1*/] aborted, boolean endAssociation) { @@ -431,9 +424,7 @@ public static boolean isTxAssociated() { * * @param control The Control object which has been suspended. * - * @return * - * @see */ static void addSuspended( ControlImpl control ) { if(statsOn) @@ -448,7 +439,6 @@ static void addSuspended( ControlImpl control ) { * * @return Indicates success of the operation. * - * @see */ static boolean removeSuspended( ControlImpl control ) { boolean result = true; @@ -463,12 +453,10 @@ static boolean removeSuspended( ControlImpl control ) { * under which the operation was invoked. If there is no such association the * null value is returned. * - * @param * * @return The current Control object. * * - * @see */ public static ControlImpl getCurrent() throws TRANSACTION_ROLLEDBACK { @@ -488,7 +476,6 @@ public static ControlImpl getCurrent() * Note that this operation can be optimised so that the Coordinator reference is * stored along with the Control reference when the thread association is set up. * - * @param * * @return The current Coordinator. * @@ -496,7 +483,6 @@ public static ControlImpl getCurrent() * back. * @exception Unavailable The Coordinator object is not available. * - * @see */ static Coordinator getCurrentCoordinator() throws TRANSACTION_ROLLEDBACK, Unavailable { @@ -542,7 +528,6 @@ static Coordinator getCurrentCoordinator() * * @return The number of active thread associations. * - * @see */ static int numActive( Long localTID, boolean[/*1*/] outstanding ) { @@ -587,9 +572,7 @@ static int numActive( Long localTID, * * @param obj The StaticResource being registered. * - * @return * - * @see */ synchronized static void registerStatic( StaticResource obj ) { @@ -607,11 +590,9 @@ synchronized static void registerStatic( StaticResource obj ) { /**Returns all the transactions in the system that are currently suspended * in the form of a sequence of Control objects. * - * @param * * @return The list of suspended Control objects. * - * @see */ static Control[] getSuspendedTransactions() { @@ -641,11 +622,9 @@ static Control[] getSuspendedTransactions() { /**Returns all the transactions in the system that are currently running * (i.e. not suspended) in the form of a sequence of Control objects. * - * @param * * @return The list of running Control objects. * - * @see */ static Control[] getRunningTransactions() { if(!statsOn){ @@ -674,11 +653,9 @@ static Control[] getRunningTransactions() { /**Returns all the transactions in the system that are currently running * or suspended in the form of a sequence of Control objects. * - * @param * * @return The list of all Control objects. * - * @see */ static Control[] getAllTransactions() { @@ -718,14 +695,12 @@ static Control[] getAllTransactions() { * @param id The request identifier. * @param holder The completed context object. * - * @return * * @exception TRANSACTION_ROLLEDBACK The current transaction has been rolled * back. The message should not be sent and TRANSACTION_ROLLEDBACK should * be returned to the caller. * @exception TRANSACTION_REQUIRED There is no current transaction. * - * @see */ static void sendingRequest( int id, PropagationContextHolder holder ) @@ -823,12 +798,10 @@ static void sendingRequest( int id, * @param context The PropagationContext from the message. * @param ex The exception on the message. * - * @return * * @exception WrongTransaction The context returned on the reply is for a * different transaction from the current one on the thread. * - * @see */ static void receivedReply( int id, PropagationContext context, @@ -944,9 +917,7 @@ static void receivedReply( int id, * @param id The request identifier. * @param context The PropagationContext from the message. * - * @return * - * @see */ static void receivedRequest( int id, PropagationContext context ) { @@ -1010,7 +981,6 @@ static void receivedRequest( int id, * @exception TRANSACTION_ROLLEDBACK The current transaction has already been * rolled back. * - * @see */ static void sendingReply( int id, PropagationContextHolder holder ) @@ -1274,9 +1244,7 @@ public static void release(GlobalTID tid) { * @param globalTID The global transaction identifier. * @param aborted Indicates whether the transaction has aborted. * - * @return * - * @see */ //not used anywhere synchronized static void endAll( GlobalTID globalTID, @@ -1331,9 +1299,7 @@ synchronized static void endAll( GlobalTID globalTID, * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ static void shutdown( boolean immediate ) { @@ -1342,11 +1308,8 @@ static void shutdown( boolean immediate ) { /**Dumps the static state of the class. * - * @param * - * @return * - * @see */ static void dump() { } @@ -1356,9 +1319,7 @@ static void dump() { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ /* static diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DefaultTransactionService.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DefaultTransactionService.java index 9c26e6c76d2..a46d0bc4ee1 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DefaultTransactionService.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DefaultTransactionService.java @@ -70,7 +70,6 @@ * @author Simon Holdsworth, IBM Corporation * @author mvatkina * - * @see */ //----------------------------------------------------------------------------// CHANGE HISTORY // @@ -97,11 +96,8 @@ public class DefaultTransactionService implements ProxyChecker { /**Default constructor. * - * @param * - * @return * - * @see */ public DefaultTransactionService() { // We do not set up the Current instance until we know the ORB. @@ -120,11 +116,9 @@ public static boolean isActive() { /**Obtain the implementation of the Current interface provided * by the transaction service implementation. * - * @param * * @return An instance of the Current class * - * @see */ public org.omg.CosTransactions.Current get_current() { org.omg.CosTransactions.Current result = null; @@ -145,9 +139,7 @@ public org.omg.CosTransactions.Current get_current() { * Receiver must be registered. * @param properties The Properties with which the ORB was initialised. * - * @return * - * @see */ public void identify_ORB(ORB orb, TSIdentification ident, @@ -296,9 +288,7 @@ public static void setServerName(Properties properties) { * * @param immediate Indicates whether to ignore running transactions. * - * @return * - * @see */ public static void shutdown( boolean immediate ) { // Remove the admin and factory objects from the naming service. @@ -336,7 +326,6 @@ public static void shutdown( boolean immediate ) { * * @return Indicates whether the object is a proxy. * - * @see */ public final boolean isProxy( org.omg.CORBA.Object obj ) { @@ -346,13 +335,10 @@ public final boolean isProxy( org.omg.CORBA.Object obj ) { /**Creates the POA objects which are used for objects within the JTS. * - * @param * - * @return * * @exception Exception The operation failed. * - * @see */ final static void createPOAs() throws Exception { @@ -461,7 +447,6 @@ private static String getAdjustedServerName(String originalName) { * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -497,9 +482,7 @@ public String[] _ids () { * * @param orb The ORB. * - * @return * - * @see */ RecoveryCoordinatorServantActivator(ORB orb) { this.orb = orb; @@ -513,7 +496,6 @@ public String[] _ids () { * * @return The servant. * - * @see */ public Servant incarnate( byte[] oid, POA adapter ) throws org.omg.PortableServer.ForwardRequest { @@ -525,11 +507,8 @@ public Servant incarnate( byte[] oid, POA adapter ) /**Does nothing. * - * @param * - * @return * - * @see */ public void etherealize( byte[] oid, POA adapter, @@ -547,7 +526,6 @@ public void etherealize( byte[] oid, * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -583,9 +561,7 @@ public String[] _ids () { * * @param orb The ORB. * - * @return * - * @see */ CoordinatorResourceServantActivator(ORB orb) { this.orb = orb; @@ -599,7 +575,6 @@ public String[] _ids () { * * @return The servant. * - * @see */ public Servant incarnate( byte[] oid, POA adapter ) throws org.omg.PortableServer.ForwardRequest { @@ -609,11 +584,8 @@ public Servant incarnate( byte[] oid, POA adapter ) /**Does nothing. * - * @param * - * @return * - * @see */ public void etherealize( byte[] oid, POA adapter, diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedRecoveryManager.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedRecoveryManager.java index e86cfc307b9..08b19ccbfc0 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedRecoveryManager.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedRecoveryManager.java @@ -55,7 +55,6 @@ * * @author Sankara Rao Bhogi * - * @see */ public class DelegatedRecoveryManager { @@ -426,7 +425,6 @@ private static void resyncComplete(boolean resynced, * * @return The Coordinator object. * - * @see */ static CoordinatorImpl getLocalCoordinator(Long localTID, String logPath) { @@ -448,7 +446,6 @@ static CoordinatorImpl getLocalCoordinator(Long localTID, String logPath) { * * @return Indicates the local transaction identifier is valid. * - * @see */ static boolean validLocalTID(Long localTID, String logPath) { @@ -469,9 +466,7 @@ static boolean validLocalTID(Long localTID, String logPath) { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ static void shutdown(boolean immediate) { @@ -723,7 +718,6 @@ private static void proceedWithXARecovery(String logPath) { * * @return The array of Coordinators. * - * @see */ static CoordinatorImpl[] getCoordinators(String logPath) { @@ -765,9 +759,7 @@ public static void waitForRecovery(String logPath) { * * @param logPath log location for which the delegated recovery is done * - * @return * - * @see */ public static void waitForResync(String logPath) { final RecoveryStateHolder state = (RecoveryStateHolder)recoveryStatetable.get(logPath); diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedTimeoutManager.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedTimeoutManager.java index f35abd0431d..0429b9ed353 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedTimeoutManager.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/DelegatedTimeoutManager.java @@ -39,7 +39,6 @@ * @version 0.01 * * - * @see */ class DelegatedTimeoutManager { @@ -71,11 +70,8 @@ class DelegatedTimeoutManager { /** * Initialises the static state of the TimeoutManager class. * - * @param * - * @return * - * @see */ /** * synchronized static void initialise() { @@ -128,7 +124,6 @@ synchronized void initSetTimeout() { * * @return Indicates success of the operation. * - * @see */ boolean setTimeout(Long localTID, int timeoutType, int seconds) { @@ -203,9 +198,7 @@ boolean setTimeout(Long localTID, int timeoutType, * @param localTID The local identifier for the transaction. * @param timeoutType The type of timeout. * - * @return * - * @see */ void timeoutCoordinator(Long localTID, int timeoutType) { @@ -318,11 +311,9 @@ void timeoutCoordinator(Long localTID, int timeoutType) { * cause a deadlock when RecoveryManager methods on other threads call * setTimeout. * - * @param * * @return The information for transactions which have timed out. * - * @see */ Enumeration checkTimeouts() { if (!isSetTimeout) @@ -444,7 +435,6 @@ XID[] getInDoubtXids() { * this value will be negative. If the timeout period has been * exceeded, this value will be zero. * - * @see */ long timeLeft(Long localTID) { @@ -472,9 +462,7 @@ long timeLeft(Long localTID) { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ void shutdown(boolean immediate) { @@ -510,7 +498,6 @@ void shutdown(boolean immediate) { * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -533,7 +520,6 @@ class DelegatedTimeoutInfo extends Object { * @version 0.01 * * - * @see */ @@ -549,11 +535,8 @@ class DelegatedTimeoutThread extends Thread { * This sets the thread name, and sets the thread to be a daemon thread so * that it does not prevent the process from terminating. * - * @param * - * @return * - * @see */ DelegatedTimeoutThread(DelegatedTimeoutManager timeoutMgr) { setName("Delegated JTS Timeout Thread"/*#Frozen*/); @@ -578,11 +561,8 @@ class DelegatedTimeoutThread extends Thread { /** * Performs timeout checking on a regular basis (every ten seconds or so). * - * @param * - * @return * - * @see */ public void run() { try { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/EventSemaphore.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/EventSemaphore.java index 0ed0b910cfc..d80151c95ec 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/EventSemaphore.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/EventSemaphore.java @@ -41,7 +41,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -55,11 +54,8 @@ public class EventSemaphore { /**Default EventSemaphore constructor. * - * @param * - * @return * - * @see */ EventSemaphore() { } @@ -68,9 +64,7 @@ public class EventSemaphore { * * @param posted Indicates whether the semaphore should be posted. * - * @return * - * @see */ EventSemaphore( boolean posted ) { this.posted = posted; @@ -87,13 +81,10 @@ synchronized public boolean isPosted() { *

    * If the event has already been posted, then the operation returns immediately. * - * @param * - * @return * * @exception InterruptedException The wait was interrupted. * - * @see */ synchronized public void waitEvent() throws InterruptedException { @@ -108,11 +99,9 @@ synchronized public void waitEvent() * * @param cmtTimeout - container managed transaction timeout * - * @return * * @exception InterruptedException The wait was interrupted. * - * @see */ synchronized public void waitTimeoutEvent(int cmtTimeout) @@ -130,11 +119,8 @@ synchronized public void waitTimeoutEvent(int cmtTimeout) *

    * All waiters are notified. * - * @param * - * @return * - * @see */ synchronized void post() { if( !posted ) @@ -144,11 +130,8 @@ synchronized void post() { /**Clears a posted event semaphore. * - * @param * - * @return * - * @see */ synchronized void clear() { posted = false; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/GlobalTID.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/GlobalTID.java index de79ca79ab9..16f1f9e48e3 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/GlobalTID.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/GlobalTID.java @@ -46,7 +46,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -77,9 +76,7 @@ public class GlobalTID extends Object { * * @param otherTID The other global identifier. * - * @return * - * @see */ public GlobalTID( otid_t otherTID ) { realTID = otherTID; @@ -91,9 +88,7 @@ public GlobalTID( otid_t otherTID ) { * @param bqual_length The branch qualifier. * @param data The identifier data. * - * @return * - * @see */ GlobalTID( int formatID, int bqual_length, @@ -122,9 +117,7 @@ public GlobalTID(javax.transaction.xa.Xid xid) { * * @param dataIn The DataInputStream for the operation. * - * @return * - * @see */ GlobalTID( DataInputStream dataIn ) { try { @@ -142,9 +135,7 @@ public GlobalTID(javax.transaction.xa.Xid xid) { * * @param The array of bytes. * - * @return * - * @see */ GlobalTID( byte[] bytes ) { int formatID = (bytes[0]&255) + @@ -163,11 +154,9 @@ public GlobalTID(javax.transaction.xa.Xid xid) { /**Creates a new global identifier which is a copy of the target object. * - * @param * * @return The copy. * - * @see */ final GlobalTID copy() { GlobalTID result = new GlobalTID(realTID); @@ -181,11 +170,9 @@ final GlobalTID copy() { /**Determines whether the global identifier represents the null transaction * identifier. * - * @param * * @return Indicates whether the global identifier is null. * - * @see */ final boolean isNullTID() { return realTID.formatID == -1; @@ -199,7 +186,6 @@ final boolean isNullTID() { * * @return Indicates the two global identifiers are equal. * - * @see */ public final boolean equals( Object other ) { return isSameTIDInternal(other); @@ -256,11 +242,9 @@ public final boolean isSameTID( otid_t otherTID ) { /**Returns a hash value for the global identifier. * - * @param * * @return The hash value. * - * @see */ public final int hashCode() { @@ -386,11 +370,9 @@ public GlobalTID(String stid){ /**Converts the global identifier to a string. * - * @param * * @return The string representation of the identifier. * - * @see */ public final String toString() { @@ -443,11 +425,9 @@ public final String toString() { /**Converts the global identifier to a byte array. * - * @param * * @return The byte array representation of the identifier. * - * @see */ final byte[] toBytes() { if( realTID.formatID == -1 ) @@ -482,9 +462,7 @@ static GlobalTID fromTIDBytes(byte[] bytes) { * * @param dataOut The DataOutputStream for the operation. * - * @return * - * @see */ final void write( DataOutputStream dataOut ) { try { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Log.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Log.java index d8b425a00ba..47d5b9bd069 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Log.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Log.java @@ -47,7 +47,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -73,11 +72,8 @@ class Log { /**Default Log constructor. * - * @param * - * @return * - * @see */ Log() { // We need to ensure that messaging is initialised as this may be called @@ -95,11 +91,8 @@ class Log { /**Initialises the log. * - * @param * - * @return * - * @see */ boolean initialise() { boolean result = true; @@ -124,7 +117,6 @@ boolean initialise() { * * @return The object representing the physical log file. * - * @see */ LogFile open( String serverName, LogUpcallTarget upcall ) { @@ -157,11 +149,8 @@ LogFile open( String serverName, /**Terminates the log. * - * @param * - * @return * - * @see */ boolean terminate() { @@ -179,9 +168,7 @@ boolean terminate() { * * @param String * - * @return * - * @see */ static boolean checkFileExists( String serverName ) { // Check whether the file exists. @@ -197,11 +184,8 @@ static boolean checkFileExists( String serverName ) { /**Dumps the state of the object. * - * @param * - * @return * - * @see */ void dump() { //! somtrDUMP_OBJECT_HEADER; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControl.java index 31a2837b17a..327d29e06cb 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControl.java @@ -65,9 +65,7 @@ public class LogControl { * @param readOnly Read only log indicator. * @param logDirectory Directory for log files. * - * @return * - * @see */ synchronized void initLog( boolean coldStart, boolean readOnly, @@ -118,7 +116,6 @@ synchronized void initLog( boolean coldStart, * * @exception LogException The open failed. * - * @see */ synchronized LogHandle openFile( String logFileName, LogUpcallTarget upcallTarget, @@ -655,11 +652,9 @@ synchronized LogHandle openFile( String logFileName, * * @param logHandle The log to clean up. * - * @return * * @exception LogException The operation failed. * - * @see */ synchronized void cleanUp( LogHandle logHandle ) throws LogException { @@ -704,7 +699,6 @@ synchronized void cleanUp( LogHandle logHandle ) * * @return Indicates whether the file exists. * - * @see */ static boolean checkFileExists( String logId, @@ -724,9 +718,7 @@ static boolean checkFileExists( String logId, * * @param logHandle * - * @return * - * @see */ synchronized void removeFile( LogHandle logHandle ) { @@ -742,11 +734,8 @@ synchronized void removeFile( LogHandle logHandle ) { /**Dumps the state of the object. * - * @param * - * @return * - * @see */ //---------------------------------------------------------------------------- void dump() { @@ -759,9 +748,7 @@ void dump() { * * @param logDir * - * @return * - * @see */ static void clearDirectory( String logDir ) { // Find each control file in turn and then delete all files that @@ -800,7 +787,6 @@ static void clearDirectory( String logDir ) { * * @return A File object representing the extent file. * - * @see */ File extentFile(String logId, int extent) { @@ -828,7 +814,6 @@ File extentFile(String logId, int extent) { * * @return A File object representing the control file. * - * @see */ final static File controlFile( String logId, String logDir ) { File result = new File(directory(logId,logDir),CONTROL_NAME); @@ -841,7 +826,6 @@ final static File controlFile( String logId, String logDir ) { * * @return A File object representing the cushion file. * - * @see */ final File cushionFile( String logId ) { @@ -857,7 +841,6 @@ final File cushionFile( String logId ) { * * @return A File object representing the directory. * - * @see */ final static File directory( String logId, String logDir ) { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControlDescriptor.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControlDescriptor.java index 0b5413a5caf..67fc5dbbb14 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControlDescriptor.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogControlDescriptor.java @@ -58,11 +58,8 @@ class LogControlDescriptor implements Serializable { /**Default LogControlDescriptor constructor. * - * @param * - * @return * - * @see */ LogControlDescriptor() { headLSN = new LogLSN(); @@ -75,9 +72,7 @@ class LogControlDescriptor implements Serializable { * @param bytes The array of bytes from which the object is to be constructed. * @param index The index in the array where copy is to start. * - * @return * - * @see */ LogControlDescriptor( byte[] bytes, int index ) { @@ -93,7 +88,6 @@ class LogControlDescriptor implements Serializable { * * @return Number of bytes copied. * - * @see */ final int toBytes( byte[] bytes, int index ) { @@ -106,12 +100,10 @@ final int toBytes( byte[] bytes, /**This method is called to direct the object to format its state into a String. * - * @param * * @return The formatted representation of the object. - * - * @see */ + @Override public final String toString() { return "LCD(head="/*#Frozen*/+headLSN+",tail="/*#Frozen*/+tailLSN+",next="/*#Frozen*/+nextLSN+")"/*#Frozen*/; } diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogCursor.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogCursor.java index 3e9cce38ca3..c65b852f380 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogCursor.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogCursor.java @@ -39,7 +39,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -74,9 +73,7 @@ class LogCursor { * @param startLSN The LSN for the start of the browse. * @param endLSN The LSN for the end of the browse. * - * @return * - * @see */ LogCursor( LogControl control, LogHandle handle, @@ -120,7 +117,6 @@ class LogCursor { * * @exception LogException The operation failed. * - * @see */ synchronized byte[] readCursor( int[/*1*/] type, LogLSN LSNread ) diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogException.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogException.java index a233094a339..95571de0582 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogException.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogException.java @@ -38,7 +38,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -127,9 +126,7 @@ class LogException extends Exception { * @param err The error code. * @param point The throw point. * - * @return * - * @see */ LogException(Object dummy /* COMMENT(Ram J) - used to be trace object */, int err, @@ -146,9 +143,7 @@ class LogException extends Exception { * @param point The throw point. * @param extra Extra information. * - * @return * - * @see */ LogException(Object dummy /* COMMENT(Ram J) - used to be trace object */, int err, diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogExtent.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogExtent.java index 2c2f7f3688d..3b00210835c 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogExtent.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogExtent.java @@ -42,7 +42,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -112,9 +111,7 @@ class LogExtent extends Object { * @param extent The number of the extent. * @param extentFH The handle of the extent file. * - * @return * - * @see */ LogExtent( int extent, LogFileHandle extentFH, @@ -126,11 +123,8 @@ class LogExtent extends Object { /**Default LogExtent destructor. * - * @param * - * @return * - * @see */ public void doFinalize() { try { @@ -147,7 +141,6 @@ public void doFinalize() { * * @return The modulated extent number. * - * @see */ final static int modExtent( int ext ) { return (ext % MAX_NO_OF_EXTENTS); diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFile.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFile.java index 0adb932d777..372c15fd06f 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFile.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFile.java @@ -47,7 +47,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -84,9 +83,7 @@ class LogFile { * * @param LogHandle * - * @return * - * @see */ LogFile( LogHandle handle ) { @@ -112,9 +109,7 @@ class LogFile { * @param recordType Log record type. * @param recordLSN LSN of the written record. * - * @return * - * @see */ synchronized boolean write( int writeType, byte[] record, @@ -153,9 +148,7 @@ synchronized boolean write( int writeType, * * @param firstLSN * - * @return * - * @see */ synchronized boolean checkpoint( LogLSN firstLSN ) { @@ -188,7 +181,6 @@ synchronized boolean checkpoint( LogLSN firstLSN ) { * * @return Indicates success of the operation. * - * @see */ synchronized boolean writeRestart( byte[] record ) { @@ -209,11 +201,9 @@ synchronized boolean writeRestart( byte[] record ) { /**Reads the restart record from the log. *

    * - * @param * * @return The restart record. * - * @see */ synchronized byte[] readRestart() { byte[] result = null; @@ -234,9 +224,7 @@ synchronized byte[] readRestart() { * * @param deleteFile * - * @return * - * @see */ synchronized boolean close( boolean deleteFile ) { @@ -262,11 +250,9 @@ synchronized boolean close( boolean deleteFile ) { * The result is returned in a Vector as we do not know ahead of time how * many log records there are. * - * @param * * @return The log records. * - * @see */ synchronized Vector getLogRecords() { Vector logRecords = new Vector(); @@ -352,11 +338,8 @@ synchronized Vector getLogRecords() { /**Dumps the state of the object. * - * @param * - * @return * - * @see */ void dump() { //! somtrDump_OBJECT_HEADER; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFileHandle.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFileHandle.java index cfea6173663..9fa3cff1bc4 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFileHandle.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogFileHandle.java @@ -43,7 +43,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -124,11 +123,8 @@ class LogFileHandle { /**Default LogFileHandle constructor. * - * @param * - * @return * - * @see */ LogFileHandle() { fhandle = null; @@ -141,11 +137,9 @@ class LogFileHandle { * @param file The File to be opened. * @param int Open options * - * @return * * @exception LogException Opening the file failed. * - * @see */ LogFileHandle( File file, int openOptions ) @@ -173,13 +167,10 @@ class LogFileHandle { /**Destroys the FileHandle, closing the file, if open. * - * @param * - * @return * * @exception LogException The close of the file failed. * - * @see */ void destroy() throws LogException { @@ -206,7 +197,6 @@ protected void finalize() * * @exception LogException The read failed. * - * @see */ int fileRead( byte[] buffer ) throws LogException{ @@ -261,7 +251,6 @@ int fileRead( byte[] buffer ) * * @exception LogException The write failed. * - * @see */ int fileWrite( byte[] buffer ) throws LogException { @@ -323,11 +312,9 @@ int fileWrite( byte[] buffer ) * @param file The name of the file. * @param fileMode The mode to open in. * - * @return * * @exception LogException The open failed. * - * @see */ void fileOpen( File file, String fileMode ) @@ -356,13 +343,10 @@ void fileOpen( File file, /**Closes the file. * - * @param * - * @return * * @exception LogException The close failed * - * @see */ void fileClose() throws LogException { @@ -395,11 +379,9 @@ void fileClose() * @param position Position to seek. * @param seekMode Mode of seek. * - * @return * * @exception LogException The seek failed. * - * @see */ void fileSeek( long position, @@ -436,13 +418,10 @@ void fileSeek( long position, /**Synchronises (flushes) the file to the file system. * - * @param * - * @return * * @exception LogException The sync failed * - * @see */ void fileSync() throws LogException { @@ -473,7 +452,6 @@ void fileSync() throws LogException { * * @exception LogException The read failed. * - * @see */ int readVector( byte[][] vector ) throws LogException { @@ -488,11 +466,9 @@ int readVector( byte[][] vector ) * * @param bytesToClear Number of bytes to allocate for the file. * - * @return * * @exception LogException The allocation failed. * - * @see */ void allocFileStorage( int bytesToClear ) diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogHandle.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogHandle.java index 855eea0f09e..8723f40f611 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogHandle.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogHandle.java @@ -195,11 +195,9 @@ class LogHandle { * @param controlFH The handle of the control file. * @param upcall The log upcall. * - * @return * * @exception LogException The creation failed. * - * @see */ LogHandle( LogControl control, String logName, @@ -230,7 +228,6 @@ class LogHandle { * * @exception LogException The write failed. * - * @see */ synchronized LogLSN writeRecord( byte[] record, int recordType, @@ -584,7 +581,6 @@ synchronized LogLSN writeRecord( byte[] record, * * @exception LogException The read failed. * - * @see */ synchronized byte[] readRecord( LogLSN readLSN, int[/*1*/] type ) @@ -714,11 +710,9 @@ synchronized byte[] readRecord( LogLSN readLSN, * * @param buffer The record to be written. * - * @return * * @exception LogException The write failed. * - * @see */ synchronized void writeRestart( byte[] buffer ) throws LogException { @@ -807,13 +801,11 @@ synchronized void writeRestart( byte[] buffer ) /**Reads the restart record. * - * @param * * @return The record read in. * * @exception LogException The read failed. * - * @see */ synchronized byte[] readRestart() throws LogException { @@ -900,11 +892,9 @@ synchronized byte[] readRestart() * * @param deleteFile Indicates whether file should be deleted. * - * @return * * @exception LogException The close failed. * - * @see */ synchronized void closeFile( boolean deleteFile ) throws LogException { // Check BlockValid field in Log_FileDescriptor block and @@ -1013,11 +1003,9 @@ synchronized void closeFile( boolean deleteFile ) throws LogException { * @param truncLSN The LSN of the truncation point. * @param inclusive Indicates whether truncation includes the LSN. * - * @return * * @exception LogException The operation failed. * - * @see */ synchronized void truncate( LogLSN truncLSN, int inclusive ) @@ -1285,11 +1273,9 @@ synchronized void truncate( LogLSN truncLSN, * * @param chkLSN The last LSN which must be written. * - * @return * * @exception LogException The operation failed. * - * @see */ synchronized void checkLSN( LogLSN chkLSN ) throws LogException { @@ -1413,7 +1399,6 @@ synchronized void checkLSN( LogLSN chkLSN ) * * @exception LogException The browse was not possible. * - * @see */ synchronized LogCursor openCursor( LogLSN startLSN, LogLSN endLSN ) @@ -1457,11 +1442,9 @@ synchronized LogCursor openCursor( LogLSN startLSN, * * @param LogCursor The cursor to be closed. * - * @return * * @exception LogException The cursor could not be closed. * - * @see */ synchronized void closeCursor( LogCursor cursor ) throws LogException { @@ -1507,7 +1490,6 @@ synchronized void closeCursor( LogCursor cursor ) * * @exception LogException The operation failed. * - * @see */ LogExtent positionFilePointer( LogLSN currentLSN, int extra, @@ -1577,11 +1559,8 @@ LogExtent positionFilePointer( LogLSN currentLSN, *

    * This internal method does not need to be synchronized. * - * @param * - * @return * - * @see */ private void freeCushion() { // If the cushion file exists, remove it. @@ -1600,11 +1579,9 @@ private void freeCushion() { * * @param callUpcall Indicates whether the upcall should be called. * - * @return * * @exception LogException The operation failed. * - * @see */ void restoreCushion( boolean callUpcall ) throws LogException { @@ -1677,13 +1654,10 @@ void restoreCushion( boolean callUpcall ) /**Writes the control file. * This internal method does not need to be synchronized. * - * @param * - * @return * * @exception LogException The write failed. * - * @see */ void writeControlFile() throws LogException { @@ -1733,7 +1707,6 @@ void writeControlFile() throws LogException { * * @exception LogException The open failed. * - * @see */ LogExtent openExtent( int extent ) throws LogException { @@ -1770,11 +1743,9 @@ LogExtent openExtent( int extent ) throws LogException { * * @param tailLSN The point from which storage is not required. * - * @return * * @exception LogException The operation failed. * - * @see */ void freeFileStorage( LogLSN tailLSN ) throws LogException { @@ -1810,11 +1781,9 @@ void freeFileStorage( LogLSN tailLSN ) * @param restartNumber The restart number. * @param restartInfo An array which will contain the length and timestamp. * - * @return * * @exception LogException The operation failed. * - * @see */ static void checkRestart( LogFileHandle fileHandle, int restartNumber, @@ -1872,13 +1841,10 @@ static void checkRestart( LogFileHandle fileHandle, /**Dumps the state of the object. * - * @param * - * @return * * @exception LogException The operation failed. * - * @see */ void dump() throws LogException { /** @@ -1910,11 +1876,8 @@ void dump() throws LogException { /**Removes all extent information from the log file. * This internal method does not need to be synchronized. * - * @param * - * @return * - * @see */ void cleanUpExtents() { @@ -1934,7 +1897,6 @@ void cleanUpExtents() { * * @return The new restart number. * - * @see */ final static int alternateRestart( int restart) { @@ -1947,7 +1909,6 @@ final static int alternateRestart( int restart) { * * @return The restart position. * - * @see */ final static int restartPosition( int restart ) { return (restart == 1) ? RESTART_OFFSET_1 : RESTART_OFFSET_2; @@ -1955,11 +1916,9 @@ final static int restartPosition( int restart ) { /**Returns the log file name. * - * @param * * @return The log file name. * - * @see */ final String logFileName() { return logFileName; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogLSN.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogLSN.java index 2aa7b2eaf07..8baf17f7cfc 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogLSN.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogLSN.java @@ -40,7 +40,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- // CHANGE HISTORY @@ -69,11 +68,8 @@ class LogLSN implements Serializable { /**Default LogLSN constructor * - * @param * - * @return * - * @see */ LogLSN() { offset = 0; @@ -85,9 +81,7 @@ class LogLSN implements Serializable { * @param ext Extent for new LSN. * @param off Offset for new LSN. * - * @return * - * @see */ LogLSN( int ext, int off ) { @@ -99,9 +93,7 @@ class LogLSN implements Serializable { * * @param lsn Other LSN to be copied. * - * @return * - * @see */ LogLSN( LogLSN lsn ) { offset = lsn.offset; @@ -113,9 +105,7 @@ class LogLSN implements Serializable { * @param bytes The array of bytes from which the LogLSN is to be constructed. * @param index The index in the array where copy is to start. * - * @return * - * @see */ LogLSN( byte[] bytes, int index ) { @@ -131,11 +121,8 @@ class LogLSN implements Serializable { /**Determines whether the target LSN is NULL. * - * @param * - * @return * - * @see */ final boolean isNULL() { return offset == 0 && extent == 0; @@ -145,9 +132,7 @@ final boolean isNULL() { * * @param other The other LogLSN to be compared. * - * @return * - * @see */ final boolean equals( LogLSN other ) { return offset == other.offset && extent == other.extent; @@ -157,9 +142,7 @@ final boolean equals( LogLSN other ) { * * @param other The other LogLSN to be compared. * - * @return * - * @see */ final boolean lessThan( LogLSN other ) { return ( (offset < other.offset && extent == other.extent) || @@ -170,9 +153,7 @@ final boolean lessThan( LogLSN other ) { * * @param other The other LogLSN to be compared. * - * @return * - * @see */ final boolean greaterThan( LogLSN other ) { return ( (offset > other.offset && extent == other.extent) || @@ -183,9 +164,7 @@ final boolean greaterThan( LogLSN other ) { * * @param LogLSN The LSN to be copied. * - * @return * - * @see */ final void copy( LogLSN other ) { extent = other.extent; @@ -199,7 +178,6 @@ final void copy( LogLSN other ) { * * @return Number of bytes copied. * - * @see */ final int toBytes( byte[] bytes, int index ) { @@ -217,11 +195,9 @@ final int toBytes( byte[] bytes, /**This method is called to direct the object to format its state to a String. * - * @param * * @return The formatted representation of the object. * - * @see */ public final String toString() { return "LSN(ext="/*#Frozen*/+extent+",off="/*#Frozen*/+offset+")"/*#Frozen*/; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordEnding.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordEnding.java index 6b9335f25ef..41d6c78a22c 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordEnding.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordEnding.java @@ -58,11 +58,8 @@ class LogRecordEnding implements Serializable { /**Default LogRecordEnding constructor. * - * @param * - * @return * - * @see */ LogRecordEnding() { } @@ -72,9 +69,7 @@ class LogRecordEnding implements Serializable { * @param bytes The array of bytes from which the object is to be constructed. * @param index The index in the array where copy is to start. * - * @return * - * @see */ LogRecordEnding( byte[] bytes, int index ) { @@ -88,7 +83,6 @@ class LogRecordEnding implements Serializable { * * @return Number of bytes copied. * - * @see */ final int toBytes( byte[] bytes, int index ) { @@ -99,11 +93,9 @@ final int toBytes( byte[] bytes, /**This method is called to direct the object to format its state to a String. * - * @param * * @return The formatted representation of the object. * - * @see */ public final String toString() { return "LRE(curr="/*#Frozen*/+currentLSN+")"/*#Frozen*/; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordHeader.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordHeader.java index 79e85146a8c..77e81ade90e 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordHeader.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRecordHeader.java @@ -67,9 +67,7 @@ class LogRecordHeader implements Serializable { * be constructed. * @param index The index in the array where copy is to start. * - * @return * - * @see */ LogRecordHeader(byte[] bytes, int index) { recordType = (bytes[index++]&255) + @@ -92,9 +90,7 @@ class LogRecordHeader implements Serializable { * * @param other The object to be copied. * - * @return * - * @see */ void copy( LogRecordHeader other) { recordType = other.recordType; @@ -112,7 +108,6 @@ void copy( LogRecordHeader other) { * * @return Number of bytes copied. * - * @see */ final int toBytes(byte[] bytes, int index) { bytes[index++] = (byte) recordType; @@ -134,11 +129,9 @@ final int toBytes(byte[] bytes, int index) { * This method is called to direct the object to format its state * to a String. * - * @param * * @return The formatted representation of the object. * - * @see */ public final String toString() { return "LRH(type="/*#Frozen*/ + recordType + ",curr="/*#Frozen*/ + currentLSN + diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRestartDescriptor.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRestartDescriptor.java index 1e237962b2a..c878efd8d96 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRestartDescriptor.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogRestartDescriptor.java @@ -54,11 +54,8 @@ class LogRestartDescriptor implements Serializable { /** * Default LogRestartDescriptor constructor. * - * @param * - * @return * - * @see */ LogRestartDescriptor() {} @@ -69,9 +66,7 @@ class LogRestartDescriptor implements Serializable { * to be constructed. * @param index The index in the array where copy is to start. * - * @return * - * @see */ LogRestartDescriptor(byte[] bytes, int index) { restartValid = (bytes[index++]&255) + @@ -98,7 +93,6 @@ class LogRestartDescriptor implements Serializable { * * @return Number of bytes copied. * - * @see */ final int toBytes(byte[] bytes, int index) { bytes[index++] = (byte) restartValid; @@ -124,7 +118,6 @@ final int toBytes(byte[] bytes, int index) { * * @return Indicates whether the objects are equal. * - * @see */ final boolean equals(LogRestartDescriptor other) { return (restartValid == other.restartValid && @@ -136,11 +129,9 @@ final boolean equals(LogRestartDescriptor other) { * This method is called to direct the object to format its state * to a String. * - * @param * * @return The formatted representation of the object. * - * @see */ public final String toString() { return "LRD(valid="/*#Frozen*/ + restartValid + diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogUpcallTarget.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogUpcallTarget.java index 602790dee6b..ba17b640938 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogUpcallTarget.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogUpcallTarget.java @@ -39,7 +39,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ interface LogUpcallTarget { @@ -47,11 +46,8 @@ interface LogUpcallTarget { /** * This is the upcall which is called by the log file. * - * @param * - * @return * - * @see */ void upcall(int reason); } diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogicErrorException.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogicErrorException.java index 7e3fbeeb93c..645be58a63e 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogicErrorException.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/LogicErrorException.java @@ -38,7 +38,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -57,9 +56,7 @@ class LogicErrorException extends Exception { * * @param reason The reason identifier. * - * @return * - * @see */ LogicErrorException(String reason) { super(); @@ -68,11 +65,9 @@ class LogicErrorException extends Exception { /** * Converts the LogicErrorException to a string. * - * @param * * @return The string representation. * - * @see */ public String toString() { return super.toString() + ", reason("/*#Frozen*/ + reason + ")"/*#Frozen*/; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages.java index 9d043307550..70c802c4fdc 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages.java @@ -41,7 +41,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages_en_US.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages_en_US.java index 58385ed562b..c7f4eb1cb99 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages_en_US.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/Messages_en_US.java @@ -39,7 +39,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/MinorCode.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/MinorCode.java index ceeae175ee3..9a7496745a8 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/MinorCode.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/MinorCode.java @@ -38,7 +38,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ public interface MinorCode { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/NestingInfo.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/NestingInfo.java index 250634993cc..5d5245e1e0b 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/NestingInfo.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/NestingInfo.java @@ -49,7 +49,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ class NestingInfo { CoordinatorImpl[] ancestorSeq = null; @@ -59,11 +58,8 @@ class NestingInfo { /** * Default NestingInfo constructor. * - * @param * - * @return * - * @see */ NestingInfo() {} @@ -73,16 +69,14 @@ class NestingInfo { * * @param ancestors The ancestors * - * @return * - * @see */ NestingInfo(CoordinatorImpl[] ancestors) { // If the sequence of ancestors is empty, set the removed flag as this // NestingInfo is part of a top-level transaction. - ancestorSeq = (CoordinatorImpl[])ancestors.clone(); + ancestorSeq = ancestors.clone(); removed = (ancestors.length == 0); } @@ -95,12 +89,13 @@ class NestingInfo { * * @return Indicates success of the operation. * - * @see */ boolean addChild(CoordinatorImpl child) { boolean result = !childSet.contains(child); - if( result ) childSet.addElement(child); + if( result ) { + childSet.addElement(child); + } return result; } @@ -114,7 +109,6 @@ boolean addChild(CoordinatorImpl child) { * * @return Indicates success of the operation. * - * @see */ boolean removeChild(CoordinatorImpl child) { boolean result = childSet.removeElement(child); @@ -124,11 +118,8 @@ boolean removeChild(CoordinatorImpl child) { /** * Empties the set of children. * - * @param * - * @return * - * @see */ void empty() { childSet.removeAllElements(); @@ -144,7 +135,6 @@ void empty() { * * @return Indicates success of the operation. * - * @see */ boolean removeFromParent(CoordinatorImpl child) { @@ -178,7 +168,6 @@ boolean removeFromParent(CoordinatorImpl child) { * * @return The parent Coordinator. * - * @see */ CoordinatorImpl getParent(boolean forgetting) { @@ -187,13 +176,16 @@ CoordinatorImpl getParent(boolean forgetting) { // If there are no ancestors, there is no parent, // otherwise return the first ancestor. - if (ancestorSeq.length != 0) + if (ancestorSeq.length != 0) { result = ancestorSeq[0]; + } // If the Coordinator is being cleaned up, then we must not // call the parent when the child calls removeFromParent. - if( forgetting ) removed = true; + if( forgetting ) { + removed = true; + } return result; } @@ -206,11 +198,9 @@ CoordinatorImpl getParent(boolean forgetting) { *

    * The top-level Coordinator is the last in the sequence of ancestors. * - * @param * * @return The top-level ancestor. * - * @see */ CoordinatorImpl getTopLevel() { @@ -219,8 +209,9 @@ CoordinatorImpl getTopLevel() { // If there are no ancestors, there is no top-level, // otherwise return the last ancestor. - if( ancestorSeq.length != 0 ) + if( ancestorSeq.length != 0 ) { result = ancestorSeq[ancestorSeq.length - 1]; + } return result; } @@ -233,11 +224,8 @@ CoordinatorImpl getTopLevel() { *

    * The caller is responsible for freeing the sequence storage. * - * @param - * * @return The sequence of ancestors. * - * @see */ CoordinatorImpl[] getAncestors() { @@ -247,7 +235,7 @@ CoordinatorImpl[] getAncestors() { // If we cannot obtain a buffer to copy the sequence, return // empty sequence Perhaps an exception should be raised instead ? - result = (CoordinatorImpl[]) ancestorSeq.clone(); + result = ancestorSeq.clone(); return result; } @@ -257,11 +245,9 @@ CoordinatorImpl[] getAncestors() { *

    * If no nesting information has been defined, the operation returns 0. * - * @param * * @return The number of children. * - * @see */ int numChildren() { return childSet.size(); @@ -277,11 +263,9 @@ int numChildren() { * these represent parts of a transaction that may not be * committed or rolled back before the parent completes. * - * @param * * @return Indicates if all is OK. * - * @see */ boolean replyCheck() { @@ -308,7 +292,6 @@ boolean replyCheck() { * * @return Indicates success of the operation. * - * @see */ boolean isDescendant(Coordinator other) { @@ -332,11 +315,8 @@ boolean isDescendant(Coordinator other) { * Rolls back all children in the set; if there are none the operation does * nothing. * - * @param * - * @return * - * @see */ void rollbackFamily() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ProxyChecker.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ProxyChecker.java index b8a1a60823a..ea794e47f47 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ProxyChecker.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/ProxyChecker.java @@ -38,7 +38,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ interface ProxyChecker { @@ -49,7 +48,6 @@ interface ProxyChecker { * * @return Indicates whether the object is a proxy. * - * @see */ boolean isProxy(org.omg.CORBA.Object obj); } diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryCoordinatorImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryCoordinatorImpl.java index bd9ff1a6840..16d92dfebed 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryCoordinatorImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryCoordinatorImpl.java @@ -61,7 +61,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -100,9 +99,7 @@ class RecoveryCoordinatorImpl extends RecoveryCoordinatorPOA { * @param globalTID The global transaction identifier. * @param sequence An internal sequence number to differentiate objects. * - * @return * - * @see */ RecoveryCoordinatorImpl(GlobalTID globalTID, int sequence) { @@ -137,7 +134,6 @@ class RecoveryCoordinatorImpl extends RecoveryCoordinatorPOA { * @exception NotPrepared The transaction for which the * RecoveryCoordinator was created has not prepared. * - * @see */ public Status replay_completion(Resource res) throws NotPrepared { @@ -377,9 +373,7 @@ public Status replay_completion(Resource res, String logPath) throws NotPrepared * * @param res The Resource to be rolled back. * - * @return * - * @see */ void rollbackOrphan(Resource res) { @@ -417,9 +411,7 @@ void rollbackOrphan(Resource res) { * * @param key The key for the object. * - * @return * - * @see */ RecoveryCoordinatorImpl(byte[] key) { @@ -445,11 +437,9 @@ void rollbackOrphan(Resource res) { /** * Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ synchronized final RecoveryCoordinator object() { @@ -502,11 +492,8 @@ synchronized final RecoveryCoordinator object() { /** * Destroys the RecoveryCoordinatorImpl object. * - * @param * - * @return * - * @see */ synchronized final void destroy() { @@ -555,7 +542,6 @@ synchronized final void destroy() { * * @author Simon Holdsworth, IBM Corporation * - * @see */ class OrphanRollbackThread extends Thread { Resource resource = null; @@ -567,9 +553,7 @@ class OrphanRollbackThread extends Thread { * @param recovery * @param resource * - * @return * - * @see */ OrphanRollbackThread(RecoveryCoordinatorImpl recovery, Resource resource) { @@ -581,11 +565,8 @@ class OrphanRollbackThread extends Thread { /** * Calls the RecoveryCoordinator to rollback the Resource. * - * @param * - * @return * - * @see */ public void run() { recovery.rollbackOrphan(resource); diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryManager.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryManager.java index 4d7c1803c5d..157113d89bd 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryManager.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RecoveryManager.java @@ -66,7 +66,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -149,11 +148,8 @@ public class RecoveryManager { /** * Initialises the static state of the RecoveryManager class. * - * @param * - * @return * - * @see */ static void initialise() { @@ -219,7 +215,6 @@ static void initialise() { * * @return Indicates success of the operation. * - * @see */ static boolean addCoordinator(GlobalTID globalTID, Long localTID, CoordinatorImpl coord, int timeout) { @@ -259,7 +254,6 @@ static boolean addCoordinator(GlobalTID globalTID, * * @return Indicates success of the operation. * - * @see */ static boolean removeCoordinator(GlobalTID globalTID, Long localTID, boolean aborted) { boolean result = false; @@ -345,7 +339,6 @@ static boolean removeCoordinator(GlobalTID globalTID, Long localTID, boolean abo * * @return The Coordinator for the transaction. * - * @see */ static CoordinatorImpl getCoordinator(GlobalTID globalTID) { @@ -406,11 +399,9 @@ static Thread removeFromTxMap(GlobalTID tid) { *

    * The method returns true if any transactions require resync. * - * @param * * @return Indicates that there are Coordinators requiring resync. * - * @see */ static boolean recover() { @@ -490,11 +481,8 @@ static boolean recover() { * Once resync is complete, a keypoint is taken to indicate that the log * information is no longer required. * - * @param * - * @return * - * @see */ static void resync() { @@ -636,11 +624,9 @@ static void resync() { * @param resynced Indicates whether any resync was done. * @param keypointRequired Indicates whether the log needs keypointing. * - * @return * * @exception LogicErrorException An internal logic error occurred. * - * @see */ static void resyncComplete(boolean resynced, boolean keypointRequired) throws LogicErrorException { // Inform JTSXA that resync is complete, and trace the fact @@ -671,7 +657,6 @@ static void resyncComplete(boolean resynced, boolean keypointRequired) throws Lo * * @return The Coordinator object. * - * @see */ static CoordinatorImpl getLocalCoordinator(Long localTID) { return (CoordinatorImpl) coordsByLocalTID.get(localTID); @@ -685,7 +670,6 @@ static CoordinatorImpl getLocalCoordinator(Long localTID) { * * @return Indicates the local transaction identifier is valid. * - * @see */ static boolean validLocalTID(Long localTID) { return coordsByLocalTID.containsKey(localTID); @@ -702,9 +686,7 @@ static boolean validLocalTID(Long localTID) { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ static void shutdown(boolean immediate) { @@ -1246,11 +1228,8 @@ static void dbXARecovery(String serverName, Enumeration xaResources) { * outcomes. These are registered with appropriate Coordinators or rolled * back as appropriate. * - * @param * - * @return * - * @see */ /* * DISCARD(Ram J) - this method is not needed anymore. This has been @@ -1306,11 +1285,9 @@ private static void recoverXA() { /** * Returns an array of Coordinator objects currently active. * - * @param * * @return The array of Coordinators. * - * @see */ static CoordinatorImpl[] getCoordinators() { @@ -1336,11 +1313,9 @@ static CoordinatorImpl[] getCoordinators() { /** * Gets the restart data for the process. * - * @param * * @return The restart data. * - * @see */ public static byte[] getRestart() { @@ -1357,9 +1332,7 @@ public static byte[] getRestart() { * * @param bytes The restart data. * - * @return * - * @see */ public static void setRestart(byte[] bytes) { @@ -1375,11 +1348,8 @@ public static void setRestart(byte[] bytes) { /** * Waits for recovery to complete. * - * @param * - * @return * - * @see */ public static void waitForRecovery() { try { @@ -1394,9 +1364,7 @@ public static void waitForRecovery() { /** * Waits for the resync between the resource and the transaction manager to complete with timeout. * - * @return * - * @see */ public static void waitForResyncWithTimeout() { final EventSemaphore semaphore = resyncInProgress; @@ -1416,11 +1384,8 @@ public static void waitForResyncWithTimeout() { /** * Waits for resync to complete. * - * @param * - * @return * - * @see */ public static void waitForResync() { @@ -1701,9 +1666,7 @@ public static void startResyncThread() { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ /* static void report() { @@ -1807,7 +1770,6 @@ public void lowerFence() { * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -1822,11 +1784,8 @@ class ResyncThread extends Thread { /** * ResyncThread constructor. * - * @param * - * @return * - * @see */ static Logger _logger = LogDomains.getLogger(ResyncThread.class, LogDomains.TRANSACTION_LOGGER); @@ -1838,11 +1797,8 @@ class ResyncThread extends Thread { /** * Performs resync. * - * @param * - * @return * - * @see */ @Override public void run() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredResources.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredResources.java index 3ad12931a14..5a3fa90e2de 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredResources.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredResources.java @@ -72,7 +72,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -129,9 +128,7 @@ class RegisteredResources { * * @param log The CoordinatorLog object for the transaction. * - * @return * - * @see */ RegisteredResources(CoordinatorLog log, CoordinatorImpl coord) { @@ -158,11 +155,8 @@ class RegisteredResources { /** * Default RegisteredResources constructor. * - * @param * - * @return * - * @see */ RegisteredResources(CoordinatorImpl coord) { this.coord = coord;} @@ -174,9 +168,7 @@ class RegisteredResources { * * @param log The CoordinatorLog holding the RegisteredResources state. * - * @return * - * @see */ void reconstruct(CoordinatorLog log) { @@ -338,7 +330,6 @@ void reconstruct(CoordinatorLog log) { * * @return The number of registered Resource objects. * - * @see */ int addRes(Resource obj) { @@ -361,11 +352,8 @@ int addRes(Resource obj) { /** * Empties the list of registered Resources. * - * @param * - * @return * - * @see */ /* void empty() { @@ -383,11 +371,9 @@ void empty() { *

    * If there are, the operation returns true, otherwise false. * - * @param * * @return Indicates whether any Resources registered. * - * @see */ boolean involved() { @@ -399,11 +385,9 @@ boolean involved() { /** * Returns the number of Resources currently in the list. * - * @param * * @return The number of registered Resources. * - * @see */ int numRegistered() { @@ -419,7 +403,6 @@ int numRegistered() { * All Resources that return VoteReadOnly have their state set to * completed. The consolidated result is returned. * - * @param * * @return The vote for the transaction. * @@ -430,7 +413,6 @@ int numRegistered() { * roll the transaction back, but one or more others may have * already heuristically committed. * - * @see */ Vote distributePrepare() throws HeuristicMixed, HeuristicHazard { Vote result = Vote.VoteReadOnly; @@ -644,7 +626,6 @@ Resource getLAOResource() { * their state is set to completed, and the CoordinatorLog object * is forced to the physical log. * - * @param * * @exception HeuristicMixed Indicates that heuristic decisions have been * taken which have resulted in part of the transaction @@ -653,7 +634,6 @@ Resource getLAOResource() { * been taken which have resulted in part of the transaction * being rolled back. * - * @see */ void distributeCommit() throws HeuristicMixed, HeuristicHazard, NotPrepared { boolean infiniteRetry = true; @@ -910,7 +890,6 @@ void distributeCommit() throws HeuristicMixed, HeuristicHazard, NotPrepared { * already been thrown for this transaction, and that forget * processing should proceed. * - * @return * * @exception HeuristicMixed Indicates that heuristic decisions have been * taken which have resulted in part of the transaction @@ -919,7 +898,6 @@ void distributeCommit() throws HeuristicMixed, HeuristicHazard, NotPrepared { * may have been taken which have resulted in part of the transaction * being rolled back. * - * @see */ void distributeRollback(boolean heuristicException) throws HeuristicMixed, HeuristicHazard { @@ -1153,7 +1131,6 @@ void distributeRollback(boolean heuristicException) * @param retries The number of times to retry the forget operation. * @param infinite indicates infinite retry. * - * @return * * @exception HeuristicMixed Indicates that heuristic decisions have been * taken which have resulted in part of the transaction @@ -1162,7 +1139,6 @@ void distributeRollback(boolean heuristicException) * been taken which have resulted in part of the transaction being * rolled back. * - * @see */ private void distributeForget(int retries, boolean infinite, boolean heuristicHazard, boolean heuristicMixed) throws HeuristicMixed, HeuristicHazard { @@ -1279,13 +1255,11 @@ private void distributeForget(int retries, boolean infinite, * * @param parent The parent's Coordinator reference. * - * @return * * @exception TRANSACTION_ROLLEDBACK The subtransaction could not be * committed. Some participants may have committed and some may have * rolled back. * - * @see */ void distributeSubcommit(Coordinator parent) throws TRANSACTION_ROLLEDBACK { @@ -1344,11 +1318,8 @@ void distributeSubcommit(Coordinator parent) throws TRANSACTION_ROLLEDBACK { * Distributes rollbackSubtransaction messages to all registered * SubtransactionAwareResources. * - * @param * - * @return * - * @see */ void distributeSubrollback() { // Browse through the participants, rolling them back. The following is @@ -1390,9 +1361,7 @@ void distributeSubrollback() { * @param resources The object to hold the objects. * @param states The object to hold the states. * - * @return * - * @see */ /* COMMENT(Ram J) - we do not support Admin package anymore. void getResources(ResourceSequenceHolder resources, @@ -1413,7 +1382,6 @@ void getResources(ResourceSequenceHolder resources, * * @return void * - * @see */ void commitOnePhase() throws HeuristicMixed, HeuristicHazard { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredStatics.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredStatics.java index b6f9ceaf2b3..699a287bfcf 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredStatics.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredStatics.java @@ -44,7 +44,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //--------------------------------------------------------------------------- @@ -61,11 +60,8 @@ class RegisteredStatics { /** * Default RegisteredStatics constructor. * - * @param * - * @return * - * @see */ RegisteredStatics() {} @@ -80,9 +76,7 @@ class RegisteredStatics { * @param control The transaction whose association has started. * @param begin Indicates if this is a begin rather than a resume. * - * @return * - * @see */ void distributeStart(ControlImpl control, boolean begin) { @@ -137,9 +131,7 @@ void distributeStart(ControlImpl control, boolean begin) { * @param complete Indicates that this is a commit/rollback rather than a * suspend. * - * @return * - * @see */ void distributeEnd(ControlImpl control, boolean complete) { @@ -175,9 +167,7 @@ void distributeEnd(ControlImpl control, boolean complete) { * * @param obj The StaticResource to be added. * - * @return * - * @see */ void addStatic(StaticResource obj) { @@ -210,7 +200,6 @@ void addStatic(StaticResource obj) { * * @return Indicates success of the operation. * - * @see */ boolean removeStatic(StaticResource obj) { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredSyncs.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredSyncs.java index d6e58aec008..40ee10f63ad 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredSyncs.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/RegisteredSyncs.java @@ -52,7 +52,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -74,11 +73,8 @@ class RegisteredSyncs { /** * Default RegisteredSyncs constructor. * - * @param * - * @return * - * @see */ RegisteredSyncs() {} @@ -88,11 +84,9 @@ class RegisteredSyncs { *

    * Returns a boolean to indicate success/failure. * - * @param * * @return Indicates success of the operation. * - * @see */ boolean distributeBefore() { @@ -131,9 +125,7 @@ boolean distributeBefore() { * * @param status Indicates whether the transaction committed. * - * @return * - * @see */ void distributeAfter(Status status) { @@ -192,9 +184,7 @@ void distributeAfter(Status status) { * * @param obj The Synchronization object to be added. * - * @return * - * @see */ void addSync(Synchronization obj) { registered.addElement(obj); @@ -203,11 +193,8 @@ void addSync(Synchronization obj) { /** * Empties the set of registered Synchronization objects. * - * @param * - * @return * - * @see */ void empty() { registered.removeAllElements(); @@ -218,11 +205,9 @@ void empty() { *

    * If there are, the operation returns true, otherwise false. * - * @param * * @return Indicates whether any objects are registered. * - * @see */ boolean involved() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SenderReceiver.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SenderReceiver.java index 878b71b6c6a..d4a5f122723 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SenderReceiver.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SenderReceiver.java @@ -59,7 +59,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -80,11 +79,8 @@ class SenderReceiver implements Sender, Receiver { /** * Default constructor. * - * @param * - * @return * - * @see */ SenderReceiver() {} @@ -94,14 +90,12 @@ class SenderReceiver implements Sender, Receiver { * @param id The request identifier. * @param holder The completed context object. * - * @return * * @exception TRANSACTION_ROLLEDBACK The current transaction * has been rolled back. The message should not be sent and * TRANSACTION_ROLLEDBACK should be returned to the caller. * @exception TRANSACTION_REQUIRED There is no current transaction. * - * @see */ @Override public void sending_request(int id, PropagationContextHolder holder) @@ -133,12 +127,10 @@ public void sending_request(int id, PropagationContextHolder holder) * @param context The PropagationContext from the message. * @param ex The exception on the message. * - * @return * * @exception WrongTransaction The context returned on the reply is for a * different transaction from the current one on the thread. * - * @see */ @Override public void received_reply(int id, PropagationContext context, @@ -170,9 +162,7 @@ public void received_reply(int id, PropagationContext context, * @param id The request identifier. * @param context The PropagationContext from the message. * - * @return * - * @see */ @Override public void received_request(int id, PropagationContext context) { @@ -202,7 +192,6 @@ public void received_request(int id, PropagationContext context) { * @param id The request identifier. * @param holder The context to be returned on the reply. * - * @return * * @exception INVALID_TRANSACTION The current transaction has * outstanding work on this reply, and has been marked rollback-only, @@ -211,7 +200,6 @@ public void received_request(int id, PropagationContext context) { * @exception TRANSACTION_ROLLEDBACK The current transaction has * already been rolled back. * - * @see */ @Override public void sending_reply(int id, PropagationContextHolder holder) @@ -240,9 +228,7 @@ public void sending_reply(int id, PropagationContextHolder holder) * * @param ident The TSIdentification object. * - * @return * - * @see */ static void identify(TSIdentification ident) { try { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/StaticResource.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/StaticResource.java index 2b128a84fa5..1f85ef3aa66 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/StaticResource.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/StaticResource.java @@ -43,7 +43,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -66,9 +65,7 @@ public abstract class StaticResource { * @param coord The transaction whose association is starting. * @param begin Indicates a begin rather than a resume. * - * @return * - * @see */ public abstract void startAssociation(Coordinator coord, boolean begin); @@ -83,9 +80,7 @@ public abstract class StaticResource { * @param coord The transaction whose association is starting. * @param complete Indicates a commit/rollback rather than a suspend. * - * @return * - * @see */ public abstract void endAssociation(Coordinator coord, boolean complete); @@ -95,11 +90,8 @@ public abstract class StaticResource { * Until this method is called, the StaticResource object will not receive * calls to start/endAssociation. * - * @param * - * @return * - * @see */ protected void register() { CurrentTransaction.registerStatic(this); diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SubCoordinator.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SubCoordinator.java index 837e3fd305a..3cd3e40365c 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SubCoordinator.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SubCoordinator.java @@ -78,7 +78,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -115,11 +114,9 @@ class SubCoordinator extends CoordinatorImpl { * @param parentLocalTID The parent's local transaction identifier. * @param ancestors This transactions's ancestors (includes parent). * - * @return * * @exception LogicErrorException An internal logic error occurred. * - * @see */ SubCoordinator(GlobalTID parentGlobalTID, Long parentLocalTID, CoordinatorImpl[] ancestors) throws LogicErrorException { @@ -189,9 +186,7 @@ class SubCoordinator extends CoordinatorImpl { * @param superior The superior Coordinator. * @param temporary The temporary flag. * @param ancestors The ancestors of the transaction. - * @return * @exception LogicErrorException An internal logic error occurred. - * @see */ SubCoordinator(GlobalTID globalTID, Coordinator superior, boolean temporary, CoordinatorImpl[] ancestors) @@ -253,12 +248,10 @@ class SubCoordinator extends CoordinatorImpl { /** * Cleans up the state of the object. * - * @param * - * @return * - * @see */ + @Override public void doFinalize() { // Set the flag to indicate that the coordinator is being destroyed. @@ -310,12 +303,11 @@ public void doFinalize() { /** * Returns the local status of the target transaction. * - * @param * * @return The status of the transaction. * - * @see */ + @Override synchronized public Status get_status() { Status result = Status.StatusUnknown; @@ -385,14 +377,13 @@ synchronized public Status get_status() { * This operation references no instance variables and so can be * implemented locally in the proxy class. * - * @param * * @return The parent transaction's status. * * @exception SystemException The parent could not be reached. * - * @see */ + @Override synchronized public Status get_parent_status() throws SystemException { Status result = Status.StatusNoTransaction; @@ -418,14 +409,13 @@ synchronized public Status get_parent_status() throws SystemException { * This operation references no instance variables and so can be * implemented locally in a proxy class. * - * @param * * @return The top-level transaction status. * * @exception SystemException The top-level ancestor could not be reached. * - * @see */ + @Override synchronized public Status get_top_level_status() throws SystemException { // Return the top-level status. If there is none, this is an error; @@ -462,8 +452,8 @@ synchronized public Status get_top_level_status() throws SystemException { * * @exception SystemException The other Coordinator could not be reached. * - * @see */ + @Override synchronized public boolean is_same_transaction(Coordinator other) throws SystemException { @@ -496,8 +486,8 @@ synchronized public boolean is_same_transaction(Coordinator other) * * @exception SystemException The other Coordinator could not be reached. * - * @see */ + @Override synchronized public boolean is_related_transaction(Coordinator other) throws SystemException { @@ -530,8 +520,8 @@ synchronized public boolean is_related_transaction(Coordinator other) * * @exception SystemException The other Coordinator could not be reached. * - * @see */ + @Override public boolean is_ancestor_transaction(Coordinator other) throws SystemException { @@ -558,8 +548,8 @@ public boolean is_ancestor_transaction(Coordinator other) * * @exception SystemException The other Coordinator could not be reached. * - * @see */ + @Override synchronized public boolean is_descendant_transaction(Coordinator other) throws SystemException { @@ -592,12 +582,11 @@ synchronized public boolean is_descendant_transaction(Coordinator other) * This operation references no instance variables and so can be * implemented locally in a proxy class. * - * @param * * @return Indicates the transaction is top-level. * - * @see */ + @Override public boolean is_top_level_transaction() { boolean result = false; @@ -613,12 +602,11 @@ public boolean is_top_level_transaction() { * Returns a hash value based on the transaction associated with the target * object. * - * @param * * @return The hash value for the transaction. * - * @see */ + @Override synchronized public int hash_transaction() { int result = hash; @@ -635,14 +623,13 @@ synchronized public int hash_transaction() { * Returns a hash value based on the top-level ancestor of the transaction * associated with the target object. * - * @param * * @return The hash value for the top-level ancestor. * * @exception SystemException The other Coordinator could not be reached. * - * @see */ + @Override synchronized public int hash_top_level_tran() throws SystemException { int result = 0; @@ -679,9 +666,8 @@ synchronized public int hash_top_level_tran() throws SystemException { * represents has already been rolled back, or been marked * rollback-only. * @exception SystemException The operation failed. - * - * @see */ + @Override synchronized public RecoveryCoordinator register_resource(Resource res) throws SystemException, Inactive, TRANSACTION_ROLLEDBACK { @@ -808,7 +794,6 @@ synchronized public RecoveryCoordinator register_resource(Resource res) * * @param sares The SubtransactionAwareResource to be registered. * - * @return * * @exception Inactive The Coordinator is completing the transaction and * cannot accept this registration. @@ -817,8 +802,8 @@ synchronized public RecoveryCoordinator register_resource(Resource res) * rollback-only. * @exception SystemException The operation failed. * - * @see */ + @Override synchronized public void register_subtran_aware(SubtransactionAwareResource sares) throws SystemException, Inactive, TRANSACTION_ROLLEDBACK { // First check the state of the transaction. If it is not active, @@ -904,14 +889,12 @@ synchronized public void register_subtran_aware(SubtransactionAwareResource sare * Ensures that the transaction represented by the target SubCoordinator * cannot be committed. * - * @param * - * @return * * @exception Inactive The Coordinator is already completing the * transaction. - * @see */ + @Override synchronized public void rollback_only() throws Inactive { if (tranState.state != TransactionState.STATE_ACTIVE) { @@ -928,12 +911,11 @@ synchronized public void rollback_only() throws Inactive { * This operation references only the global TID, and so can be * implemented locally in a proxy class. * - * @param * * @return The transaction name. * - * @see */ + @Override synchronized public String get_transaction_name() { String result = null; @@ -951,15 +933,14 @@ synchronized public String get_transaction_name() { * Creates a subtransaction and returns a Control object that * represents the child transaction. * - * @param * * @return The Control object for the new child transaction. * * @exception Inactive The Coordinator is completing the * subtransaction and cannot create a new child. * - * @see */ + @Override synchronized public Control create_subtransaction() throws Inactive { Control result = null; @@ -1028,12 +1009,11 @@ synchronized public Control create_subtransaction() throws Inactive { * deadlock in resync. I don't think this is a problem as the global * identifier is allocated in the constructor and then never changes. * - * @param * * @return The global identifier for the transaction. * - * @see */ + @Override public otid_t getGlobalTID() { otid_t result = null; @@ -1047,12 +1027,11 @@ public otid_t getGlobalTID() { * This method is currently not synchronized because that causes a deadlock * in resync. * - * @param * * @return The local transaction identifier. * - * @see */ + @Override public long getLocalTID() { long result = superInfo.localTID.longValue(); @@ -1075,8 +1054,8 @@ public long getLocalTID() { * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ + @Override synchronized CoordinatorImpl replyAction(int[/* 1 */] action) throws SystemException { CoordinatorImpl result = null; action[0] = CoordinatorImpl.doNothing; @@ -1126,12 +1105,11 @@ synchronized CoordinatorImpl replyAction(int[/* 1 */] action) throws SystemExcep /** * Marks the SubCoordinator as permanent. * - * @param * * @return The local transaction identifier. * - * @see */ + @Override synchronized Long setPermanent() { Long result = superInfo.localTID; @@ -1143,12 +1121,11 @@ synchronized Long setPermanent() { /** * Checks whether the SubCoordinator is marked rollback-only. * - * @param * * @return Indicates whether the transaction is rollback-only. * - * @see */ + @Override synchronized public boolean isRollbackOnly() { boolean result = rollbackOnly; @@ -1158,12 +1135,11 @@ synchronized public boolean isRollbackOnly() { /** * Checks whether the SubCoordinator is active. * - * @param * * @return Indicates the transaction is active. * - * @see */ + @Override synchronized boolean isActive() { boolean result = (tranState.state == TransactionState.STATE_ACTIVE); @@ -1173,12 +1149,11 @@ synchronized boolean isActive() { /** * Checks whether the SubCoordinator has registered with its superior. * - * @param * * @return Indicates the registration status. * - * @see */ + @Override synchronized boolean hasRegistered() { boolean result = registered; @@ -1188,12 +1163,11 @@ synchronized boolean hasRegistered() { /** * Returns the sequence of ancestors of the transaction. * - * @param * * @return The sequence of ancestors. * - * @see */ + @Override synchronized public TransIdentity[] getAncestors() { CoordinatorImpl[] coords = nestingInfo.getAncestors(); @@ -1217,8 +1191,8 @@ synchronized public TransIdentity[] getAncestors() { * * @return Indicates success of the operation. * - * @see */ + @Override synchronized boolean addChild(CoordinatorImpl child) { boolean result = nestingInfo.addChild(child); @@ -1235,8 +1209,8 @@ synchronized boolean addChild(CoordinatorImpl child) { * * @return Indicates success of the operation. * - * @see */ + @Override synchronized boolean removeChild(CoordinatorImpl child) { boolean result = false; @@ -1273,17 +1247,16 @@ synchronized boolean removeChild(CoordinatorImpl child) { * The SubCoordinator checks that the subtransaction can be committed. * It does not distribute prepare operations to the participants. * - * @param * * @return The consolidated vote. * * @exception INVALID_TRANSACTION The transaction is not in a * state to commit, due to outstanding work. * - * @see */ static String[] resultName = { "Commit"/*#Frozen*/, "Rollback"/*#Frozen*/, "Read-only"/*#Frozen*/ }; + @Override synchronized Vote prepare() throws INVALID_TRANSACTION { Vote result = Vote.VoteRollback; @@ -1337,12 +1310,10 @@ synchronized Vote prepare() throws INVALID_TRANSACTION { * Directs the SubCoordinator to commit the transaction. * The SubCoordinator directs all registered Resources to commit. * - * @param * - * @return * - * @see */ + @Override void commit() { Coordinator parent = null; @@ -1440,10 +1411,9 @@ void commit() { * * @param force * - * @return * - * @see */ + @Override void rollback(boolean force) { // Until we actually distribute rollback flows, synchronize the method. @@ -1555,15 +1525,14 @@ void rollback(boolean force) { * * @param sync The Synchronization object to be registered. * - * @return * * @exception Inactive The Coordinator is in the process of completing the * transaction and cannot accept this registration. * @exception SynchronizationUnavailable The transaction service * cannot support synchronization. * - * @see */ + @Override synchronized public void register_synchronization(Synchronization sync) throws Inactive, SynchronizationUnavailable { // First check the state of the transaction. If it is not active, @@ -1591,10 +1560,9 @@ synchronized public void register_synchronization(Synchronization sync) * @param term The object normally responsible for terminating the * Coordinator. * - * @return * - * @see */ + @Override synchronized void setTerminator(CompletionHandler term) { terminator = term; } @@ -1602,12 +1570,11 @@ synchronized void setTerminator(CompletionHandler term) { /** * Gets the parent coordinator of the transaction. * - * @param * * @return The parent Coordinator * - * @see */ + @Override Coordinator getParent() { Coordinator result = nestingInfo.getParent(false).object(); return result; @@ -1616,12 +1583,11 @@ Coordinator getParent() { /** * Gets the superior Coordinator for this transaction. * - * @param * * @return The superior Coordinator * - * @see */ + @Override Coordinator getSuperior() { Coordinator result = superInfo.superior; return result; @@ -1633,9 +1599,7 @@ Coordinator getSuperior() { * @param resources The object which will contain the Resources * @param states The object which will contain the states. * - * @return * - * @see */ /* COMMENT(Ram J) only Admin package needs this. public void getResources(ResourceSequenceHolder resources, @@ -1662,13 +1626,12 @@ public void getResources(ResourceSequenceHolder resources, /** * Gets the object normally responsible for terminating this Coordinator. * - * @param * * @return The object normally responsible for terminating * the Coordinator. * - * @see */ + @Override CompletionHandler getTerminator() { CompletionHandler result = terminator; return result; @@ -1680,15 +1643,14 @@ CompletionHandler getTerminator() { * Creates a PropagationContext which contains the information which would * normally be passed implicitly via the CosTSPropagation interfaces. * - * @param * * @return The transaction context. * * @exception Inactive The Coordinator is in the process of completing the * transaction and cannot return the information. * - * @see */ + @Override synchronized public PropagationContext get_txcontext() throws Unavailable { // First check the state of the transaction. If it is not active, @@ -1744,10 +1706,9 @@ synchronized public PropagationContext get_txcontext() throws Unavailable { * * @param parent The parent Coordinator, if any. * - * @return * - * @see */ + @Override void cleanUpEmpty(CoordinatorImpl parent) { // Roll the transaction back, ignoring any exceptions. @@ -1772,12 +1733,10 @@ void cleanUpEmpty(CoordinatorImpl parent) { * Directs the SubCoordinator to commit the transaction in one phase * The SubCoordinator directs all registered Resources to commit. * - * @param * - * @return * - * @see */ + @Override boolean commitOnePhase() { // The commit of a subtransaction is always a one phase commit. @@ -1805,12 +1764,11 @@ boolean commitOnePhase() { * This very basic method is used by the trace facility and should * not call any method which is traced. * - * @param * * @return The hash code for the object. * - * @see */ + @Override public int hashCode() { return hash; } @@ -1834,8 +1792,8 @@ public int hashCode() { * * @return Indicates equality. * - * @see */ + @Override public boolean equals(java.lang.Object other) throws INVALID_TRANSACTION { // Do a quick check on the object references. diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SuperiorInfo.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SuperiorInfo.java index 04ed6f6a65a..4c5ea625b1f 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SuperiorInfo.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/SuperiorInfo.java @@ -49,7 +49,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -100,11 +99,8 @@ class SuperiorInfo { /** * Default SuperiorInfo constructor. * - * @param * - * @return * - * @see */ SuperiorInfo() { } @@ -121,9 +117,7 @@ class SuperiorInfo { * @param superior The superior Coordinator reference (may be null). * @param log The CoordinatorLog object (may be null). * - * @return * - * @see */ SuperiorInfo(Long localTID, GlobalTID globalTID, Coordinator superior, CoordinatorLog log) { @@ -153,11 +147,8 @@ class SuperiorInfo { /** * Cleans up the objects state. * - * @param * - * @return * - * @see */ public void doFinalize() { @@ -204,9 +195,7 @@ public void doFinalize() { * @param log The CoordinatorLog object for the transaction. * @param coord The Coordinator object recreated after recovery. * - * @return * - * @see */ void reconstruct(CoordinatorLog log, CoordinatorImpl coord) { @@ -361,9 +350,7 @@ void delegated_reconstruct(CoordinatorLog log, CoordinatorImpl coord, String log * * @param rec The RecoveryCoordinator from the superior. * - * @return * - * @see */ void setRecovery(RecoveryCoordinator rec) { @@ -383,9 +370,7 @@ void setRecovery(RecoveryCoordinator rec) { * * @param res The CoordinatorResource registered with the superior. * - * @return * - * @see */ void setResource(SubtransactionAwareResource res) { @@ -403,11 +388,9 @@ void setResource(SubtransactionAwareResource res) { /** * Returns the number of retries so far, and increments the count. * - * @param * * @return The number of retries so far. * - * @see */ int resyncRetries() { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TerminatorImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TerminatorImpl.java index b5ef3df3793..7512eea32d4 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TerminatorImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TerminatorImpl.java @@ -69,7 +69,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -95,11 +94,8 @@ class TerminatorImpl extends TerminatorPOA implements Terminator { /** * Default TerminatorImpl constructor. * - * @param * - * @return * - * @see */ TerminatorImpl() {} @@ -111,9 +107,7 @@ class TerminatorImpl extends TerminatorPOA implements Terminator { * @param coordinator The Coordinator for the transaction. * @param subtran A flag indicating whether the transaction is a child. * - * @return * - * @see */ TerminatorImpl (CoordinatorImpl coordinator, boolean subtran) { @@ -189,7 +183,6 @@ private void preCompletionCheck() * @param reportHeuristics Indicates whether heuristic exceptions * should be passed to the caller. * - * @return * * @exception HeuristicHazard Heuristic action may have been taken by a * participant in the transaction. @@ -198,7 +191,6 @@ private void preCompletionCheck() * of the transaction has been rolled back. * @exception SystemException The operation failed. * - * @see */ synchronized public void commit(boolean reportHeuristics) throws HeuristicMixed, HeuristicHazard, TRANSACTION_ROLLEDBACK { @@ -251,13 +243,10 @@ synchronized public void commit(boolean reportHeuristics) * This operation is part of the OMG interface and must not return * any exceptions other than those defined in the OMG interface. * - * @param * - * @return * * @exception SystemException The operation failed. * - * @see */ public void rollback() throws SystemException { @@ -294,11 +283,9 @@ public void rollback() throws SystemException { /** * Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ synchronized final Terminator object() { if (thisRef == null) { @@ -335,11 +322,8 @@ synchronized final Terminator object() { /** * Destroys the TerminatorImpl object. * - * @param * - * @return * - * @see */ synchronized final void destroy() { if (poa != null && thisRef != null) { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TimeoutManager.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TimeoutManager.java index c729b099652..14762a29e0b 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TimeoutManager.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TimeoutManager.java @@ -51,7 +51,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -89,11 +88,8 @@ class TimeoutManager { /** * Initialises the static state of the TimeoutManager class. * - * @param * - * @return * - * @see */ synchronized static void initialise() { @@ -138,7 +134,6 @@ static synchronized void initSetTimeout() { * * @return Indicates success of the operation. * - * @see */ static boolean setTimeout(Long localTID, int timeoutType, int seconds) { boolean result = true; @@ -218,9 +213,7 @@ static boolean setTimeout(Long localTID, int timeoutType, int seconds) { * @param localTID The local identifier for the transaction. * @param timeoutType The type of timeout. * - * @return * - * @see */ static void timeoutCoordinator(Long localTID, int timeoutType) { @@ -333,11 +326,9 @@ static void timeoutCoordinator(Long localTID, int timeoutType) { * cause a deadlock when RecoveryManager methods on other threads call * setTimeout. * - * @param * * @return The information for transactions which have timed out. * - * @see */ static Enumeration checkTimeouts() { if (!isSetTimeout) { @@ -460,7 +451,6 @@ static XID[] getInDoubtXids() { * this value will be negative. If the timeout period has been * exceeded, this value will be zero. * - * @see */ static long timeLeft(Long localTID) { @@ -489,9 +479,7 @@ static long timeLeft(Long localTID) { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ static void shutdown(boolean immediate) { @@ -524,9 +512,7 @@ static void shutdown(boolean immediate) { * * @param immediate Indicates whether to stop immediately. * - * @return * - * @see */ /* static void report() { @@ -569,7 +555,6 @@ static void report() { * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -593,7 +578,6 @@ class TimeoutInfo extends Object { * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -615,9 +599,6 @@ class TimeoutThread extends Thread { * This sets the thread name, and sets the thread to be a daemon thread so * that it does not prevent the process from terminating. * - * @param - * @return - * @see */ TimeoutThread() { setName("JTS Timeout Thread"/* #Frozen */); @@ -640,11 +621,8 @@ class TimeoutThread extends Thread { /** * Performs timeout checking on a regular basis (every ten seconds or so). * - * @param * - * @return * - * @see */ public void run() { try { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TopCoordinator.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TopCoordinator.java index 5ec970a183d..4d27c7cbfd4 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TopCoordinator.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TopCoordinator.java @@ -87,7 +87,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -139,11 +138,8 @@ public class TopCoordinator extends CoordinatorImpl { /** * Default TopCoordinator constructor. * - * @param * - * @return * - * @see */ TopCoordinator() { // No persistent reference is created in this case. @@ -158,11 +154,9 @@ public class TopCoordinator extends CoordinatorImpl { * * @param timeOut The time-out value for the transaction. * - * @return * * @exception LogicErrorException An internal logic error occurred. * - * @see */ TopCoordinator(int timeOut) throws LogicErrorException { @@ -251,11 +245,9 @@ public class TopCoordinator extends CoordinatorImpl { * @param superior The superior Coordinator. * @param temporary The temporary indicator. * - * @return * * @exception LogicErrorException An internal logic error occurred. * - * @see */ TopCoordinator(int timeOut, GlobalTID globalTID, Coordinator superior, boolean temporary) throws LogicErrorException { @@ -329,11 +321,8 @@ public class TopCoordinator extends CoordinatorImpl { /** * Cleans up the objects state. * - * @param * - * @return * - * @see */ synchronized public void doFinalize() { @@ -406,9 +395,7 @@ synchronized public void doFinalize() { * * @param log The CoordinatorLog object which contains the Coordinators * state. - * @return * - * @see */ synchronized void reconstruct(CoordinatorLog log) { @@ -486,9 +473,7 @@ synchronized void reconstruct(CoordinatorLog log) { * state. * * @param logPath Location of the log file - * @return * - * @see */ synchronized void delegated_reconstruct(CoordinatorLog log, String logPath ) { @@ -574,7 +559,6 @@ synchronized void delegated_reconstruct(CoordinatorLog log, String logPath ) { * * @return The state of the recovered transaction. * - * @see */ synchronized Status recover(boolean[/*1*/] isRoot) { @@ -791,11 +775,9 @@ synchronized Status recover(boolean[/*1*/] isRoot) { /** * Returns the local status of the target transaction. * - * @param * * @return The status of the transaction. * - * @see */ public Status get_status() { @@ -876,11 +858,9 @@ public Status get_status() { * This operation references no instance variables and so can be * implemented locally in the proxy class. * - * @param * * @return The status of the transaction. * - * @see */ public Status get_parent_status() { Status result = get_status(); @@ -894,11 +874,9 @@ public Status get_parent_status() { * This operation references no instance variables and so can be * implemented locally in a proxy class. * - * @param * * @return The status of the transaction. * - * @see */ public Status get_top_level_status() { @@ -923,7 +901,6 @@ public Status get_top_level_status() { * * @exception SystemException The other Coordinator could not be reached. * - * @see */ /** removed synchronization at method level since only tranState requires @@ -966,7 +943,6 @@ public boolean is_same_transaction(Coordinator other) * * @exception SystemException The other Coordinator could not be reached. * - * @see */ public boolean is_related_transaction(Coordinator other) throws SystemException { @@ -991,7 +967,6 @@ public boolean is_related_transaction(Coordinator other) * * @return Indicates if this is the root TopCoordinator. * - * @see */ public boolean is_root_transaction() { @@ -1015,7 +990,6 @@ public boolean is_root_transaction() { * * @exception SystemException The other Coordinator could not be reached. * - * @see */ public boolean is_ancestor_transaction(Coordinator other) throws SystemException { @@ -1046,7 +1020,6 @@ public boolean is_ancestor_transaction(Coordinator other) * * @exception SystemException The other Coordinator could not be reached. * - * @see */ public boolean is_descendant_transaction(Coordinator other) throws SystemException { @@ -1071,11 +1044,9 @@ public boolean is_descendant_transaction(Coordinator other) * This operation references no instance variables and so can be * implemented locally in a proxy class. * - * @param * * @return Indicates this is a top-level transaction. * - * @see */ public boolean is_top_level_transaction() { @@ -1089,11 +1060,9 @@ public boolean is_top_level_transaction() { * This operation references only the global TID, and so can be * implemented locally in a proxy class. * - * @param * * @return The hash value for the transaction. * - * @see */ /** removed synchronization at method level since only tranState requires @@ -1117,11 +1086,9 @@ public int hash_transaction() { * This operation references only the global TID, and so can be * implemented locally in a proxy class. * - * @param * * @return The hash value for the transaction. * - * @see */ synchronized public int hash_top_level_tran() { @@ -1154,7 +1121,6 @@ synchronized public int hash_top_level_tran() { * represents has already been rolled back, or has been marked * rollback-only. * - * @see */ synchronized public RecoveryCoordinator register_resource(Resource res) throws Inactive, TRANSACTION_ROLLEDBACK { @@ -1310,12 +1276,10 @@ synchronized public RecoveryCoordinator register_resource(Resource res) * * @param sares The SubtransactionAwareResource to be registered. * - * @return * * @exception NotSubtransaction The Coordinator represents a top-level * transaction and cannot accept the registration. * - * @see */ synchronized public void register_subtran_aware(SubtransactionAwareResource sares) throws NotSubtransaction { NotSubtransaction exc = new NotSubtransaction(); @@ -1326,13 +1290,10 @@ synchronized public void register_subtran_aware(SubtransactionAwareResource sare * Ensures that the transaction represented by the target TopCoordinator * cannot be committed. * - * @param * - * @return * * @exception Inactive The Coordinator is already completing the * transaction. - * @see */ public void rollback_only() throws Inactive { @@ -1351,11 +1312,9 @@ public void rollback_only() throws Inactive { * This operation references only the global TID, and so can be * implemented locally in a proxy class. * - * @param * * @return The transaction name. * - * @see */ /** removed synchronization at method level since only tranState requires @@ -1380,14 +1339,12 @@ public String get_transaction_name() { * Creates a subtransaction and returns a Control object that represents * the child transaction. * - * @param * * @return The Control object for the new child transaction. * * @exception Inactive The Coordinator is completing the subtransaction * and cannot create a new child. * - * @see */ synchronized public Control create_subtransaction() throws Inactive { @@ -1463,11 +1420,9 @@ synchronized public Control create_subtransaction() throws Inactive { * in resync. I don't think this is a problem as the global identifier is * allocated in the constructor and then never changes. * - * @param * * @return The global transaction identifier. * - * @see */ public otid_t getGlobalTID() { @@ -1491,11 +1446,9 @@ public int getParticipantCount() { * This method is currently not synchronized because that causes a deadlock * in resync. * - * @param * * @return The local identifier. * - * @see */ public long getLocalTID() { @@ -1519,7 +1472,6 @@ public long getLocalTID() { * @exception SystemException An error occurred. The minor code indicates * the reason for the exception. * - * @see */ synchronized CoordinatorImpl replyAction(int[/* 1 */] action) throws SystemException { CoordinatorImpl result = null; @@ -1580,11 +1532,9 @@ synchronized CoordinatorImpl replyAction(int[/* 1 */] action) throws SystemExcep /** * Marks the TopCoordinator as permanent. * - * @param * * @return The local transaction identifier. * - * @see */ synchronized Long setPermanent() { @@ -1596,11 +1546,9 @@ synchronized Long setPermanent() { /** * Checks whether the TopCoordinator is marked rollback-only. * - * @param * * @return Indicates whether the transaction is rollback-only. * - * @see */ synchronized public boolean isRollbackOnly() { @@ -1611,11 +1559,9 @@ synchronized public boolean isRollbackOnly() { /** * Checks whether the TopCoordinator is active. * - * @param * * @return Indicates the transaction is active. * - * @see */ synchronized boolean isActive() { @@ -1626,11 +1572,9 @@ synchronized boolean isActive() { /** * Checks whether the TopCoordinator has registered with its superior. * - * @param * * @return Indicates the registration status. * - * @see */ synchronized boolean hasRegistered() { @@ -1641,11 +1585,9 @@ synchronized boolean hasRegistered() { /** * Returns the sequence of ancestors of the transaction. * - * @param * * @return The sequence of ancestors. * - * @see */ synchronized public TransIdentity[] getAncestors() { return null; @@ -1659,7 +1601,6 @@ synchronized public TransIdentity[] getAncestors() { * * @return Indicates success of the operation. * - * @see */ synchronized boolean addChild(CoordinatorImpl child) { @@ -1687,7 +1628,6 @@ synchronized boolean addChild(CoordinatorImpl child) { * * @return Indicates success of the operation. * - * @see */ synchronized boolean removeChild(CoordinatorImpl child) { @@ -1725,7 +1665,6 @@ synchronized boolean removeChild(CoordinatorImpl child) { * at most one prepare request (This includes the case where the * Recoverable Server registers the same Resource twice). * - * @param * @return The consolidated vote. * @exception INVALID_TRANSACTION The transaction is not in a state to * commit, due to outstanding work. @@ -1735,7 +1674,6 @@ synchronized boolean removeChild(CoordinatorImpl child) { * @exception HeuristicHazard Indicates that a participant voted to roll * the transaction back, but one or more others may have already * heuristically committed. - * @see */ Vote prepare() throws INVALID_TRANSACTION, HeuristicMixed, HeuristicHazard { // Until we actually distribute prepare flows, synchronize the method. @@ -1973,9 +1911,7 @@ Vote prepare() throws INVALID_TRANSACTION, HeuristicMixed, HeuristicHazard { * and the Resources are directed to forget the transaction before the * Coordinator returns a heuristic exception to its caller. * - * @param * - * @return * * @exception HeuristicMixed A Resource has taken an heuristic decision * which has resulted in part of the transaction being rolled back. @@ -1984,7 +1920,6 @@ Vote prepare() throws INVALID_TRANSACTION, HeuristicMixed, HeuristicHazard { * being rolled back. * @exception NotPrepared The transaction has not been prepared. * - * @see */ void commit() throws HeuristicMixed, HeuristicHazard, NotPrepared { @@ -2139,14 +2074,12 @@ void commit() throws HeuristicMixed, HeuristicHazard, NotPrepared { * * @param force Indicates that the transaction must rollback regardless. * - * @return * * @exception HeuristicMixed A Resource has taken an heuristic decision * which has resulted in part of the transaction being committed. * @exception HeuristicHazard Indicates that heuristic decisions may * have been taken which have resulted in part of the transaction * being rolled back. - * @see */ void rollback(boolean force) throws HeuristicMixed, HeuristicHazard { @@ -2328,7 +2261,6 @@ void rollback(boolean force) throws HeuristicMixed, HeuristicHazard { * * @param sync The Synchronization object to be registered. * - * @return * * @exception Inactive The Coordinator is in the process of completing the * transaction and cannot accept this registration. @@ -2336,7 +2268,6 @@ void rollback(boolean force) throws HeuristicMixed, HeuristicHazard { * cannot support synchronization. * @exception SystemException The operation failed. * - * @see */ synchronized public void register_synchronization(Synchronization sync) throws SystemException, Inactive, SynchronizationUnavailable { @@ -2447,14 +2378,11 @@ synchronized public void register_synchronization(Synchronization sync) * it that the transaction is about to complete and waits for all of the * replies before this operation completes. * - * @param * - * @return * * @exception INVALID_TRANSACTION The transaction is not in a state to * commit, due to outstanding work. * - * @see */ synchronized void beforeCompletion() throws INVALID_TRANSACTION { @@ -2497,9 +2425,7 @@ synchronized void beforeCompletion() throws INVALID_TRANSACTION { * * @param status Indicates whether the transaction committed or aborted. * - * @return * - * @see */ synchronized void afterCompletion(Status status) { @@ -2564,9 +2490,7 @@ synchronized void afterCompletion(Status status) { * * @param term The object normally responsible for terminating the * Coordinator. - * @return * - * @see */ synchronized void setTerminator(CompletionHandler term) { terminator = term; @@ -2576,11 +2500,9 @@ synchronized void setTerminator(CompletionHandler term) { * Gets the parent coordinator of the transaction. As this is a top level * coordinator, a parent does not exist so NULL is returned. * - * @param * * @return The parent Coordinator, null. * - * @see */ Coordinator getParent() { @@ -2591,11 +2513,9 @@ Coordinator getParent() { /** * Gets the superior Coordinator for this transaction. * - * @param * * @return The superior Coordinator * - * @see */ Coordinator getSuperior() { @@ -2609,9 +2529,7 @@ Coordinator getSuperior() { * @param resources The object which will contain the Resources * @param states The object which will contain the states. * - * @return * - * @see */ /* COMMENT(Ram J) only Admin package needs this. public void getResources(ResourceSequenceHolder resources, @@ -2637,12 +2555,10 @@ public void getResources(ResourceSequenceHolder resources, /** * Gets the object normally responsible for terminating this Coordinator. * - * @param * * @return The object normally responsible for terminating * the Coordinator. * - * @see */ CompletionHandler getTerminator() { @@ -2662,9 +2578,7 @@ CompletionHandler getTerminator() { * * @param res The Resource to be directly registered. * - * @return * - * @see */ void directRegisterResource(Resource res) { @@ -2696,14 +2610,12 @@ void directRegisterResource(Resource res) { * Creates a PropagationContext which contains the information which would * normally be passed implicitly via the CosTSPropagation interfaces. * - * @param * * @return The transaction context. * * @exception Inactive The Coordinator is in the process of completing the * transaction and cannot return the information. * - * @see */ synchronized public PropagationContext get_txcontext() throws Unavailable { @@ -2768,9 +2680,7 @@ synchronized public PropagationContext get_txcontext() throws Unavailable { * * @param parent The parent Coordinator * (always null for a TopCoordinator). - * @return * - * @see */ void cleanUpEmpty(CoordinatorImpl parent) { @@ -2800,7 +2710,6 @@ void cleanUpEmpty(CoordinatorImpl parent) { * @param none * @return boolean indicating success or whether two phase commit * should be tried. - * @see */ boolean commitOnePhase() throws HeuristicMixed, HeuristicHazard { @@ -3094,11 +3003,9 @@ boolean commitOnePhase() throws HeuristicMixed, HeuristicHazard { * This very basic method is used by the trace facility and * should not call any method which is traced. * - * @param * * @return The hash code for the object. * - * @see */ public int hashCode() { if (hash == 0 && superInfo != null && superInfo.globalTID != null) { @@ -3115,7 +3022,6 @@ public int hashCode() { * * @return Indicates equality. * - * @see */ public boolean equals(java.lang.Object other) { diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionFactoryImpl.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionFactoryImpl.java index 67babdcf03c..f3d632a4bbc 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionFactoryImpl.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionFactoryImpl.java @@ -70,7 +70,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -93,11 +92,8 @@ class TransactionFactoryImpl extends TransactionFactoryPOA implements Transactio * Constructor for the TransactionFactoryImpl. Passes through * to the parent constructor. * - * @param * - * @return * - * @see */ TransactionFactoryImpl() { @@ -117,7 +113,6 @@ class TransactionFactoryImpl extends TransactionFactoryPOA implements Transactio * * @exception SystemException An error occurred. * - * @see */ public Control create(int timeOut) throws SystemException { @@ -148,7 +143,6 @@ public Control create(int timeOut) throws SystemException { * * @exception SystemException An error occurred. * - * @see */ public ControlImpl localCreate(int timeOut) throws SystemException { @@ -232,7 +226,6 @@ public ControlImpl localCreate(int timeOut) throws SystemException { * * @exception SystemException An error occurred. * - * @see */ public Control recreate(PropagationContext context) throws SystemException { @@ -525,11 +518,8 @@ timeout, tid, new TxInflowCoordinator(), /** * Prevents any further transactional activity in the process. * - * @param * - * @return * - * @see */ static void deactivate() { @@ -544,11 +534,9 @@ static void deactivate() { /**Returns the CORBA Object which represents this object. * - * @param * * @return The CORBA object. * - * @see */ synchronized TransactionFactory object() { if (thisRef == null) { @@ -602,7 +590,6 @@ synchronized TransactionFactory object() { * * @return The TransactionFactoryImpl object which serves it. * - * @see */ synchronized static final TransactionFactoryImpl servant(TransactionFactory factory) { TransactionFactoryImpl result = null; diff --git a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionState.java b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionState.java index e44ea6ba174..90b254feaa5 100644 --- a/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionState.java +++ b/appserver/transaction/jts/src/main/java/com/sun/jts/CosTransactions/TransactionState.java @@ -47,7 +47,6 @@ * * @author Simon Holdsworth, IBM Corporation * - * @see */ //---------------------------------------------------------------------------- @@ -219,11 +218,8 @@ class TransactionState { /** * Default TransactionState constructor. * - * @param * - * @return * - * @see */ TransactionState() {} @@ -240,9 +236,7 @@ class TransactionState { * * @param log The CoordinatorLog object for the transaction. * - * @return * - * @see */ TransactionState(CoordinatorLog log) { @@ -288,9 +282,7 @@ class TransactionState { * @param globalTID The global identifier for the transaction. * @param log The CoordinatorLog for a top-level transaction. * - * @return * - * @see */ TransactionState(GlobalTID globalTID, CoordinatorLog log) { @@ -330,9 +322,7 @@ class TransactionState { * @param parentLocalTID The parent's local identifier. * @param parentGlobalTID The parent's global identifier. * - * @return * - * @see */ TransactionState(Long parentLocalTID, GlobalTID parentGlobalTID) { @@ -368,7 +358,6 @@ class TransactionState { * * @return The current state of the transaction. * - * @see */ int reconstruct(CoordinatorLog log) { @@ -448,7 +437,6 @@ int reconstruct(CoordinatorLog log) { * * @return Indicates if the state change is possible. * - * @see */ boolean setState(int newState) { @@ -756,11 +744,9 @@ boolean setState(int newState) { /** * Returns the current transaction sequence number and increments it. * - * @param * * @return The current transaction sequence number. * - * @see */ private static synchronized long getSequenceNumber() { @@ -770,11 +756,9 @@ private static synchronized long getSequenceNumber() { /** * Returns the current epoch number. * - * @param * * @return The current epoch number. * - * @see */ /*private static int getEpochNumber() { @@ -786,11 +770,9 @@ private static synchronized long getSequenceNumber() { /** * Returns a flag indicating whether any transactions may be in doubt. * - * @param * * @return The in doubt indicator. * - * @see */ static boolean inDoubt() { return inDoubt; @@ -801,9 +783,7 @@ static boolean inDoubt() { * * @param value The new value of the indicator. * - * @return * - * @see */ static void setInDoubt(boolean value) { inDoubt = value; @@ -816,9 +796,7 @@ static void setInDoubt(boolean value) { * @param epoch The epoch number. * @param serverName The server name. * - * @return * - * @see */ private static final byte[] generateTID(long localTID) { if (TIDTemplate == null) { diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java index b19e1fb38fc..de2db36c492 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/core/ApplicationFilterChain.java @@ -89,7 +89,7 @@ public ApplicationFilterChain() { private StandardWrapper wrapper; /** - * Static class array used when the SecurityManager is turned on and doFilterdoFilter is invoked. */ private static Class[] classType = new Class[] { ServletRequest.class, ServletResponse.class, FilterChain.class }; @@ -136,12 +136,14 @@ private void internalDoFilter(ServletRequest request, ServletResponse response) support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response); } catch (IOException | ServletException | RuntimeException e) { - if (filter != null) + if (filter != null) { support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response, e); + } throw e; } catch (Throwable e) { - if (filter != null) + if (filter != null) { support.fireInstanceEvent(AFTER_FILTER_EVENT, filter, request, response, e); + } throw new ServletException(rb.getString(LogFacade.FILTER_EXECUTION_EXCEPTION), e); } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/DeferredFileOutputStream.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/DeferredFileOutputStream.java index 793031736e7..1870671ba9d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/DeferredFileOutputStream.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/DeferredFileOutputStream.java @@ -37,7 +37,7 @@ * you want to store it in memory (for speed), but if the file is large you want * to store it to file (to avoid memory issues). * - * @author Martin Cooper + * @author Martin Cooper * @author gaxzerow * * @version $Id: DeferredFileOutputStream.java 606381 2007-12-22 02:03:16Z ggregory $ diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/MultipartStream.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/MultipartStream.java index 6584edefbba..51720cc4a30 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/MultipartStream.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/MultipartStream.java @@ -85,8 +85,8 @@ * * * - * @author Rafal Krzewski - * @author Martin Cooper + * @author Rafal Krzewski + * @author Martin Cooper * @author Sean C. Sullivan * * @version $Id: MultipartStream.java 607869 2008-01-01 16:42:17Z jochen $ diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/PartItem.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/PartItem.java index 57d0f01f2ea..65b45d3c788 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/PartItem.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/PartItem.java @@ -54,11 +54,11 @@ * This class implements java.servlet.http.Part. * * Original authors: - * @author Rafal Krzewski - * @author Sean Legassick - * @author Jason van Zyl + * @author Rafal Krzewski + * @author Sean Legassick + * @author Jason van Zyl * @author John McNally - * @author Martin Cooper + * @author Martin Cooper * @author Sean C. Sullivan * * Adopted for Glassfish: diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItem.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItem.java index 0278a210560..7df26b36f8e 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItem.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItem.java @@ -29,13 +29,13 @@ * received within a multipart/form-data POST request. * The items contents are retrieved by calling {@link #openStream()}.

    *

    Instances of this class are created by accessing the - * iterator, returned by * {@link RequestItemIterator()}.

    + * iterator, returned by * {@link RequestItemIterator}.

    * * Original authors from org.apache.common.fileupload.FileItem: - * @author Rafal Krzewski - * @author Sean Legassick - * @author Jason van Zyl - * @author Martin Cooper + * @author Rafal Krzewski + * @author Sean Legassick + * @author Jason van Zyl + * @author Martin Cooper * * Adopted for Glassfish: * @author Kin-man Chung @@ -50,7 +50,6 @@ interface RequestItem { * @throws IllegalStateException The method was already invoked on * this item. It is not possible to recreate the data stream. * @throws IOException An I/O error occurred. - * @see ItemSkippedException */ InputStream openStream() throws IOException; diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItemIterator.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItemIterator.java index 9b0c4aefb3b..29a9633db70 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItemIterator.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/RequestItemIterator.java @@ -39,11 +39,11 @@ * RFC 1867. * * Original authors from org.apache.common.fileupload: - * @author Rafal Krzewski + * @author Rafal Krzewski * @author Daniel Rall - * @author Jason van Zyl + * @author Jason van Zyl * @author John McNally - * @author Martin Cooper + * @author Martin Cooper * @author Sean C. Sullivan * * Adopted for glassfish: diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/ThresholdingOutputStream.java b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/ThresholdingOutputStream.java index c22f010175f..8a2d3633304 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/ThresholdingOutputStream.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/fileupload/ThresholdingOutputStream.java @@ -38,7 +38,7 @@ * is actually reached, since it triggers when a pending write operation would * cause the threshold to be exceeded. * - * @author Martin Cooper + * @author Martin Cooper * * @version $Id: ThresholdingOutputStream.java 540714 2007-05-22 19:39:44Z niallp $ */ diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/realm/JAASCallbackHandler.java b/appserver/web/web-core/src/main/java/org/apache/catalina/realm/JAASCallbackHandler.java index 89087c31cfa..84d762e0b68 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/realm/JAASCallbackHandler.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/realm/JAASCallbackHandler.java @@ -26,10 +26,8 @@ import javax.security.auth.callback.UnsupportedCallbackException; /** - *

    - * Implementation of the JAAS CallbackHandler interface, used to negotiate delivery of the username and + * Implementation of the JAAS CallbackHandler interface, used to negotiate delivery of the username and * credentials that were specified to our constructor. No interaction with the user is required (or possible). - *

    * * @author Craig R. McClanahan * @version $Revision: 1.2 $ $Date: 2005/12/08 01:27:52 $ diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Catalina.java b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Catalina.java index 22d17503f66..e204f6d1ff5 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Catalina.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Catalina.java @@ -48,7 +48,7 @@ * "catalina.base" system property. [conf/server.xml] *
  • -help - Display usage information. *
  • -stop - Stop the currently running instance of Catalina. - * + * * * Should do the same thing as Embedded, but using a server.xml file. * @@ -135,6 +135,7 @@ public void setParentClassLoader(ClassLoader parentClassLoader) { * * @param server The new server */ + @Override public void setServer(Server server) { this.server = server; } @@ -230,8 +231,9 @@ protected boolean arguments(String args[]) { protected File configFile() { File file = new File(configFile); - if (!file.isAbsolute()) + if (!file.isAbsolute()) { file = new File(System.getProperty("catalina.base"), configFile); + } return (file); } @@ -244,8 +246,9 @@ protected Digester createStartDigester() { long t1=System.currentTimeMillis(); // Initialize the digester Digester digester = new Digester(); - if (debug>0) + if (debug>0) { digester.setDebug(debug); + } digester.setValidating(false); digester.setClassLoader(standardServerClassLoader); @@ -331,8 +334,9 @@ protected Digester createStartDigester() { parentClassLoader)); long t2=System.currentTimeMillis(); - if (log.isLoggable(Level.FINE)) + if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Digester for server.xml created " + ( t2-t1 )); + } return (digester); } @@ -345,8 +349,9 @@ protected Digester createStopDigester() { // Initialize the digester Digester digester = new Digester(); - if (debug>0) + if (debug>0) { digester.setDebug(debug); + } // Configure the rules we need for shutting down digester.addObjectCreate("Server", @@ -401,8 +406,9 @@ public void stopServer() { socket = new Socket("127.0.0.1", server.getPort()); stream = socket.getOutputStream(); String shutdown = server.getShutdown(); - for (int i = 0; i < shutdown.length(); i++) + for (int i = 0; i < shutdown.length(); i++) { stream.write(shutdown.charAt(i)); + } stream.flush(); } catch (IOException e) { log.log(Level.SEVERE, LogFacade.CATALINA_STOP_EXCEPTION, e); @@ -431,6 +437,7 @@ public void stopServer() { * working directory if it has not been set. * @deprecated Use initDirs() */ + @Deprecated public void setCatalinaBase() { initDirs(); } @@ -440,6 +447,7 @@ public void setCatalinaBase() { * working directory if it has not been set. * @deprecated Use initDirs() */ + @Deprecated public void setCatalinaHome() { initDirs(); } @@ -542,8 +550,9 @@ public void load(String args[]) { setCatalinaHome(); setCatalinaBase(); try { - if (arguments(args)) + if (arguments(args)) { load(); + } } catch (Exception e) { log.log(Level.WARNING, LogFacade.ERROR_LOADING_CONFIGURATION_EXCEPTION, e); } @@ -553,6 +562,7 @@ public void create() { } + @Override public void destroy() { } @@ -560,6 +570,7 @@ public void destroy() { /** * Start a new server instance. */ + @Override public void start() { if (server == null) { @@ -603,6 +614,7 @@ public void start() { /** * Stop an existing server instance. */ + @Override public void stop() { try { @@ -661,6 +673,7 @@ protected class CatalinaShutdownHook extends Thread { super("GlassFish Catalina Shutdown Hook"); } + @Override public void run() { if (server != null) { @@ -693,10 +706,12 @@ public SetParentClassLoaderRule(Digester digester, ClassLoader parentClassLoader = null; + @Override public void begin(Attributes attributes) throws Exception { - if (digester.getDebug() >= 1) + if (digester.getDebug() >= 1) { digester.log("Setting parent class loader"); + } Container top = (Container) digester.peek(); top.setParentClassLoader(parentClassLoader); diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/DigesterFactory.java b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/DigesterFactory.java index 72498c9632b..12dd9aa4fff 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/DigesterFactory.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/DigesterFactory.java @@ -71,7 +71,7 @@ public Digester newDigester(RuleSet rule){ * Create a Digester parser. * @param xmlValidation turn on/off xml validation * @param xmlNamespaceAware turn on/off namespace validation - * @param rule an instance of RuleRule used for parsing the xml. */ public Digester newDigester(boolean xmlValidation, boolean xmlNamespaceAware, @@ -99,8 +99,9 @@ public Digester newDigester(boolean xmlValidation, } digester.setEntityResolver(entityResolver); - if ( rule != null ) + if ( rule != null ) { digester.addRuleSet(rule); + } return (digester); } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/HomesUserDatabase.java b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/HomesUserDatabase.java index 93fbb058a8c..fb7f5dc1036 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/HomesUserDatabase.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/HomesUserDatabase.java @@ -24,7 +24,7 @@ /** - * Concrete implementation of the UserDatabase interface + * Concrete implementation of the UserDatabase interface * considers all directories in a directory whose pathname is specified * to our constructor to be "home" directories for those users. * @@ -70,6 +70,7 @@ public HomesUserDatabase() { /** * Return the UserConfig listener with which we are associated. */ + @Override public UserConfig getUserConfig() { return (this.userConfig); @@ -82,6 +83,7 @@ public UserConfig getUserConfig() { * * @param userConfig The new UserConfig listener */ + @Override public void setUserConfig(UserConfig userConfig) { this.userConfig = userConfig; @@ -98,6 +100,7 @@ public void setUserConfig(UserConfig userConfig) { * * @param user User for which a home directory should be retrieved */ + @Override public String getHome(String user) { return homes.get(user); @@ -108,6 +111,7 @@ public String getHome(String user) { /** * Return an enumeration of the usernames defined on this server. */ + @Override public Enumeration getUsers() { return (homes.keys()); @@ -125,14 +129,16 @@ private void init() { String homeBase = userConfig.getHomeBase(); File homeBaseDir = new File(homeBase); - if (!homeBaseDir.exists() || !homeBaseDir.isDirectory()) + if (!homeBaseDir.exists() || !homeBaseDir.isDirectory()) { return; + } String homeBaseFiles[] = homeBaseDir.list(); for (int i = 0; i < homeBaseFiles.length; i++) { File homeDir = new File(homeBaseDir, homeBaseFiles[i]); - if (!homeDir.isDirectory() || !homeDir.canRead()) + if (!homeDir.isDirectory() || !homeDir.canRead()) { continue; + } homes.put(homeBaseFiles[i], homeDir.toString()); } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/PasswdUserDatabase.java b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/PasswdUserDatabase.java index c21e0aad287..f2c23c9f16d 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/PasswdUserDatabase.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/PasswdUserDatabase.java @@ -26,7 +26,7 @@ /** - * Concrete implementation of the UserDatabase interface + * Concrete implementation of the UserDatabase interface * that processes the /etc/passwd file on a Unix system. * * @author Craig R. McClanahan @@ -77,6 +77,7 @@ public PasswdUserDatabase() { /** * Return the UserConfig listener with which we are associated. */ + @Override public UserConfig getUserConfig() { return (this.userConfig); @@ -89,6 +90,7 @@ public UserConfig getUserConfig() { * * @param userConfig The new UserConfig listener */ + @Override public void setUserConfig(UserConfig userConfig) { this.userConfig = userConfig; @@ -105,6 +107,7 @@ public void setUserConfig(UserConfig userConfig) { * * @param user User for which a home directory should be retrieved */ + @Override public String getHome(String user) { return homes.get(user); @@ -115,6 +118,7 @@ public String getHome(String user) { /** * Return an enumeration of the usernames defined on this server. */ + @Override public Enumeration getUsers() { return (homes.keys()); @@ -141,19 +145,22 @@ private void init() { StringBuilder buffer = new StringBuilder(); while (true) { int ch = reader.read(); - if ((ch < 0) || (ch == '\n')) + if ((ch < 0) || (ch == '\n')) { break; + } buffer.append((char) ch); } String line = buffer.toString(); - if (line.length() < 1) + if (line.length() < 1) { break; + } // Parse the line into constituent elements int n = 0; String tokens[] = new String[7]; - for (int i = 0; i < tokens.length; i++) + for (int i = 0; i < tokens.length; i++) { tokens[i] = null; + } while (n < tokens.length) { String token = null; int colon = line.indexOf(':'); @@ -168,8 +175,9 @@ private void init() { } // Add this user and corresponding directory - if ((tokens[0] != null) && (tokens[5] != null)) + if ((tokens[0] != null) && (tokens[5] != null)) { homes.put(tokens[0], tokens[5]); + } } diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Tool.java b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Tool.java index dc233d2a81f..4f4525d8f91 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Tool.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/startup/Tool.java @@ -51,23 +51,23 @@ * *

    with the following replacement contents: *

      - *
    • ${options} - Command line options for this Tool wrapper. + *
    • ${options} - Command line options for this Tool wrapper. * The following options are supported: *
        - *
      • -ant : Set the ant.home system property + *
      • -ant : Set the ant.home system property * to corresponding to the value of catalina.home * (useful when your command line tool runs Ant).
      • - *
      • -common : Add common/classes and - * common/lib - *
      • -debug : Enable debugging messages from this wrapper.
      • - *
      • -server : Add server/classes and + *
      • -common : Add common/classes and + * common/lib to the class loader repositories.
      • + *
      • -debug : Enable debugging messages from this wrapper.
      • + *
      • -server : Add server/classes and * server/lib to the class loader repositories.
      • - *
      • -shared : Add shared/classes and + *
      • -shared : Add shared/classes and * shared/lib to the class loader repositories.
      • *
      - *
    • ${classname} - Fully qualified Java class name of the + *
    • ${classname} - Fully qualified Java class name of the * application's main class.
    • - *
    • ${arguments} - Command line arguments to be passed to + *
    • ${arguments} - Command line arguments to be passed to * the application's main() method.
    • *
    * diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/util/ExtensionValidator.java b/appserver/web/web-core/src/main/java/org/apache/catalina/util/ExtensionValidator.java index d11a14b432c..ab144c890fe 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/util/ExtensionValidator.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/util/ExtensionValidator.java @@ -136,7 +136,9 @@ public static synchronized boolean validateApplication( ManifestResource appManifestResource = null; // If the application context is null it does not exist and // therefore is not valid - if (dirContext == null) return false; + if (dirContext == null) { + return false; + } // Find the Manifest for the Web Applicaiton InputStream inputStream = null; try { @@ -213,7 +215,7 @@ public static synchronized boolean validateApplication( * objects. This method requires an application name (which is the * context root of the application at runtime). * - * false is returned if the extension dependencies + * false is returned if the extension dependencies * represented by any given ManifestResource objects * is not met. * diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/util/IOTools.java b/appserver/web/web-core/src/main/java/org/apache/catalina/util/IOTools.java index 9d7467343e2..fdee7627c91 100644 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/util/IOTools.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/util/IOTools.java @@ -53,7 +53,7 @@ public static void flow( Reader reader, Writer writer, char[] buf ) } /** - * @see flow( Reader, Writer, char[] ) + * @see #flow(Reader, Writer, char[]) */ public static void flow( Reader reader, Writer writer ) throws IOException { @@ -65,8 +65,8 @@ public static void flow( Reader reader, Writer writer ) * Read input from input stream and write it to output stream * until there is no more input from input stream. * - * @param input stream the input stream to read from. - * @param output stream the output stream to write to. + * @param is stream the input stream to read from. + * @param os stream the output stream to write to. * @param buf the byte array to use as a buffer */ public static void flow( InputStream is, OutputStream os, byte[] buf ) @@ -78,7 +78,7 @@ public static void flow( InputStream is, OutputStream os, byte[] buf ) } /** - * @see flow( Reader, Writer, byte[] ) + * @see #flow(Reader, Writer, char[]) */ public static void flow( InputStream is, OutputStream os ) throws IOException { diff --git a/appserver/web/web-core/src/main/java/org/apache/catalina/valves/ExtendedAccessLogValve.java b/appserver/web/web-core/src/main/java/org/apache/catalina/valves/ExtendedAccessLogValve.java index 437f01d3f5e..ae055b5d173 100755 --- a/appserver/web/web-core/src/main/java/org/apache/catalina/valves/ExtendedAccessLogValve.java +++ b/appserver/web/web-core/src/main/java/org/apache/catalina/valves/ExtendedAccessLogValve.java @@ -107,7 +107,7 @@ *

    * *

    - * For JMX junkies, a public method called rotate has + * For JMX junkies, a public method called rotate has * been made available to allow you to tell this instance to move * the existing log file to somewhere else start writing a new log file. *

    diff --git a/appserver/web/web-core/src/main/java/org/apache/tomcat/util/digester/Digester.java b/appserver/web/web-core/src/main/java/org/apache/tomcat/util/digester/Digester.java index 1c538d65df5..4803db69947 100644 --- a/appserver/web/web-core/src/main/java/org/apache/tomcat/util/digester/Digester.java +++ b/appserver/web/web-core/src/main/java/org/apache/tomcat/util/digester/Digester.java @@ -88,6 +88,7 @@ public class Digester extends DefaultHandler { private static class SystemPropertySource implements IntrospectionUtils.PropertySource { + @Override public String getProperty( String key ) { return System.getProperty(key); } @@ -213,6 +214,7 @@ public Digester(XMLReader reader) { /** * @deprecated This is now managed by {@link ParserFeatureSetterFactory} */ + @Deprecated protected String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; @@ -453,6 +455,7 @@ public String getCurrentElementName() { * jakarta commons-logging library; see the documentation for that library * for more information. */ + @Deprecated public int getDebug() { return (0); @@ -470,6 +473,7 @@ public int getDebug() { * the apache jakarta comons-logging library; see the documentation * for that library for more information. */ + @Deprecated public void setDebug(int debug) { ; // No action is taken @@ -517,8 +521,8 @@ public SAXParserFactory getFactory() { /** * Returns a flag indicating whether the requested feature is supported * by the underlying implementation of org.xml.sax.XMLReader. - * See + * See http://www.saxproject.org/apidoc/overview-summary.html * for information about the standard SAX2 feature flags. * * @param feature Name of the feature to inquire about @@ -542,8 +546,8 @@ public boolean getFeature(String feature) /** * Sets a flag indicating whether the requested feature is supported * by the underlying implementation of org.xml.sax.XMLReader. - * See + * See http://www.saxproject.org/apidoc/overview-summary.html * for information about the standard SAX2 feature flags. In order to be * effective, this method must be called before the * getParser() method is called for the first time, either @@ -724,8 +728,8 @@ public SAXParser getParser() { /** * Return the current value of the specified property for the underlying * XMLReader implementation. - * See + * See http://www.saxproject.org/apidoc/overview-summary.html * for information about the standard SAX2 properties. * * @param property Property name to be retrieved @@ -746,8 +750,8 @@ public Object getProperty(String property) /** * Set the current value of the specified property for the underlying * XMLReader implementation. - * See + * See http://www.saxproject.org/apidoc/overview-summary.html * for information about the standard SAX2 properties. * * @param property Property name to be set @@ -773,6 +777,7 @@ public void setProperty(String property, Object value) * @deprecated Use getXMLReader() instead, which can throw a * SAXException if the reader cannot be instantiated */ + @Deprecated public XMLReader getReader() { try { @@ -1015,6 +1020,7 @@ public XMLReader getXMLReader() throws SAXException { * * @exception SAXException if a parsing error is to be reported */ + @Override public void characters(char buffer[], int start, int length) throws SAXException { @@ -1032,6 +1038,7 @@ public void characters(char buffer[], int start, int length) * * @exception SAXException if a parsing error is to be reported */ + @Override public void endDocument() throws SAXException { if (saxLog.isLoggable(Level.FINE)) { @@ -1080,6 +1087,7 @@ public void endDocument() throws SAXException { * empty string if qualified names are not available. * @exception SAXException if a parsing error is to be reported */ + @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { @@ -1176,6 +1184,7 @@ public void endElement(String namespaceURI, String localName, * * @exception SAXException if a parsing error is to be reported */ + @Override public void endPrefixMapping(String prefix) throws SAXException { if (saxLog.isLoggable(Level.FINE)) { @@ -1189,8 +1198,9 @@ public void endPrefixMapping(String prefix) throws SAXException { } try { stack.pop(); - if (stack.empty()) + if (stack.empty()) { namespaces.remove(prefix); + } } catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); } @@ -1208,6 +1218,7 @@ public void endPrefixMapping(String prefix) throws SAXException { * * @exception SAXException if a parsing error is to be reported */ + @Override public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { @@ -1229,6 +1240,7 @@ public void ignorableWhitespace(char buffer[], int start, int len) * * @exception SAXException if a parsing error is to be reported */ + @Override public void processingInstruction(String target, String data) throws SAXException { @@ -1257,6 +1269,7 @@ public Locator getDocumentLocator() { * * @param locator The new locator */ + @Override public void setDocumentLocator(Locator locator) { if (saxLog.isLoggable(Level.FINE)) { @@ -1275,6 +1288,7 @@ public void setDocumentLocator(Locator locator) { * * @exception SAXException if a parsing error is to be reported */ + @Override public void skippedEntity(String name) throws SAXException { if (saxLog.isLoggable(Level.FINE)) { @@ -1291,6 +1305,7 @@ public void skippedEntity(String name) throws SAXException { * * @exception SAXException if a parsing error is to be reported */ + @Override public void startDocument() throws SAXException { if (saxLog.isLoggable(Level.FINE)) { @@ -1317,6 +1332,7 @@ public void startDocument() throws SAXException { * no attributes, it shall be an empty Attributes object. * @exception SAXException if a parsing error is to be reported */ + @Override public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { @@ -1391,6 +1407,7 @@ public void startElement(String namespaceURI, String localName, * * @exception SAXException if a parsing error is to be reported */ + @Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { @@ -1419,6 +1436,7 @@ public void startPrefixMapping(String prefix, String namespaceURI) * @param publicId The public identifier (if any) * @param systemId The system identifier (if any) */ + @Override public void notationDecl(String name, String publicId, String systemId) { if (saxLog.isLoggable(Level.FINE)) { @@ -1437,6 +1455,7 @@ public void notationDecl(String name, String publicId, String systemId) { * @param systemId The system identifier (if any) * @param notation The name of the associated notation */ + @Override public void unparsedEntityDecl(String name, String publicId, String systemId, String notation) { @@ -1478,6 +1497,7 @@ public EntityResolver getEntityResolver(){ * @exception SAXException if a parsing exception occurs * */ + @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { @@ -1485,8 +1505,9 @@ public InputSource resolveEntity(String publicId, String systemId) saxLog.log(Level.FINE, "resolveEntity('" + publicId + "', '" + systemId + "')"); } - if (publicId != null) + if (publicId != null) { this.publicId = publicId; + } // Has this system identifier been registered? String entityURL = null; @@ -1540,6 +1561,7 @@ public InputSource resolveEntity(String publicId, String systemId) * * @exception SAXException if a parsing exception occurs */ + @Override public void error(SAXParseException exception) throws SAXException { String msg = MessageFormat.format(rb.getString(LogFacade.PARSE_ERROR), @@ -1561,6 +1583,7 @@ public void error(SAXParseException exception) throws SAXException { * * @exception SAXException if a parsing exception occurs */ + @Override public void fatalError(SAXParseException exception) throws SAXException { String msg = MessageFormat.format(rb.getString(LogFacade.PARSE_FATAL_ERROR), @@ -1583,6 +1606,7 @@ public void fatalError(SAXParseException exception) throws SAXException { * * @exception SAXException if a parsing exception occurs */ + @Override public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { log.log(Level.WARNING, LogFacade.PARSE_WARNING_ERROR, @@ -1604,6 +1628,7 @@ public void warning(SAXParseException exception) throws SAXException { * @param message The message to be logged * @deprecated Call getLogger() and use it's logging methods */ + @Deprecated public void log(String message) { log.log(Level.INFO, message); } @@ -1615,6 +1640,7 @@ public void log(String message) { * @param message The message to be logged * @deprecated Call getLogger() and use it's logging methods */ + @Deprecated public void log(String message, Throwable exception) { log.log(Level.SEVERE, message, exception); diff --git a/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/CacheTag.java b/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/CacheTag.java index aa75b17624a..b5b84a3b73c 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/CacheTag.java +++ b/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/CacheTag.java @@ -37,14 +37,17 @@ * or not. * * Usage Example: - * <%@ taglib prefix="ias" uri="Sun ONE Application Server Tags" %> - * - * ... expensive operation ... - * + *
    + * {@code <%@ taglib prefix="ias" uri="Sun ONE Application Server Tags" %>}
    + * {@code }
    + * {@code  ... expensive operation ...}
    + * {@code }
    + * 
    */ -public class CacheTag extends BodyTagSupport -{ +public class CacheTag extends BodyTagSupport { + private static final long serialVersionUID = 1L; + /** * Constants used to calculate the timeout */ @@ -121,6 +124,7 @@ public class CacheTag extends BodyTagSupport * ensures that the BodyContent is created and the tag body * is evaluated into it. */ + @Override public int doStartTag() throws JspException { @@ -131,16 +135,18 @@ public int doStartTag() // key is specified, a position specific key suffix is used _key = CacheUtil.generateKey(_keyExpr, pageContext); - if (_logger.isLoggable(Level.FINE)) + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, LogFacade.CACHETAG_TIMEOUT, new Object[] {_key, _timeout}); + } // if useCachedResponse is false, we do not check for any // cached response and just evaluate the tag body if (_useCachedResponse) { _cache = CacheUtil.getCache(pageContext, _scope); - if (_cache == null) + if (_cache == null) { throw new JspException(_rb.getString(LogFacade.TAGLIBS_CACHE_NO_CACHE)); + } // if refreshCache is true, we want to re-evaluate the // tag body and refresh the cached entry @@ -190,6 +196,7 @@ public int doStartTag() * @throws JspException the standard exception thrown * @return always returns SKIP_BODY since we dont do any iteration */ + @Override public int doAfterBody() throws JspException { @@ -223,6 +230,7 @@ public int doAfterBody() * @throws JspException the standard exception thrown * @return always returns EVAL_PAGE since we want the entire jsp evaluated */ + @Override public int doEndTag() throws JspException { @@ -245,8 +253,9 @@ public int doEndTag() * the cache. */ public void setKey(String key) { - if (key != null && key.length() > 0) + if (key != null && key.length() > 0) { _keyExpr = key; + } } /** @@ -266,8 +275,9 @@ public void setTimeout(String timeout) { // try to parse it as 1sec, 1min, 1 hour and 1day formats int i = 0; while (i < timeout.length() && - Character.isDigit(timeout.charAt(i))) + Character.isDigit(timeout.charAt(i))) { i++; + } if (i > 0) { _timeout = Integer.parseInt(timeout.substring(0, i)); @@ -298,8 +308,9 @@ public void setTimeout(String timeout) { * either. */ public void setNocache(boolean noCache) { - if (noCache) + if (noCache) { _useCachedResponse = false; + } } /** diff --git a/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/FlushTag.java b/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/FlushTag.java index 0ffbd518a36..401029f652a 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/FlushTag.java +++ b/appserver/web/web-glue/src/main/java/com/sun/appserv/web/taglibs/cache/FlushTag.java @@ -34,10 +34,14 @@ * identified by the key. * * Usage Example: - * <%@ taglib prefix="ias" uri="Sun ONE Application Server Tags" %> - * + *
    + * {@code <%@ taglib prefix="ias" uri="Sun ONE Application Server Tags" %>}
    + * {@code }
    + * 
    */ public class FlushTag extends TagSupport { + private static final long serialVersionUID = 1L; + /** * The key for the cache entry that needs to be flushed. */ @@ -63,6 +67,7 @@ public class FlushTag extends TagSupport { * @throws JspException the standard exception thrown * @return SKIP_BODY since the tag should be empty */ + @Override public int doStartTag() throws JspException { @@ -77,14 +82,16 @@ public int doStartTag() // remove the entry for the key cache.remove(key); - if (_logger.isLoggable(Level.FINE)) + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, LogFacade.FLUSH_TAG_CLEAR_KEY, key); + } } else { // clear the entire cache cache.clear(); - if (_logger.isLoggable(Level.FINE)) + if (_logger.isLoggable(Level.FINE)) { _logger.log(Level.FINE, LogFacade.FLUSH_TAG_CLEAR_CACHE); + } } return SKIP_BODY; @@ -96,6 +103,7 @@ public int doStartTag() * @throws JspException the standard exception thrown * @return always returns EVAL_PAGE since we want the entire jsp evaluated */ + @Override public int doEndTag() throws JspException { @@ -112,8 +120,9 @@ public int doEndTag() * This is set a key for the cache element that needs to be cleared */ public void setKey(String key) { - if (key != null && key.length() > 0) + if (key != null && key.length() > 0) { _key = key; + } } /** diff --git a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebModule.java b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebModule.java index f73f12a7a74..b6c1fecb1b0 100644 --- a/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebModule.java +++ b/appserver/web/web-glue/src/main/java/com/sun/enterprise/web/WebModule.java @@ -1000,7 +1000,7 @@ protected void configureValves() { } /** - * Configure the WebModuleWebModule properties. */ protected void configureCatalinaProperties() { String propName = null; @@ -1027,7 +1027,7 @@ protected void configureCatalinaProperties() { } /** - * Configure the WebModuleWebModule properties. * * @param propName the property name * @param propValue the property value diff --git a/appserver/web/web-glue/src/main/java/org/glassfish/web/deployment/annotation/handlers/AbstractWebHandler.java b/appserver/web/web-glue/src/main/java/org/glassfish/web/deployment/annotation/handlers/AbstractWebHandler.java index b664eee1030..40a9d782b0c 100644 --- a/appserver/web/web-glue/src/main/java/org/glassfish/web/deployment/annotation/handlers/AbstractWebHandler.java +++ b/appserver/web/web-glue/src/main/java/org/glassfish/web/deployment/annotation/handlers/AbstractWebHandler.java @@ -65,7 +65,7 @@ protected abstract HandlerProcessingResult processAnnotation( /** * Process a particular annotation which type is the same as the - * one returned by @see getAnnotationType(). All information + * one returned by {@link AnnotationInfo#getElementType()}. All information * pertinent to the annotation and its context is encapsulated * in the passed AnnotationInfo instance. * This is a method in interface AnnotationHandler. diff --git a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/WebServiceReferenceManagerImpl.java b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/WebServiceReferenceManagerImpl.java index c231813f58b..6000339c71a 100644 --- a/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/WebServiceReferenceManagerImpl.java +++ b/appserver/webservices/jsr109-impl/src/main/java/org/glassfish/webservices/WebServiceReferenceManagerImpl.java @@ -77,7 +77,7 @@ /** * This class acts as a service to resolve the - * jakarta.xml.ws.WebServiceRef references + * jakarta.xml.ws.WebServiceRef references * and also jakarta.xml.ws.WebServiceContext * Whenever a lookup is done from GlassfishNamingManagerImpl * these methods are invoked to resolve the references diff --git a/docs/add-on-component-development-guide/src/main/asciidoc/extending-asadmin.adoc b/docs/add-on-component-development-guide/src/main/asciidoc/extending-asadmin.adoc index 71d26d9b96f..18a917a0483 100644 --- a/docs/add-on-component-development-guide/src/main/asciidoc/extending-asadmin.adoc +++ b/docs/add-on-component-development-guide/src/main/asciidoc/extending-asadmin.adoc @@ -123,7 +123,7 @@ are installed, use the xref:reference-manual.adoc#list-commands[`list-commands`] subcommand. For a complete list of `asadmin` subcommands that are supplied in {productName} distributions, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc[{productName} Reference Manual]. [[ensuring-that-an-admincommand-implementation-is-stateless]] diff --git a/docs/add-on-component-development-guide/src/main/asciidoc/preface.adoc b/docs/add-on-component-development-guide/src/main/asciidoc/preface.adoc index a0e535dec22..e03e3c72081 100644 --- a/docs/add-on-component-development-guide/src/main/asciidoc/preface.adoc +++ b/docs/add-on-component-development-guide/src/main/asciidoc/preface.adoc @@ -56,24 +56,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -86,45 +86,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -137,7 +137,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/administration-guide/src/main/asciidoc/asadmin-subcommands.adoc b/docs/administration-guide/src/main/asciidoc/asadmin-subcommands.adoc index 2f045e85202..a08145b06fc 100644 --- a/docs/administration-guide/src/main/asciidoc/asadmin-subcommands.adoc +++ b/docs/administration-guide/src/main/asciidoc/asadmin-subcommands.adoc @@ -29,11 +29,11 @@ this release of the {productName} {product-majorVersion} software. For information and instructions on using the `asadmin` application deployment subcommands, see -the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. -Online help for the `asadmin` subcommands can be invoked on the command -line, for example, `asadmin create-domain` `help`. -The xref:reference-manual.adoc#GSRFM[{productName} Reference Manual] also +Documentation help for the `asadmin` subcommands can be invoked on the command +line, for example, `asadmin create-domain --help`. +The xref:reference-manual.adoc[{productName} Reference Manual] also provides a collection of these help pages. diff --git a/docs/administration-guide/src/main/asciidoc/general-administration.adoc b/docs/administration-guide/src/main/asciidoc/general-administration.adoc index ef70a758a71..8f72ee3efdf 100644 --- a/docs/administration-guide/src/main/asciidoc/general-administration.adoc +++ b/docs/administration-guide/src/main/asciidoc/general-administration.adoc @@ -229,7 +229,7 @@ Command list-applications executed successfully. {productName} provides help information about the syntax, purpose, and options of the `asadmin` utility and its subcommands. This help information is written in the style of UNIX platform man pages. This -help information is also available in the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +help information is also available in the xref:reference-manual.adoc[{productName} Reference Manual]. 1. If you are displaying help information for a remote subcommand, ensure that the server is running. @@ -2996,7 +2996,7 @@ message-id:: value, for example, `CORE5004`. All `SEVERE` and `WARNING` messages and some `INFO` messages from {productName} contain a message identifier. For more information, see the - xref:error-messages-reference.adoc#GSEMR[ + xref:error-messages-reference.adoc[ {productName} Error Message Reference]. message-text:: The text of the log message. @@ -3100,7 +3100,7 @@ message-id:: A unique identifier for the message. For messages from {productName}, this identifier consists of a module code and a numerical value, for example, `CORE5004`. All `SEVERE` and `WARNING` messages and some `INFO` messages from {productName} contain a message - identifier. For more information, see the xref:error-messages-reference.adoc#GSEMR[{productName} Error Message Reference]. + identifier. For more information, see the xref:error-messages-reference.adoc[{productName} Error Message Reference]. thread-id:: The numerical identifier of the thread that created the message. thread-name:: diff --git a/docs/administration-guide/src/main/asciidoc/http_https.adoc b/docs/administration-guide/src/main/asciidoc/http_https.adoc index 129d4f1bca0..00dcee3b155 100644 --- a/docs/administration-guide/src/main/asciidoc/http_https.adoc +++ b/docs/administration-guide/src/main/asciidoc/http_https.adoc @@ -32,7 +32,7 @@ either in a single application server instance or in a cluster of multiple server instances. HTTP services are provided by two kinds of related objects: listeners and virtual servers. -For more information about clusters, see the xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability Administration Guide]. +For more information about clusters, see the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. The following topics are addressed here: @@ -787,7 +787,7 @@ web application and don't specify any assigned virtual servers, the web application is assigned to all currently defined virtual servers. If you then create additional virtual servers and want to assign existing web applications to them, you must redeploy the web applications. For more -information about deployment, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +information about deployment, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. You can define virtual server properties using the `asadmin set` command. For example: @@ -980,7 +980,7 @@ You can assign a virtual server to a deployed application or web module. Before You Begin The application or module must already be deployed. For more -information, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +information, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. 1. In the Administration Console, open the HTTP Service component under diff --git a/docs/administration-guide/src/main/asciidoc/jdbc.adoc b/docs/administration-guide/src/main/asciidoc/jdbc.adoc index c7c9c220042..7606a7d3f15 100644 --- a/docs/administration-guide/src/main/asciidoc/jdbc.adoc +++ b/docs/administration-guide/src/main/asciidoc/jdbc.adoc @@ -101,7 +101,7 @@ The following topics are addressed here: 1. Install a supported database product. + -To see the current list of database products supported by {productName}, refer to the xref:release-notes.adoc#GSRLN[{productName} Release Notes]. +To see the current list of database products supported by {productName}, refer to the xref:release-notes.adoc[{productName} Release Notes]. 2. Install a supported JDBC driver for the database product. + @@ -514,7 +514,7 @@ xref:overview.adoc#configuration-changes-that-require-restart[Configuration Chan See Also For information about how to tune a connection pool, see the -xref:performance-tuning-guide.adoc#GSPTG[{productName} Performance Tuning +xref:performance-tuning-guide.adoc[{productName} Performance Tuning Guide]. [[to-delete-a-jdbc-connection-pool]] @@ -1037,7 +1037,7 @@ these topics: ===== Supported Database Drivers Supported JDBC drivers are those that have been fully tested by Oracle. -For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release +For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see <>. diff --git a/docs/administration-guide/src/main/asciidoc/overview.adoc b/docs/administration-guide/src/main/asciidoc/overview.adoc index 8eff68ec783..7f89c5318cd 100644 --- a/docs/administration-guide/src/main/asciidoc/overview.adoc +++ b/docs/administration-guide/src/main/asciidoc/overview.adoc @@ -810,7 +810,7 @@ asadmin help restart-domain ---- A collection of the `asadmin` help pages is available in HTML and PDF -format in the xref:reference-manual.adoc#GSRFM[{productName} Reference +format in the xref:reference-manual.adoc[{productName} Reference Manual]. [[rest-interfaces]] @@ -1178,6 +1178,6 @@ system, use backslashes (\) instead. For example: The following additional documents address specific administration areas: * Verifying and deploying applications -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide] +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/administration-guide/src/main/asciidoc/preface.adoc b/docs/administration-guide/src/main/asciidoc/preface.adoc index e4b26ef3cf4..3426ca9c56e 100644 --- a/docs/administration-guide/src/main/asciidoc/preface.adoc +++ b/docs/administration-guide/src/main/asciidoc/preface.adoc @@ -45,24 +45,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -75,45 +75,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -126,7 +126,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/administration-guide/src/main/asciidoc/transactions.adoc b/docs/administration-guide/src/main/asciidoc/transactions.adoc index 2867b7ef695..542800a5810 100644 --- a/docs/administration-guide/src/main/asciidoc/transactions.adoc +++ b/docs/administration-guide/src/main/asciidoc/transactions.adoc @@ -114,7 +114,7 @@ Application Development Guide. + The {productName} supports a variety of JDBC XA drivers. For a list of the JDBC drivers currently supported by the {productName}, see the -xref:release-notes.adoc#GSRLN[{productName} Release Notes]. For +xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see xref:jdbc.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]. * Java Message Service (JMS) Providers - Use of transactions ensures @@ -246,7 +246,7 @@ property to override server names that can cause errors. + You can use the xref:reference-manual.adoc#get[`get`] subcommand to list all the transaction service attributes and the properties that have been set. -For details, see the xref:reference-manual.adoc[{productName} +For details, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. + Changing `keypoint-interval`, `retry-timeout-in-seconds`, or @@ -787,7 +787,7 @@ See Also For information about JDBC connection pools and resources, see xref:jdbc.adoc#administering-database-connectivity[Administering Database Connectivity]. For more information about the `asadmin set` and `asadmin create-jvm-options` -commands, see the xref:reference-manual.adoc[{productName} +commands, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. For databases with which transaction logging has been tested, see the {productName} Release Notes. diff --git a/docs/application-deployment-guide/src/main/asciidoc/asadmin-deployment-subcommands.adoc b/docs/application-deployment-guide/src/main/asciidoc/asadmin-deployment-subcommands.adoc index 14a4aae383a..8e713f32370 100644 --- a/docs/application-deployment-guide/src/main/asciidoc/asadmin-deployment-subcommands.adoc +++ b/docs/application-deployment-guide/src/main/asciidoc/asadmin-deployment-subcommands.adoc @@ -14,7 +14,7 @@ This appendix lists the `asadmin` deployment subcommands that are included with this release of the {productName} software. For information on additional `asadmin` subcommands, see "xref:administration-guide.adoc#asadmin-subcommands[Subcommands for the `asadmin` Utility]" in {productName} Administration Guide or see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc[{productName} Reference Manual]. xref:reference-manual.adoc#add-library[`add-library`]:: Adds one or more library JAR files to {productName}. You can diff --git a/docs/application-deployment-guide/src/main/asciidoc/dd-elements.adoc b/docs/application-deployment-guide/src/main/asciidoc/dd-elements.adoc index 070c6505aeb..04c57a8dfdc 100644 --- a/docs/application-deployment-guide/src/main/asciidoc/dd-elements.adoc +++ b/docs/application-deployment-guide/src/main/asciidoc/dd-elements.adoc @@ -2447,7 +2447,7 @@ module. If none is specified, a default is generated; see xref:#java-web-start-access[`java-web-start-access`]. If you are setting up load balancing, web module context roots must be -unique within a server instance. See the xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability Administration Guide] for more +unique within a server instance. See the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide] for more information about load balancing. [[superelements-44]] @@ -3692,7 +3692,7 @@ resource. Specifies the fully qualified name of the factory class, which implements javax.naming.spi.InitialContextFactory . -For more information about JNDI, see the xref:application-development-guide.adoc#GSDVG[{productName} Application Development Guide]. +For more information about JNDI, see the xref:application-development-guide.adoc[{productName} Application Development Guide]. |`object-type` |`user` a| (optional) Defines the type of the resource. Allowed values are: diff --git a/docs/application-deployment-guide/src/main/asciidoc/deploying-applications.adoc b/docs/application-deployment-guide/src/main/asciidoc/deploying-applications.adoc index 4cec21c9ca8..074128b52ad 100644 --- a/docs/application-deployment-guide/src/main/asciidoc/deploying-applications.adoc +++ b/docs/application-deployment-guide/src/main/asciidoc/deploying-applications.adoc @@ -1190,9 +1190,9 @@ deployment option was set to true. This option is not supported and ignored in a clustered environment. See xref:#gijzm[Example 2-8]. + For information about HTTP session persistence, see the -xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability +xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. -* Load Balancing. See the xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability Administration Guide] for information about +* Load Balancing. See the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide] for information about load balancing. * JSP Precompilation. You can precompile JSP files during deployment by checking the appropriate box in the Administration Console, or by using diff --git a/docs/application-deployment-guide/src/main/asciidoc/overview.adoc b/docs/application-deployment-guide/src/main/asciidoc/overview.adoc index e712bc97ce9..b6797952b10 100644 --- a/docs/application-deployment-guide/src/main/asciidoc/overview.adoc +++ b/docs/application-deployment-guide/src/main/asciidoc/overview.adoc @@ -748,11 +748,11 @@ are the following: The following product documentation might be relevant to some aspects of application deployment: -* xref:application-development-guide.adoc#GSDVG[ +* xref:application-development-guide.adoc[ {productName} Application Development Guide] -* xref:administration-guide.adoc#GSADG[ +* xref:administration-guide.adoc[ {productName} Administration Guide] -* xref:add-on-component-development-guide.adoc#GSACG[ +* xref:add-on-component-development-guide.adoc[ {productName} Add-On Component Development Guide] * xref:reference-manual.adoc[ {productName} Reference Manual] diff --git a/docs/application-deployment-guide/src/main/asciidoc/preface.adoc b/docs/application-deployment-guide/src/main/asciidoc/preface.adoc index ec09b5451ce..03475b335c2 100644 --- a/docs/application-deployment-guide/src/main/asciidoc/preface.adoc +++ b/docs/application-deployment-guide/src/main/asciidoc/preface.adoc @@ -48,24 +48,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -78,45 +78,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -129,7 +129,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/application-development-guide/src/main/asciidoc/connectors.adoc b/docs/application-development-guide/src/main/asciidoc/connectors.adoc index 532e68afecd..f3daf488b97 100644 --- a/docs/application-development-guide/src/main/asciidoc/connectors.adoc +++ b/docs/application-development-guide/src/main/asciidoc/connectors.adoc @@ -40,7 +40,7 @@ https://jakarta.ee/learn/docs/jakartaee-tutorial/current/supporttechs/connectors Resource Adapters and Contracts] in The Jakarta EE Tutorial. For information about deploying a connector to the {productName}, see -the xref:application-deployment-guide.adoc#GSDPG[ +the xref:application-deployment-guide.adoc[ {productName} Application Deployment Guide]. The following topics are addressed here: @@ -160,7 +160,7 @@ resource adapters. To create a thread pool: configuration. For details, click the Help button in the Administration Console. * Use the `asadmin create-threadpool` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-threadpool[{productName} Reference Manual]. To associate a connector with a thread pool: @@ -170,7 +170,7 @@ the Thread Pool ID field. For details, click the Help button in the Administration Console. * Use the `--threadpoolid` option of the `asadmin create-resource-adapter-config` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-resource-adapter-config[{productName} Reference Manual]. If you create a resource adapter configuration for a connector module that is already deployed, the connector module deployment is restarted @@ -193,7 +193,7 @@ Connectors, select Connector Connection Pools, and select the Security Maps tab. For details, click the Help button in the Administration Console. * Use the `asadmin create-connector-security-map` command. For details, -see the xref:reference-manual.adoc#GSRFM[{productName} Reference +see the xref:reference-manual.adoc#create-connector-security-map[{productName} Reference Manual]. If a security map already exists for a connector connection pool, the @@ -221,7 +221,7 @@ map either principals or groups, but not both. To create a work security map, use the `asadmin create-connector-work-security-map` command. For details, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-connector-work-security-map[{productName} Reference Manual]. The work security map configuration supports the wildcard asterisk (`*`) character to indicate all users or all user groups. When an EIS @@ -246,7 +246,7 @@ the Administration Console. * Use the `asadmin create-resource-adapter-config` command to create a configuration for a resource adapter. Use this command's `--property` option to specify a name-value pair for a resource adapter property. For -details, see the xref:reference-manual.adoc#GSRFM[{productName} +details, see the xref:reference-manual.adoc#create-resource-adapter-config[{productName} Reference Manual]. You can specify configuration properties either before or after resource @@ -274,7 +274,7 @@ pool you want to test. Then select the Ping button in the top right corner of the page. For details, click the Help button in the Administration Console. * Use the `asadmin ping-connection-pool` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#ping-connection-pool[{productName} Reference Manual]. Both these commands fail and display an error message unless they successfully connect to the connection pool. @@ -288,7 +288,7 @@ Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--ping` option in the `asadmin create-connector-connection-pool` command. For more -information, see the xref:reference-manual.adoc#GSRFM[{productName} +information, see the xref:reference-manual.adoc#create-connector-connection-pool[{productName} Reference Manual]. [[flushing-a-connector-connection-pool]] @@ -310,7 +310,7 @@ pool you want to flush. Then select the Flush button in the top right corner of the page. For details, click the Help button in the Administration Console. * Use the `asadmin flush-connection-pool` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#flush-connection-pool[{productName} Reference Manual]. ==== Handling Invalid Connections @@ -353,7 +353,7 @@ asadmin set server.resources.connector-connection-pool.CCP1.is-connection-valida asadmin set server.resources.connector-connection-pool.CCP1.property.prefer-validate-over-recreate="true" ---- -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. The interface ValidatingManagedConnectionFactory exposes the method @@ -382,7 +382,7 @@ click the Help button in the Administration Console. ---- asadmin set server.connector-service.shutdown-timeout-in-seconds="num-secs" ---- -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. The {productName} deactivates all message-driven bean deployments @@ -408,7 +408,7 @@ To configure this setting, use the `asadmin set` command. For example: asadmin set server.connector-service.class-loading-policy="global" ---- -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. [[using-last-agent-optimization-of-transactions]] @@ -451,7 +451,7 @@ Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--pooling` option in the `asadmin create-connector-connection-pool` command. For more -information, see the xref:reference-manual.adoc#GSRFM[{productName} +information, see the xref:reference-manual.adoc#create-connector-connection-pool[{productName} Reference Manual]. [[using-application-scoped-connectors]] diff --git a/docs/application-development-guide/src/main/asciidoc/container_managed-persistence.adoc b/docs/application-development-guide/src/main/asciidoc/container_managed-persistence.adoc index c62b89ddbd2..46752cd9a5b 100644 --- a/docs/application-development-guide/src/main/asciidoc/container_managed-persistence.adoc +++ b/docs/application-development-guide/src/main/asciidoc/container_managed-persistence.adoc @@ -261,7 +261,7 @@ To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC Driver for Oracle Databases, you must set the `streamstolob` property value to `true`. -For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release +For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. @@ -302,7 +302,7 @@ To use BLOB or CLOB data types larger than 4 KB for CMP using the Inet Oraxo JDBC Driver for Oracle Databases, you must set the `streamstolob` property value to `true`. -For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release +For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. @@ -426,7 +426,7 @@ type (or a collection of such) can be the type of a CMR field. The following table contains the mappings of JDBC types to database vendor-specific types when automatic mapping is used. For a list of the JDBC drivers currently supported by the {productName}, see the -xref:release-notes.adoc#GSRLN[{productName} Release Notes]. For +xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. @@ -643,7 +643,7 @@ in `glassfish-ejb-jar.xml` is used. For more information about the `asadmin deploy`, `asadmin deploydir`, -and `asadmin undeploy` commands, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +and `asadmin undeploy` commands, see the xref:reference-manual.adoc#deploy[{productName} Reference Manual]. When command line and `glassfish-ejb-jar.xml` options are both specified, the `asadmin` options take precedence. @@ -682,7 +682,7 @@ properly configured CMP resource. See xref:#configuring-the-cmp-resource[Configu You can use the `capture-schema` command to manually generate the database metadata (`.dbschema`) file. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#capture-schema[{productName} Reference Manual]. The `capture-schema` utility does not modify the schema in any way. Its only purpose is to provide the persistence engine with information about @@ -721,7 +721,7 @@ In the Administration Console, open the Resources component, then select JDBC. Click the Help button in the Administration Console for information on creating a new JDBC resource. -For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release +For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. diff --git a/docs/application-development-guide/src/main/asciidoc/debugging-apps.adoc b/docs/application-development-guide/src/main/asciidoc/debugging-apps.adoc index a4a2d5b4fae..935d16a9fb9 100644 --- a/docs/application-development-guide/src/main/asciidoc/debugging-apps.adoc +++ b/docs/application-development-guide/src/main/asciidoc/debugging-apps.adoc @@ -113,7 +113,7 @@ To generate a Java stack trace for debugging, use the `asadmin generate-jvm-report --type=thread` command. The stack trace goes to the domain-dir`/logs/server.log` file and also appears on the command prompt screen. For more information about the -`asadmin generate-jvm-report` command, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +`asadmin generate-jvm-report` command, see the xref:reference-manual.adoc#generate-jvm-report[{productName} Reference Manual]. [[application-client-debugging]] @@ -139,7 +139,7 @@ debugging both concurrently. For details about setting the port, see xref:#jpda-options[JPDA Options]. You can also include JVM options in the `appclient` script directly. For -information about the `appclient` script, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +information about the `appclient` script, see the xref:reference-manual.adoc#appclient[{productName} Reference Manual]. [NOTE] diff --git a/docs/application-development-guide/src/main/asciidoc/ejb.adoc b/docs/application-development-guide/src/main/asciidoc/ejb.adoc index 4a965003f8e..579049499e9 100644 --- a/docs/application-development-guide/src/main/asciidoc/ejb.adoc +++ b/docs/application-development-guide/src/main/asciidoc/ejb.adoc @@ -241,7 +241,7 @@ preconfigured to use an embedded version of the Apache Derby database. The EJB Timer Service configuration can store persistent timer information in any database supported by the {productName} for persistence. For a list of the JDBC drivers currently supported by the -{productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release Notes]. For configurations of supported and other +{productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. @@ -300,7 +300,7 @@ in {productName} Administration Guide. For information about the `asadmin list-timers` and -`asadmin migrate-timers` subcommands, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. For information about +`asadmin migrate-timers` subcommands, see the xref:reference-manual.adoc#list-timers[{productName} Reference Manual]. For information about migrating EJB timers, see "xref:ha-administration-guide.adoc#migrating-ejb-timers[Migrating EJB Timers]" in {productName} High Availability Administration Guide. @@ -322,7 +322,7 @@ the newly redeployed application retrieves the EJB timers that correspond to these IDs from the timer database. For more information about the `asadmin redeploy` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#redeploy[{productName} Reference Manual]. [[to-deploy-an-ejb-timer-to-a-cluster]] @@ -455,10 +455,6 @@ The {productName} specific deployment descriptor file, For more information about `glassfish-ejb-jar.xml`, see "xref:application-deployment-guide.adoc#GSDPG00079[The glassfish-ejb-jar.xml File]" in {productName} Application Deployment Guide. -The {productName} provides the `wscompile` and `wsdeploy` tools to -help you implement a web service endpoint as a stateless session bean. -For more information about these tools, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. - [[stateful-container]] ===== Stateful Container @@ -665,7 +661,7 @@ Service box. All instances in an {productName} cluster should have the same availability settings to ensure consistent behavior. For more information about SFSB state persistence, see the -xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability +xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. [[using-the---keepstate-option]] @@ -693,7 +689,7 @@ saves it in memory. To restore the data, the class loader of the newly redeployed application deserializes the data that was previously saved. For more information about the `asadmin redeploy` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#redeploy[{productName} Reference Manual]. [[using-the---asyncreplication-option]] @@ -710,7 +706,7 @@ availability is guaranteed. States are not buffered but immediately transmitted to other instances in the cluster. For more information about the `asadmin deploy` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#deploy[{productName} Reference Manual]. [[enabling-checkpointing]] @@ -736,7 +732,7 @@ Application and EJB Module Levels To enable SFSB checkpointing at the application or EJB module level during deployment, use the `asadmin deploy` or `asadmin deploydir` command with the `--availabilityenabled` option set to `true`. For -details, see the xref:reference-manual.adoc#GSRFM[{productName} +details, see the xref:reference-manual.adoc#deploy[{productName} Reference Manual]. [[sfsb-level]] @@ -1274,7 +1270,7 @@ asadmin set server-config.mdb-container.property.cmt-max-runtime-exceptions="5" ---- For more information about the `asadmin set` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#set[{productName} Reference Manual]. The `cmt-max-runtime-exceptions` property specifies the maximum number of runtime exceptions allowed from a message-driven bean's `onMessage` diff --git a/docs/application-development-guide/src/main/asciidoc/java-clients.adoc b/docs/application-development-guide/src/main/asciidoc/java-clients.adoc index 33b2029eaa2..2909e0b06c5 100644 --- a/docs/application-development-guide/src/main/asciidoc/java-clients.adoc +++ b/docs/application-development-guide/src/main/asciidoc/java-clients.adoc @@ -183,12 +183,12 @@ see xref:jndi.adoc#mapping-references[Mapping References]. 3. Deploy the application client and EJB component together in an application. + For more information on deployment, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. To get the client JAR file, use the `--retrieve` option of the `asadmin deploy` command. + To retrieve the stubs and ties generated during deployment, use the `asadmin get-client-stubs` command. + For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#get-client-stubs[{productName} Reference Manual]. 4. Ensure that the client JAR file includes the following files: * A Java class to access the bean. @@ -210,7 +210,7 @@ system files required to launch application clients on remote systems using the `package-appclient` script, then retrieve the application client itself using the `asadmin get-client-stubs` command. + For more information, see xref:#using-the-package-appclient-script[Using the `package-appclient` Script] -and the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +and the xref:reference-manual.adoc#package-appclient[{productName} Reference Manual]. 6. To access EJB components that are residing in a remote system, make the following changes to the `sun-acc.xml` file or the `appclient` @@ -229,7 +229,7 @@ To determine the ORB port on the remote server, use the `asadmin get` command. F asadmin --host rmtsrv get server-config.iiop-service.iiop-listener.iiop-listener1.port ---- For more information about the `asadmin get` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#get[{productName} Reference Manual]. 7. [[accejb8]] To set up load balancing and failover of remote EJB references, define @@ -305,7 +305,7 @@ using the `package-appclient` script, then retrieve the application client itself using the `asadmin get-client-stubs` command. + For more information, see xref:#using-the-package-appclient-script[Using the `package-appclient` -Script] and the xref:reference-manual.adoc#GSRFM[{productName} +Script] and the xref:reference-manual.adoc#appclient[{productName} Reference Manual]. 6. Run the application client. + @@ -338,7 +338,7 @@ Java Web Start is enabled for all application clients by default. The application developer or deployer can specify that Java Web Start is always disabled for an application client by setting the value of the `eligible` element to `false` in the `glassfish-application-client.xml` -file. See the xref:application-deployment-guide.adoc#GSDPG[{productName} +file. See the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. The {productName} administrator can disable Java Web Start for a @@ -363,7 +363,7 @@ asadmin set applications.application.module-name.property.java-web-start-enabled Setting `java-web-start-enabled="true"` re-enables Java Web Start for an eligible application client. For more information about the -`asadmin set` command, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +`asadmin set` command, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. [[downloading-and-launching-an-application-client]] @@ -438,7 +438,7 @@ naming, see "xref:application-deployment-guide.adoc#naming-standards[Naming Stan To set a different URL for an application client, use the `context-root` subelement of the `java-web-start-access` element in the `glassfish-application-client.xml` file. This overrides the -appclient-module-id or application-id. See the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +appclient-module-id or application-id. See the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. You can also pass arguments to the ACC or to the application client's `main` method as query parameters in the URL. If multiple application @@ -629,7 +629,7 @@ asadmin deploy --property jar-signing-alias=MyAlias MyApp.ear ---- For more information about the `asadmin deploy` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#deploy[{productName} Reference Manual]. [[error-handling]] @@ -689,7 +689,7 @@ The following example vendor element contains only a text string: The default value is the text string `Application Client`. For more information about the `glassfish-application-client.xml` file, -see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application +see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. You can also specify a vendor-specific icon, splash screen, text string, @@ -1152,7 +1152,7 @@ might not support such serial or concurrent reuse. To run an application client, you can launch the ACC using the `appclient` script, whether or not Java Web Start is enabled. This is optional. This script is located in the as-install``/bin`` directory. For -details, see the xref:reference-manual.adoc#GSRFM[{productName} +details, see the xref:reference-manual.adoc#appclient[{productName} Reference Manual]. [[using-the-package-appclient-script]] @@ -1163,7 +1163,7 @@ You can package the {productName} system files required to launch application clients on remote systems into a single JAR file using the `package-appclient` script. This is optional. This script is located in the as-install``/bin`` directory. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#package-appclient[{productName} Reference Manual]. [[GSDVG00468]][[the-client.policy-file]] @@ -1221,7 +1221,7 @@ ProgrammaticLogin Class] mechanism. ---- For more information about the `glassfish-ejb-jar.xml` and `sun-acc.xml` -files, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +files, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. To use a client certificate, configure the `ior-security-config` element @@ -1369,7 +1369,7 @@ does not apply. In this case, you could write logic to catch an exception around the lookup and retry explicitly. For details about the `appclient` script syntax, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#appclient[{productName} Reference Manual]. [[using-libraries-with-application-clients]] diff --git a/docs/application-development-guide/src/main/asciidoc/jdbc.adoc b/docs/application-development-guide/src/main/asciidoc/jdbc.adoc index c1bf49fe488..0ab833c264f 100644 --- a/docs/application-development-guide/src/main/asciidoc/jdbc.adoc +++ b/docs/application-development-guide/src/main/asciidoc/jdbc.adoc @@ -67,7 +67,7 @@ Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--initsql` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `init-sql` option in the `asadmin set` command. For example: + @@ -75,7 +75,7 @@ example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.init-sql="sql-string" ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. [[setting-a-statement-timeout]] @@ -97,7 +97,7 @@ Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--statementtimeout` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. [[statement-leak-detection-and-leaked-statement-reclamation]] @@ -166,7 +166,7 @@ Advanced Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--statementcachesize` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `statement-cache-size` option in the `asadmin set` command. For example: + @@ -174,7 +174,7 @@ command. For example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.statement-cache-size=10 ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. By default, this attribute is set to zero and the statement caching is turned off. To enable statement caching, you can set any positive @@ -196,7 +196,7 @@ Advanced Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--sqltracelisteners` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `sql-trace-listeners` option in the `asadmin set` command. For example: + @@ -204,7 +204,7 @@ For example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.sql-trace-listeners=listeners ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. The {productName} provides a public interface, org.glassfish.api.jdbc.SQLTraceListener , that implements a means of @@ -325,7 +325,7 @@ page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--pooling` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `pooling` option in the `asadmin set` command. For example: + @@ -333,7 +333,7 @@ example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.pooling=false ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. The `pooling` option and the system property `com.sun.enterprise.connectors.SwitchoffACCConnectionPooling`, which @@ -383,7 +383,7 @@ Advanced Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--associatewiththread` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `associate-with-thread` option in the `asadmin set` command. For example: + @@ -391,7 +391,7 @@ command. For example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.associate-with-thread=true ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. [[custom-connection-validation]] @@ -421,7 +421,7 @@ information, click the Help button in the Administration Console. * Specify the `--isconnectionvalidatereq`, `--validationmethod`, and `--validationclassname` options in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `is-connection-validation-required`, `connection-validation-method`, and `validation-classname` options in the `asadmin set` command. For example: @@ -432,7 +432,7 @@ asadmin set domain1.resources.jdbc-connection-pool.MyPool.is-connection-validati asadmin set domain1.resources.jdbc-connection-pool.MyPool.connection-validation-method=custom-validation asadmin set domain1.resources.jdbc-connection-pool.MyPool.validation-classname=impl-class ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. By default, optimized validation mechanisms are provided for DB2, Apache Derby, MSSQL, MySQL, Oracle, PostgreSQL and Sybase databases. @@ -537,7 +537,7 @@ asadmin set server.resources.jdbc-connection-pool.JCPool1.is-connection-validati asadmin set server.resources.jdbc-connection-pool.JCPool1.property.prefer-validate-over-recreate="true" ---- -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. The interface ValidatingManagedConnectionFactory exposes the method @@ -576,7 +576,7 @@ Advanced Attributes page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--wrapjdbcobjects` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. [[obtaining-a-physical-connection-from-a-wrapped-connection]] @@ -640,7 +640,7 @@ Advanced Attributes page in the Administration Console. The default is Administration Console. * Specify the `--allownoncomponentcallers` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `allow-non-component-callers` option in the `asadmin set` command. For example: + @@ -648,7 +648,7 @@ command. For example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.allow-non-component-callers=true ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. * Create a JDBC resource with a `__pm` suffix. Accessing a `DataSource` using the `Synchronization.beforeCompletion()` diff --git a/docs/application-development-guide/src/main/asciidoc/jndi.adoc b/docs/application-development-guide/src/main/asciidoc/jndi.adoc index 0cb6a468587..52e48b1ffd9 100644 --- a/docs/application-development-guide/src/main/asciidoc/jndi.adoc +++ b/docs/application-development-guide/src/main/asciidoc/jndi.adoc @@ -199,7 +199,7 @@ asadmin> create-jvm-options -Djava.naming.factory.initial=org.glassfish.jndi.cos ---- For details about `asadmin create-jvm-options`, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-jvm-options[{productName} Reference Manual]. Or you can set this property in the code, as follows: @@ -330,7 +330,7 @@ External Resources. For details, click the Help button in the Administration Console. * To create an external JNDI resource, use the `asadmin create-jndi-resource` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-jndi-resource[{productName} Reference Manual]. [[custom-resources]] @@ -348,7 +348,7 @@ Resources component, open the JNDI component, and select Custom Resources. For details, click the Help button in the Administration Console. * To create a custom resource, use the `asadmin create-custom-resource` -command. For details, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +command. For details, see the xref:reference-manual.adoc#create-custom-resource[{productName} Reference Manual]. [[built-in-factories-for-custom-resources]] @@ -366,7 +366,7 @@ Template `glassfish-resources.xml` files for these built-in factories and a `README` file are available at as-install``/lib/install/templates/resources/custom/``. For more information about the `glassfish-resources.xml` file, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[javabeanfactory]] diff --git a/docs/application-development-guide/src/main/asciidoc/jpa.adoc b/docs/application-development-guide/src/main/asciidoc/jpa.adoc index 9e107972eba..b18f768af88 100644 --- a/docs/application-development-guide/src/main/asciidoc/jpa.adoc +++ b/docs/application-development-guide/src/main/asciidoc/jpa.adoc @@ -239,7 +239,7 @@ value="jdbc:derby://localhost:1527/testdb;retrieveMessagesFromServerOnGetMessage ---- -For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc#GSRLN[{productName} Release +For a list of the JDBC drivers currently supported by the {productName}, see the xref:release-notes.adoc[{productName} Release Notes]. For configurations of supported and other drivers, see "xref:administration-guide.adoc#configuration-specifics-for-jdbc-drivers[Configuration Specifics for JDBC Drivers]" in {productName} Administration Guide. @@ -477,7 +477,7 @@ If not specified, tables are dropped only if the For more information about the `asadmin deploy`, `asadmin deploydir`, -and `asadmin undeploy` commands, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +and `asadmin undeploy` commands, see the xref:reference-manual.adoc#deploy[{productName} Reference Manual]. When `asadmin` deployment options and `persistence.xml` options are both specified, the `asadmin` deployment options take precedence. diff --git a/docs/application-development-guide/src/main/asciidoc/lifecycle-listeners.adoc b/docs/application-development-guide/src/main/asciidoc/lifecycle-listeners.adoc index 90831656b26..a62434058ac 100644 --- a/docs/application-development-guide/src/main/asciidoc/lifecycle-listeners.adoc +++ b/docs/application-development-guide/src/main/asciidoc/lifecycle-listeners.adoc @@ -144,9 +144,9 @@ initial context to which all the resources are bound. === Deploying a Lifecycle Module For instructions on how to deploy a lifecycle module, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide], or see the `asadmin create-lifecycle-module` command in the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-lifecycle-module[{productName} Reference Manual]. You do not need to specify a classpath for the lifecycle module if you place it in the domain-dir``/lib`` or domain-dir`/lib/classes` directory diff --git a/docs/application-development-guide/src/main/asciidoc/mail.adoc b/docs/application-development-guide/src/main/asciidoc/mail.adoc index 81dcf4d95d8..dbb9713f190 100644 --- a/docs/application-development-guide/src/main/asciidoc/mail.adoc +++ b/docs/application-development-guide/src/main/asciidoc/mail.adoc @@ -67,7 +67,7 @@ You can create a Jakarta Mail session in the following ways: Jakarta Mail Sessions. For details, click the Help button in the Administration Console. * Use the `asadmin create-mail-resource` command. For details, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-mail-resource[{productName} Reference Manual]. [[jakarta-mail-session-properties]] diff --git a/docs/application-development-guide/src/main/asciidoc/osgi.adoc b/docs/application-development-guide/src/main/asciidoc/osgi.adoc index dfeaf8261da..eed8e72af3a 100644 --- a/docs/application-development-guide/src/main/asciidoc/osgi.adoc +++ b/docs/application-development-guide/src/main/asciidoc/osgi.adoc @@ -249,7 +249,7 @@ availability of JDBC data sources using the `ServiceTracking` facility of the OSGi platform. The life of the OSGi service matches that of the underlying data source created in {productName}. For instructions on administering JDBC resources in {productName}, see the -xref:administration-guide.adoc#GSADG[{productName} Administration Guide]. +xref:administration-guide.adoc[{productName} Administration Guide]. {productName} registers each JDBC data source as an OSGi service with `objectClass = "javax.sql.DataSource"` and a service property called diff --git a/docs/application-development-guide/src/main/asciidoc/preface.adoc b/docs/application-development-guide/src/main/asciidoc/preface.adoc index c96d5f29f9c..b5e34538b76 100644 --- a/docs/application-development-guide/src/main/asciidoc/preface.adoc +++ b/docs/application-development-guide/src/main/asciidoc/preface.adoc @@ -51,24 +51,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -81,45 +81,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -132,7 +132,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/application-development-guide/src/main/asciidoc/securing-apps.adoc b/docs/application-development-guide/src/main/asciidoc/securing-apps.adoc index 0832d669b94..5e10b75a35a 100644 --- a/docs/application-development-guide/src/main/asciidoc/securing-apps.adoc +++ b/docs/application-development-guide/src/main/asciidoc/securing-apps.adoc @@ -14,7 +14,7 @@ This chapter describes how to write secure Jakarta EE applications, which contain components that perform user authentication and access authorization for the business logic of Jakarta EE components. -For information about administrative security for the {productName}, see the xref:security-guide.adoc#GSSCG[{productName} +For information about administrative security for the {productName}, see the xref:security-guide.adoc[{productName} Server Security Guide]. For general information about Jakarta EE security, see @@ -132,7 +132,7 @@ The {productName} supports the deployment descriptors specified by Jakarta EE and has additional security elements included in its own deployment descriptors. Declarative security is the application deployer's responsibility. For more information about {productName} -deployment descriptors, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +deployment descriptors, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. There are two levels of declarative security, as follows: @@ -284,7 +284,7 @@ access in the following ways: relevant configuration. For details, click the Help button in the Administration Console. * Use the `asadmin set` command. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. For +xref:reference-manual.adoc#set[{productName} Reference Manual]. For example, you can set the default principal as follows. + [source] @@ -349,7 +349,7 @@ You can configure a realm in one of these ways: relevant configuration and go to the Realms page. For details, click the Help button in the Administration Console. * Use the `asadmin create-auth-realm` command to configure realms on -local servers. For details, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +local servers. For details, see the xref:reference-manual.adoc#create-auth-realm[{productName} Reference Manual]. [[how-to-set-a-realm-for-an-application-or-module]] @@ -659,7 +659,7 @@ Security component under the relevant configuration, and select the Audit Modules component. For details, click the Help button in the Administration Console. * You can use the `asadmin create-audit-module` command to configure an -audit module. For details, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +audit module. For details, see the xref:reference-manual.adoc#create-audit-module[{productName} Reference Manual]. [[the-auditmodule-class]] @@ -790,7 +790,7 @@ The following predefined system properties, also called variables, are available for use in the `server.policy` file. The system property most frequently used in `server.policy` is `${com.sun.aas.instanceRoot}`. For more information about system properties, see the -`asadmin create-system-properties` command in the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +`asadmin create-system-properties` command in the xref:reference-manual.adoc#create-system-properties[{productName} Reference Manual]. [[GSDVG533]] @@ -953,7 +953,7 @@ asadmin create-jvm-options -Djava.security.debug=failure ---- For more information about the `asadmin create-jvm-options` command, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jvm-options[{productName} Reference Manual]. You can use the J2SE standard `policytool` or any text editor to edit the `server.policy` file. For more information, see @@ -1007,7 +1007,7 @@ asadmin create-jvm-options -Djava.security.manager To disable the security manager, uncheck the Security Manager Enabled box or use the corresponding `asadmin delete-jvm-options` command. For more information about `create-jvm-options` and `delete-jvm-options`, -see the xref:reference-manual.adoc#GSRFM[{productName} Reference +see the xref:reference-manual.adoc#create-jvm-options[{productName} Reference Manual]. If the security manager is enabled and you are using the Java @@ -1092,7 +1092,7 @@ For more information about message security, see the following: * "https://jakarta.ee/learn/docs/jakartaee-tutorial/current/security/security.html[Introduction to Security in the Jakarta EE Platform]" in The Jakarta EE Tutorial -* xref:security-guide.adoc#GSSCG[{productName} Server Security Guide] +* xref:security-guide.adoc[{productName} Server Security Guide] * http://www.jcp.org/en/jsr/detail?id=196[JSR 196] (`http://www.jcp.org/en/jsr/detail?id=196`), Java Authentication Service Provider Interface for Containers @@ -1138,7 +1138,7 @@ asadmin set server-config.security-service.message-security-config.SOAP.default_client_provider=XWS_ClientProvider ---- For more information about the `asadmin set` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#set[{productName} Reference Manual]. The example described in xref:#understanding-and-running-the-sample-application[Understanding and Running the Sample Application] uses the `ClientProvider` and `ServerProvider` @@ -1168,10 +1168,10 @@ The WS-I BSP specification can be viewed at `http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html`. For more information about the {productName} deployment descriptor -files, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +files, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. -For information about configuring these providers in the {productName}, see the xref:security-guide.adoc#GSSCG[{productName} +For information about configuring these providers in the {productName}, see the xref:security-guide.adoc[{productName} Server Security Guide]. For additional information about overriding provider settings, see xref:#application-specific-message-protection[Application-Specific Message Protection]. @@ -1183,7 +1183,7 @@ and select the Message Security component. For details, click the Help button in the Administration Console. * You can use the `asadmin create-message-security-provider` command to create a message security provider. For details, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#create-message-security-provider[{productName} Reference Manual]. In addition, you can set a few optional provider properties using the `asadmin set` command. For example: @@ -1310,7 +1310,7 @@ databases. Certificates and private keys are stored in key stores and are managed with `keytool`. If Network Security Services (NSS) is installed, certificates and private keys are stored in an NSS database, where they are managed using `certutil`. System administrator tasks are -discussed in the xref:security-guide.adoc#GSSCG[{productName} +discussed in the xref:security-guide.adoc[{productName} Server Security Guide]. [[application-specific-message-protection]] @@ -1364,7 +1364,7 @@ update the `message-security-binding` element for the EJB web service endpoint in the application's `glassfish-ejb-jar.xml` file. In this file, add `request-protection` and `response-protection` elements, which are analogous to the `request-policy` and `response-policy` elements -discussed in the xref:security-guide.adoc#GSSCG[{productName} +discussed in the xref:security-guide.adoc[{productName} Server Security Guide]. To apply the same protection mechanisms for all methods, leave the method-name element blank. xref:#configuring-message-protection-for-a-specific-method-based-on-digital-signatures[Configuring Message Protection for a Specific Method Based on Digital Signatures] @@ -1428,7 +1428,7 @@ the EJB web service endpoint in the application's `glassfish-ejb-jar.xml` file. To this file, add `request-protection` and `response-protection` elements, which are analogous to the `request-policy` and `response-policy` elements discussed in the -xref:security-guide.adoc#GSSCG[{productName} Server Security Guide]. The +xref:security-guide.adoc[{productName} Server Security Guide]. The administration guide includes a table listing the set and order of security operations for different request and response policy configurations. @@ -1870,7 +1870,7 @@ asadmin set server-config.http-service.virtual-server.vsrv1.property.sso-reap-in ---- For more information about the `asadmin set` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#set[{productName} Reference Manual]. [[adding-authentication-mechanisms-to-the-servlet-container]] @@ -2483,7 +2483,7 @@ configure a SAM. Set the following options: ** Provider name operand — Specify a unique name for the SAM, for example `MySAM` + -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#create-message-security-provider[{productName} Reference Manual]. [[binding-a-server-authentication-module-to-your-application]] @@ -2500,7 +2500,7 @@ using the `glassfish-web.xml` file. Set the value of the `httpservlet-security-provider` attribute of the `glassfish-web-app` element to the SAM's configured provider ID, for example, `MySAM`. For more information about the `glassfish-web.xml` file, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. This option leverages the native `AuthConfigProvider` implementation that ships with the {productName}. * Another approach is to develop your own `AuthConfigProvider` and diff --git a/docs/application-development-guide/src/main/asciidoc/setting-up-dev-env.adoc b/docs/application-development-guide/src/main/asciidoc/setting-up-dev-env.adoc index 2b2af0d339b..f5afe628117 100644 --- a/docs/application-development-guide/src/main/asciidoc/setting-up-dev-env.adoc +++ b/docs/application-development-guide/src/main/asciidoc/setting-up-dev-env.adoc @@ -28,7 +28,7 @@ The following topics are addressed here: === Installing and Preparing the Server for Development For more information about {productName} installation, see the -xref:installation-guide.adoc#GSING[ +xref:installation-guide.adoc[ {productName} Installation Guide]. The following components are included in the full installation. @@ -67,7 +67,7 @@ in {productName} Administration Guide. === High Availability Features High availability features such as load balancing and session failover -are discussed in detail in the xref:ha-administration-guide.adoc#GSHAG[{productName} +are discussed in detail in the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. This book describes the following features in the following sections: @@ -107,7 +107,7 @@ The following third-party tools might also be useful: The `asadmin` command allows you to configure a local or remote server and perform both administrative and development tasks at the command line. For general information about `asadmin`, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#asadmin[{productName} Reference Manual]. The `asadmin` command is located in the as-install``/bin`` directory. Type `asadmin help` for a list of subcommands. diff --git a/docs/application-development-guide/src/main/asciidoc/transaction-service.adoc b/docs/application-development-guide/src/main/asciidoc/transaction-service.adoc index fddccf0115d..bf4bb917a45 100644 --- a/docs/application-development-guide/src/main/asciidoc/transaction-service.adoc +++ b/docs/application-development-guide/src/main/asciidoc/transaction-service.adoc @@ -81,7 +81,7 @@ Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--isolationlevel` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `transaction-isolation-level` option in the `asadmin set` command. For example: + @@ -89,7 +89,7 @@ command. For example: ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.transaction-isolation-level=serializable ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. Note that you cannot call `setTransactionIsolation` during a transaction. @@ -135,7 +135,7 @@ Pool or Edit Connection Pool page in the Administration Console. For more information, click the Help button in the Administration Console. * Specify the `--isisolationguaranteed` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `is-isolation-level-guaranteed` option in the `asadmin set` command. For example: + @@ -143,7 +143,7 @@ the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.is-isolation-level-guaranteed=true ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. [[using-non-transactional-connections]] @@ -158,7 +158,7 @@ default is unchecked. For more information, click the Help button in the Administration Console. * Specify the `--nontransactionalconnections` option in the `asadmin create-jdbc-connection-pool` command. For more information, see -the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +the xref:reference-manual.adoc#create-jdbc-connection-pool[{productName} Reference Manual]. * Specify the `non-transactional-connections` option in the `asadmin set` command. For example: + @@ -166,7 +166,7 @@ the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. ---- asadmin set domain1.resources.jdbc-connection-pool.DerbyPool.non-transactional-connections=true ---- -For more information, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +For more information, see the xref:reference-manual.adoc#set[{productName} Reference Manual]. * Use the `DataSource` implementation in the {productName}, which provides a `getNonTxConnection` method. This method retrieves a JDBC connection that is not in the scope of any transaction. There are two diff --git a/docs/application-development-guide/src/main/asciidoc/webapps.adoc b/docs/application-development-guide/src/main/asciidoc/webapps.adoc index 7e446925399..a46b6c01ab6 100644 --- a/docs/application-development-guide/src/main/asciidoc/webapps.adoc +++ b/docs/application-development-guide/src/main/asciidoc/webapps.adoc @@ -55,10 +55,6 @@ To develop servlets, use the Java Servlet API. For information about using the Java Servlet API, see the documentation at `https://jakarta.ee/specifications/servlet/`. -The {productName} provides the `wscompile` and `wsdeploy` tools to -help you implement a web service endpoint as a servlet. For more -information about these tools, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. - This section describes how to create effective servlets to control application interactions running on a {productName}, including standard-based servlets. In addition, this section describes the @@ -378,7 +374,7 @@ asadmin set server-config.web-container.property.jspCachingEnabled="true" ---- For more information about the `asadmin set` command, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#set[{productName} Reference Manual]. To enable JSP caching for a single web application, follow these steps: @@ -588,10 +584,10 @@ files into servlets: * JSP files are automatically compiled at runtime. * The `asadmin deploy` command has a `--precompilejsp` option. For -details, see the xref:reference-manual.adoc#GSRFM[{productName} +details, see the xref:reference-manual.adoc#deploy[{productName} Reference Manual]. -* The `jspc` command line tool allows you to precompile JSP files at the -command line. For details, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +* The `jspc` command line tool in `glassfish/bin` allows you to precompile JSP files at the +command line. For details, run `glassfish/bin/jspc -help` [[creating-and-managing-sessions]] @@ -631,7 +627,7 @@ application. For more about the properties you can configure, see For information about configuring default session properties for the entire web container, see xref:#GSDVG00410[Using the `default-web.xml` File] -and the xref:ha-administration-guide.adoc#GSHAG[{productName} High +and the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. [[coordinating-session-access]] @@ -667,7 +663,7 @@ become invalid unless you use the `--keepstate=true` option of the asadmin redeploy --keepstate=true --name hello.war ---- -For details, see the xref:reference-manual.adoc#GSRFM[{productName} +For details, see the xref:reference-manual.adoc#redeploy[{productName} Reference Manual]. The default for `--keepstate` is false. This option is supported only on @@ -723,7 +719,7 @@ session persistence type reverts to `memory`. See xref:#the-replicated-persisten listed in xref:#fvyem[Table 7-3]. * The web application must be deployed using the `deploy` or `deploydir` command with the `--availabilityenabled` option set to `true`. See the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc#deploy[{productName} Reference Manual]. [NOTE] @@ -746,7 +742,7 @@ list of the types of references that `HTTPSession` failover supports. * References to open files or network connections are lost. For information about how to work around these limitations, see the -xref:deployment-planning-guide.adoc#GSPLG[{productName} Deployment Planning +xref:deployment-planning-guide.adoc[{productName} Deployment Planning Guide]. In the following table, No indicates that failover for the object type @@ -868,7 +864,7 @@ this behavior, specify an empty string as the value of `sessionFilename`. The default value is an empty string. For more information about the `glassfish-web.xml` file, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[the-file-persistence-type]] @@ -921,7 +917,7 @@ and supports the `directory` store property listed under "xref:application-deployment-guide.adoc#store-properties[store-properties]" in {productName} Application Deployment Guide. For more information about the `glassfish-web.xml` file, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[the-replicated-persistence-type]] @@ -944,7 +940,7 @@ Service box. To enable availability for the web container, select the Web Container Availability tab, then check the Availability Service box. All instances in an {productName} cluster should have the same availability settings to ensure consistent behavior. For details, see -the xref:ha-administration-guide.adoc#GSHAG[{productName} High Availability +the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. To change settings such as persistence frequency and persistence scope @@ -960,7 +956,7 @@ server-config.availability-service.web-container-availability.persistence-freque ---- For more information, see the description of the `asadmin set` command -in the xref:reference-manual.adoc#GSRFM[{productName} Reference +in the xref:reference-manual.adoc#set[{productName} Reference Manual]. To specify the `replicated` persistence type for a specific web @@ -994,7 +990,7 @@ listed under "xref:application-deployment-guide.adoc#manager-properties[manager- listed under "xref:application-deployment-guide.adoc#store-properties[store-properties]" in {productName} Application Deployment Guide. For more information about the `glassfish-web.xml` file, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. To specify that web sessions for which high availability is enabled are @@ -1356,7 +1352,7 @@ http://localhost:8080/cometd/index.html See Also For more information about deployment in the {productName}, see the -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. For more information about the Bayeux protocol, see @@ -1495,7 +1491,7 @@ The default value is `delegate="true"`, which causes the web application class loader to delegate in the same manner as the other class loaders. Use `delegate="true"` for a web application that accesses EJB components or that acts as a web service client or endpoint. For details about -`glassfish-web.xml`, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +`glassfish-web.xml`, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. For a number of packages, including `java.*` and `javax.*`, symbol resolution is always delegated to the parent class loader regardless of @@ -2107,7 +2103,7 @@ To work with a native executable, do the following: 3. Use directory deployment to deploy the web module. Do not deploy it as a WAR file, because the executable bit information is lost during the process of `jar` and `unjar`. For more information about directory -deployment, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +deployment, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. diff --git a/docs/application-development-guide/src/main/asciidoc/webservices.adoc b/docs/application-development-guide/src/main/asciidoc/webservices.adoc index 7ff40c5e60f..60a8384f635 100644 --- a/docs/application-development-guide/src/main/asciidoc/webservices.adoc +++ b/docs/application-development-guide/src/main/asciidoc/webservices.adoc @@ -89,10 +89,10 @@ The test page feature is enabled by default and described in xref:#the-web-service-uri-wsdl-file-and-test-page[The Web Service URI, WSDL File, and Test Page]. For more information about deployment, autodeployment, and deployment -descriptors, see the xref:application-deployment-guide.adoc#GSDPG[ +descriptors, see the xref:application-deployment-guide.adoc[ {productName} Application Deployment Guide]. For more information about the -`asadmin deploy` command, see the xref:reference-manual.adoc#GSRFM[ +`asadmin deploy` command, see the xref:reference-manual.adoc#deploy[ {productName} Reference Manual]. [[the-web-service-uri-wsdl-file-and-test-page]] @@ -154,7 +154,7 @@ Generation of the test page is enabled by default. You can disable the test page for a web service by setting the value of the `debugging-enabled` element in the `glassfish-web.xml` and `glassfish-ejb-jar.xml` deployment descriptor to `false`. For more -information, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +information, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[the-databinding-provider]] diff --git a/docs/deployment-planning-guide/src/main/asciidoc/checklist.adoc b/docs/deployment-planning-guide/src/main/asciidoc/checklist.adoc index c39269b2a9e..8ad74849255 100644 --- a/docs/deployment-planning-guide/src/main/asciidoc/checklist.adoc +++ b/docs/deployment-planning-guide/src/main/asciidoc/checklist.adoc @@ -29,7 +29,7 @@ a|Determine the following requirements for the application to be deployed. * Session timeout in `web.xml`. * Failover and availability requirements. -For more information see the xref:performance-tuning-guide.adoc#GSPTG[ +For more information see the xref:performance-tuning-guide.adoc[ {productName} Performance Tuning Guide]. |Hardware @@ -37,14 +37,14 @@ a| * Have necessary amounts of hard disk space and memory installed. * Use the sizing exercise to identify the requirements for deployment. -For more information see the xref:release-notes.adoc#GSRLN[{productName} Release Notes] +For more information see the xref:release-notes.adoc[{productName} Release Notes] |Operating System a| * Ensure that the product is installed on a supported platform. * Ensure that the patch levels are up-to-date and accurate. -For more information see the xref:release-notes.adoc#GSRLN[{productName} Release Notes] +For more information see the xref:release-notes.adoc[{productName} Release Notes] |Network Infrastructure a| @@ -53,7 +53,7 @@ a| * Run `ttcp` benchmark test to determine if the throughput meets the requirements/expected result. * Setup `ssh` based your preference. -For more information see the xref:installation-guide.adoc#GSING[{productName} Installation Guide]. +For more information see the xref:installation-guide.adoc[{productName} Installation Guide]. |Back-ends and other external data sources |Check with the domain expert or vendor to ensure that these data sources @@ -70,7 +70,7 @@ a| * On Solaris, use `Setoolkit` to determine the behavior of the system. Resolve any flags that show up. -For more information see the xref:performance-tuning-guide.adoc#GSPTG[{productName} Performance Tuning Guide]. +For more information see the xref:performance-tuning-guide.adoc[{productName} Performance Tuning Guide]. |Installation a| @@ -88,9 +88,9 @@ a| and they are not overridden underneath in the individual Web/EJB modules. * Ensure that only critical methods in the SFSB are checkpointed. -For more information on tuning, see the xref:performance-tuning-guide.adoc#GSPTG[{productName} Performance Tuning Guide]. +For more information on tuning, see the xref:performance-tuning-guide.adoc[{productName} Performance Tuning Guide]. -For more information on configuration, see the xref:administration-guide.adoc#GSADG[{productName} Administration Guide]. +For more information on configuration, see the xref:administration-guide.adoc[{productName} Administration Guide]. |Load balancer Configuration a| diff --git a/docs/deployment-planning-guide/src/main/asciidoc/concepts.adoc b/docs/deployment-planning-guide/src/main/asciidoc/concepts.adoc index 8fc08021ead..834b4379514 100644 --- a/docs/deployment-planning-guide/src/main/asciidoc/concepts.adoc +++ b/docs/deployment-planning-guide/src/main/asciidoc/concepts.adoc @@ -524,7 +524,7 @@ For more information, see xref:planning.adoc#design-decisions[Design Decisions]. 3. Install {productName} and related subcomponents such as a web server. + For more information, see the following documentation: -* xref:installation-guide.adoc#GSING[{productName} Installation Guide] +* xref:installation-guide.adoc[{productName} Installation Guide] * Installation guides for related subcomponents, for example, Oracle iPlanet Web Server 7.0.9 Installation and Migration Guide (`http://docs.oracle.com/cd/E19146-01/821-1832/index.html`) @@ -564,4 +564,4 @@ Guide * link:{mq-admin-guide-url}[Open Message Queue Administration Guide] 9. Deploy applications and configure them for high availability and session failover. + -For more information, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +For more information, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. diff --git a/docs/deployment-planning-guide/src/main/asciidoc/planning.adoc b/docs/deployment-planning-guide/src/main/asciidoc/planning.adoc index e58f6f4a8c4..9c9a43e3d75 100644 --- a/docs/deployment-planning-guide/src/main/asciidoc/planning.adoc +++ b/docs/deployment-planning-guide/src/main/asciidoc/planning.adoc @@ -804,7 +804,7 @@ Use the following `asadmin` commands: ** `asadmin list-jms-resources` + -For more information on these commands, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual] or the corresponding man pages. +For more information on these commands, see the xref:reference-manual.adoc[{productName} Reference Manual] or the corresponding man pages. [[default-jms-host]] diff --git a/docs/deployment-planning-guide/src/main/asciidoc/preface.adoc b/docs/deployment-planning-guide/src/main/asciidoc/preface.adoc index ce4cbfcc58b..09a86614881 100644 --- a/docs/deployment-planning-guide/src/main/asciidoc/preface.adoc +++ b/docs/deployment-planning-guide/src/main/asciidoc/preface.adoc @@ -40,24 +40,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -70,45 +70,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -121,7 +121,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/embedded-server-guide/src/main/asciidoc/embedded-server-guide.adoc b/docs/embedded-server-guide/src/main/asciidoc/embedded-server-guide.adoc index 94a75d6adc7..63d407da0a5 100644 --- a/docs/embedded-server-guide/src/main/asciidoc/embedded-server-guide.adoc +++ b/docs/embedded-server-guide/src/main/asciidoc/embedded-server-guide.adoc @@ -61,7 +61,7 @@ integration tests as part of the build process. [NOTE] ==== For information on how to embed {productName} in an OSGi environment, -see the xref:add-on-component-development-guide.adoc#GSACG[{productName} Add-On +see the xref:add-on-component-development-guide.adoc[{productName} Add-On Component Development Guide]. ==== @@ -854,7 +854,7 @@ Table 1-9 `embedded-glassfish:stop` Parameters This goal runs a {productName} administration command. You must use either the command and commandParameters parameters in combination or the commandLine parameter. For more information about administration -commands, see the xref:reference-manual.adoc#GSRFM[{productName} +commands, see the xref:reference-manual.adoc[{productName} Reference Manual]. You can set the parameters described in the following table. @@ -1198,7 +1198,7 @@ The following topics are addressed here: * xref:#creating-a-scattered-archive[Creating a Scattered Archive] * xref:#creating-a-scattered-enterprise-archive[Creating a Scattered Enterprise Archive] -For general information about deploying applications in {productName}, see the xref:application-deployment-guide.adoc#GSDPG[{productName} +For general information about deploying applications in {productName}, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[to-deploy-an-application-from-an-archive-file-or-a-directory]] @@ -1592,9 +1592,9 @@ required `asadmin` commands to create a JDBC technology connection to a database. For more information about configuring embedded {productName}, see -the xref:administration-guide.adoc#GSADG[{productName} Administration +the xref:administration-guide.adoc[{productName} Administration Guide]. For detailed information about `asadmin` commands, see Section 1 -of the xref:reference-manual.adoc#GSRFM[{productName} Reference +of the xref:reference-manual.adoc[{productName} Reference Manual]. diff --git a/docs/embedded-server-guide/src/main/asciidoc/preface.adoc b/docs/embedded-server-guide/src/main/asciidoc/preface.adoc index ea4b8f1f8fd..1f93c96c5f1 100644 --- a/docs/embedded-server-guide/src/main/asciidoc/preface.adoc +++ b/docs/embedded-server-guide/src/main/asciidoc/preface.adoc @@ -50,24 +50,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -80,45 +80,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -131,7 +131,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/error-messages-reference/src/main/asciidoc/error-messages.adoc b/docs/error-messages-reference/src/main/asciidoc/error-messages.adoc index a03aaf13f88..1b766b1e65b 100644 --- a/docs/error-messages-reference/src/main/asciidoc/error-messages.adoc +++ b/docs/error-messages-reference/src/main/asciidoc/error-messages.adoc @@ -23,7 +23,7 @@ Viewer. For more information about logging, see xref:administration-guide.adoc#administering-the-logging-service[Administering the Logging Service] in {productName} Administration Guide. For additional troubleshooting information, see the -xref:troubleshooting-guide.adoc#GSTSG[{productName} Server Troubleshooting Guide]. +xref:troubleshooting-guide.adoc[{productName} Server Troubleshooting Guide]. Error messages in this chapter are listed in alphabetic and numeric order by message ID. The text is as it appears in the actual error diff --git a/docs/error-messages-reference/src/main/asciidoc/preface.adoc b/docs/error-messages-reference/src/main/asciidoc/preface.adoc index 88b065435de..46f29b1055c 100644 --- a/docs/error-messages-reference/src/main/asciidoc/preface.adoc +++ b/docs/error-messages-reference/src/main/asciidoc/preface.adoc @@ -47,24 +47,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -77,45 +77,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -128,7 +128,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/ha-administration-guide/src/main/asciidoc/instances.adoc b/docs/ha-administration-guide/src/main/asciidoc/instances.adoc index cca5271af0d..042d4d01af9 100644 --- a/docs/ha-administration-guide/src/main/asciidoc/instances.adoc +++ b/docs/ha-administration-guide/src/main/asciidoc/instances.adoc @@ -447,7 +447,7 @@ typing `asadmin help start-cluster` at the command line. Next Steps After starting a cluster, you can deploy applications to the cluster. -For more information, see xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +For more information, see xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[to-stop-a-cluster]] @@ -567,7 +567,7 @@ typing `asadmin help start-instance` at the command line. Next Steps After starting an instance, you can deploy applications to the instance. -For more information, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +For more information, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[to-stop-an-individual-instance-centrally]] @@ -1094,7 +1094,7 @@ typing `asadmin help start-local-instance` at the command line. Next Steps After starting an instance, you can deploy applications to the instance. -For more information, see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment Guide]. +For more information, see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[to-stop-an-individual-instance-locally]] diff --git a/docs/ha-administration-guide/src/main/asciidoc/overview.adoc b/docs/ha-administration-guide/src/main/asciidoc/overview.adoc index 7ac7776e56b..54828abdb46 100644 --- a/docs/ha-administration-guide/src/main/asciidoc/overview.adoc +++ b/docs/ha-administration-guide/src/main/asciidoc/overview.adoc @@ -410,7 +410,7 @@ production environments. For information about planning a high-availability deployment, including assessing hardware requirements, planning network configuration, and -selecting a topology, see the xref:deployment-planning-guide.adoc#GSPLG[{productName} Deployment Planning Guide]. This manual also provides a +selecting a topology, see the xref:deployment-planning-guide.adoc[{productName} Deployment Planning Guide]. This manual also provides a high-level introduction to concepts such as: * {productName} components such as node agents, domains, and clusters @@ -418,10 +418,10 @@ high-level introduction to concepts such as: * Message queue failover For more information about developing applications that take advantage -of high availability features, see the xref:application-development-guide.adoc#GSDVG[{productName} Application Development Guide]. +of high availability features, see the xref:application-development-guide.adoc[{productName} Application Development Guide]. For information on how to configure and tune applications and {productName} for best performance with high availability, see the -xref:performance-tuning-guide.adoc#GSPTG[{productName} Performance Tuning +xref:performance-tuning-guide.adoc[{productName} Performance Tuning Guide], which discusses topics such as: * Tuning persistence frequency and persistence scope diff --git a/docs/ha-administration-guide/src/main/asciidoc/preface.adoc b/docs/ha-administration-guide/src/main/asciidoc/preface.adoc index bd9afed59ed..2028a72492a 100644 --- a/docs/ha-administration-guide/src/main/asciidoc/preface.adoc +++ b/docs/ha-administration-guide/src/main/asciidoc/preface.adoc @@ -40,24 +40,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -70,45 +70,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -121,7 +121,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/ha-administration-guide/src/main/asciidoc/session-persistence-and-failover.adoc b/docs/ha-administration-guide/src/main/asciidoc/session-persistence-and-failover.adoc index a452e83c794..ab4b3070bd1 100644 --- a/docs/ha-administration-guide/src/main/asciidoc/session-persistence-and-failover.adoc +++ b/docs/ha-administration-guide/src/main/asciidoc/session-persistence-and-failover.adoc @@ -110,7 +110,7 @@ with dynamic deployment, dynamic reloading, and autodeployment. These features are for development, not production environments, so you must disable them before enabling the session persistence service. For information about how to disable these features, see the -xref:application-deployment-guide.adoc#GSDPG[ +xref:application-deployment-guide.adoc[ {productName} Application Deployment Guide]. * {productName} {product-majorVersion} does not support High Availability Database diff --git a/docs/ha-administration-guide/src/main/asciidoc/ssh-setup.adoc b/docs/ha-administration-guide/src/main/asciidoc/ssh-setup.adoc index 8cd6ec05a6d..dd3da414c30 100644 --- a/docs/ha-administration-guide/src/main/asciidoc/ssh-setup.adoc +++ b/docs/ha-administration-guide/src/main/asciidoc/ssh-setup.adoc @@ -1256,7 +1256,7 @@ installation on each host. * If you require complete control over the installation on each host, install the software from a {productName} distribution on each host -individually. For more information, see xref:installation-guide.adoc#GSING[{productName} Installation Guide]. +individually. For more information, see xref:installation-guide.adoc[{productName} Installation Guide]. * If the same set up on each host is acceptable, copy an existing {productName} installation to the hosts. For more information, see xref:#to-copy-a-glassfish-server-installation-to-multiple-hosts[To Copy a {productName} Installation to Multiple Hosts]. diff --git a/docs/installation-guide/src/main/asciidoc/installing.adoc b/docs/installation-guide/src/main/asciidoc/installing.adoc index 74b85f823a0..1592a953358 100644 --- a/docs/installation-guide/src/main/asciidoc/installing.adoc +++ b/docs/installation-guide/src/main/asciidoc/installing.adoc @@ -745,7 +745,7 @@ under your current directory. This `glassfish{product-majorVersion}` directory i throughout the {productName} documentation set as as-install-parent. 4. Start {productName} Server using the instructions in the -xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide]. +xref:quick-start-guide.adoc[Server Quick Start Guide]. + The guide explains how to perform basic tasks such as starting the server, accessing the Administration Console, and deploying a sample application. diff --git a/docs/installation-guide/src/main/asciidoc/preface.adoc b/docs/installation-guide/src/main/asciidoc/preface.adoc index 0d024cb1144..437dea96205 100644 --- a/docs/installation-guide/src/main/asciidoc/preface.adoc +++ b/docs/installation-guide/src/main/asciidoc/preface.adoc @@ -47,24 +47,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -77,45 +77,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -128,7 +128,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/performance-tuning-guide/src/main/asciidoc/overview.adoc b/docs/performance-tuning-guide/src/main/asciidoc/overview.adoc index 148e80fddfc..5ab92424dff 100644 --- a/docs/performance-tuning-guide/src/main/asciidoc/overview.adoc +++ b/docs/performance-tuning-guide/src/main/asciidoc/overview.adoc @@ -41,17 +41,17 @@ Table 1-1 Performance Tuning Roadmap |Step |Description of Task |Location of Instructions |1 |Design: Decide on the high-availability topology and set up {productName}. -a|xref:deployment-planning-guide.adoc#GSPLG[ +a|xref:deployment-planning-guide.adoc[ {productName} Deployment Planning Guide] |2 |Capacity Planning: Make sure the systems have sufficient resources to perform well. -a|xref:deployment-planning-guide.adoc#GSPLG[ +a|xref:deployment-planning-guide.adoc[ {productName} Deployment Planning Guide] |3 |Installation: Configure your DAS, clusters, and clustered server instances. -a|xref:installation-guide.adoc#GSING[ +a|xref:installation-guide.adoc[ {productName} Installation Guide] |4 @@ -59,15 +59,15 @@ a|xref:installation-guide.adoc#GSING[ Familiarize yourself with how to configure and administer the {productName}. a|The following books: -* xref:application-deployment-guide.adoc#GSDPG[ +* xref:application-deployment-guide.adoc[ {productName} Application Deployment Guide] -* xref:administration-guide.adoc#GSADG[ +* xref:administration-guide.adoc[ {productName} Administration Guide] |5 |High Availability Configuration: Configuring your DAS, clusters, and clustered server instances for high availability and failover -a|xref:ha-administration-guide.adoc#GSHAG[ +a|xref:ha-administration-guide.adoc[ {productName} High Availability Administration Guide] |6 @@ -279,7 +279,7 @@ minimum application downtime and enhanced transactional security. See xref:tuning-java.adoc#tuning-high-availability-persistence[Tuning High Availability Persistence] for high availability persistence tuning recommendations. -See the xref:ha-administration-guide.adoc#GSHAG[{productName} High +See the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide] for complete information about configuring high availability clustering, load balancing, and failover features in {productName} {product-majorVersion}. @@ -339,7 +339,7 @@ can host different URL domains on a single {productName} process for efficient administration. For detailed information on administration, see the -xref:administration-guide.adoc#GSADG[{productName} Administration Guide]. +xref:administration-guide.adoc[{productName} Administration Guide]. [[general-tuning-concepts]] @@ -512,7 +512,7 @@ http://java.sun.com/docs/performance[Java Performance Documentation] http://java.sun.com/blueprints/performance/index.html[Java Performance BluePrints] (`http://java.sun.com/blueprints/performance/index.html`). * For more information about performance tuning for high availability -configurations, see the xref:ha-administration-guide.adoc#GSHAG[{productName} +configurations, see the xref:ha-administration-guide.adoc[{productName} High Availability Administration Guide]. * For complete information about using the Performance Tuning features available through the {productName} Administration Console, refer to diff --git a/docs/performance-tuning-guide/src/main/asciidoc/preface.adoc b/docs/performance-tuning-guide/src/main/asciidoc/preface.adoc index 90a2c737b14..2d78633db83 100644 --- a/docs/performance-tuning-guide/src/main/asciidoc/preface.adoc +++ b/docs/performance-tuning-guide/src/main/asciidoc/preface.adoc @@ -38,24 +38,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -68,45 +68,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -119,7 +119,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/performance-tuning-guide/src/main/asciidoc/tuning-apps.adoc b/docs/performance-tuning-guide/src/main/asciidoc/tuning-apps.adoc index c484bb79245..cfd60577da0 100644 --- a/docs/performance-tuning-guide/src/main/asciidoc/tuning-apps.adoc +++ b/docs/performance-tuning-guide/src/main/asciidoc/tuning-apps.adoc @@ -604,7 +604,7 @@ option, which can speed up deployment. If you have a legacy rich-client application that directly uses the CosNaming service (not a recommended configuration), then you must generate the stubs for your application explicitly using RMIC. For more -information, see the xref:troubleshooting-guide.adoc#GSTSG[{productName} +information, see the xref:troubleshooting-guide.adoc[{productName} Server Troubleshooting Guide] for more details. [[remove-unneeded-stateful-session-beans]] diff --git a/docs/quick-start-guide/src/main/asciidoc/basic-features.adoc b/docs/quick-start-guide/src/main/asciidoc/basic-features.adoc index 8b7f14ba7f0..b92e0978b29 100644 --- a/docs/quick-start-guide/src/main/asciidoc/basic-features.adoc +++ b/docs/quick-start-guide/src/main/asciidoc/basic-features.adoc @@ -59,7 +59,7 @@ information about {productName} and other entities mentioned in this guide, see xref:#for-more-information[For More Information]. To review additional details about this release before you begin using -the software, see the xref:release-notes.adoc#GSRLN[{productName} +the software, see the xref:release-notes.adoc[{productName} Release Notes]. The Release Notes provide important information about the {productName} {product-majorVersion} release, including details about new features, information about known issues and possible workarounds, and tips for @@ -390,7 +390,7 @@ For more information about the `deploy` subcommand, see xref:reference-manual.adoc#deploy[`deploy`(1)]. For more information about deploying applications from the command line, -see the xref:application-deployment-guide.adoc#GSDPG[{productName} Application +see the xref:application-deployment-guide.adoc[{productName} Application Deployment Guide]. [[to-list-deployed-applications-from-the-command-line]] @@ -720,7 +720,7 @@ The following resources are described here: Comprehensive product documentation is available and includes the following. -* xref:release-notes.adoc#GSRLN[{productName} Release Notes]: +* xref:release-notes.adoc[{productName} Release Notes]: Latest details about new features, known issues, and tips for installing and working with {productName} software. * https://glassfish.org/docs/[{productName}] diff --git a/docs/quick-start-guide/src/main/asciidoc/preface.adoc b/docs/quick-start-guide/src/main/asciidoc/preface.adoc index 009214d655e..81a743abc2d 100644 --- a/docs/quick-start-guide/src/main/asciidoc/preface.adoc +++ b/docs/quick-start-guide/src/main/asciidoc/preface.adoc @@ -51,24 +51,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -81,45 +81,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -132,7 +132,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/reference-manual/src/main/asciidoc/add-library.adoc b/docs/reference-manual/src/main/asciidoc/add-library.adoc index c8d38eb0965..4c5ee21afa1 100644 --- a/docs/reference-manual/src/main/asciidoc/add-library.adoc +++ b/docs/reference-manual/src/main/asciidoc/add-library.adoc @@ -70,7 +70,7 @@ asadmin-options:: + For more information about these directories, see -"xref:application-development-guide.adoc#class-loaders[Class Loaders]" +"link:application-development-guide/class-loaders.html#class-loaders[Class Loaders]" in {productName} Application Development Guide. `--upload`:: @@ -133,6 +133,6 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:list-libraries.adoc#list-libraries[`list-libraries`(1)], xref:remove-library.adoc#remove-library[`remove-library`(1)] -"xref:application-development-guide.adoc#class-loaders[Class Loaders]" in {productName} Application Development Guide +"link:application-development-guide/class-loaders.html#class-loaders[Class Loaders]" in {productName} Application Development Guide diff --git a/docs/reference-manual/src/main/asciidoc/create-application-ref.adoc b/docs/reference-manual/src/main/asciidoc/create-application-ref.adoc index c10ce9647c0..55835aefde0 100644 --- a/docs/reference-manual/src/main/asciidoc/create-application-ref.adoc +++ b/docs/reference-manual/src/main/asciidoc/create-application-ref.adoc @@ -119,7 +119,7 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:delete-application-ref.adoc#delete-application-ref[`delete-application-ref`(1)], xref:list-application-refs.adoc#list-application-refs[`list-application-refs`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/create-auth-realm.adoc b/docs/reference-manual/src/main/asciidoc/create-auth-realm.adoc index 8be77d59214..89afcf9787b 100644 --- a/docs/reference-manual/src/main/asciidoc/create-auth-realm.adoc +++ b/docs/reference-manual/src/main/asciidoc/create-auth-realm.adoc @@ -54,9 +54,8 @@ asadmin-options:: `com.sun.enterprise.security.auth.realm.file.FileRealm`, `com.sun.enterprise.security.auth.realm.certificate.CertificateRealm`, `com.sun.enterprise.security.ee.authentication.glassfish.jdbc.JDBCRealm`, - `com.sun.enterprise.security.auth.realm.ldap.LDAPRealm`, - `com.sun.enterprise.security.ee.authentication.glassfish.pam.PamRealm`, and - `com.sun.enterprise.security.auth.realm.solaris.SolarisRealm`, or a + `com.sun.enterprise.security.auth.realm.ldap.LDAPRealm`, and + `com.sun.enterprise.security.ee.authentication.glassfish.pam.PamRealm`, or a custom realm. `--property`:: Optional attribute name-value pairs for configuring the authentication @@ -64,7 +63,7 @@ asadmin-options:: which vary based on implementation. + The following properties are common to all of the supported realms, which include `FileRealm`, `CertificateRealm`, `JDBCRealm`, - `LDAPRealm`, PamRealm, and `SolarisRealm`. + `LDAPRealm`, and `PamRealm`. + -- `jaas-context`;; diff --git a/docs/reference-manual/src/main/asciidoc/delete-application-ref.adoc b/docs/reference-manual/src/main/asciidoc/delete-application-ref.adoc index 2c269f26010..b6d377224fc 100644 --- a/docs/reference-manual/src/main/asciidoc/delete-application-ref.adoc +++ b/docs/reference-manual/src/main/asciidoc/delete-application-ref.adoc @@ -108,7 +108,7 @@ xref:create-application-ref.adoc#create-application-ref[`create-application-ref` xref:list-application-refs.adoc#list-application-refs[`list-application-refs`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/deploy.adoc b/docs/reference-manual/src/main/asciidoc/deploy.adoc index fee61fd610e..447975bc8de 100644 --- a/docs/reference-manual/src/main/asciidoc/deploy.adoc +++ b/docs/reference-manual/src/main/asciidoc/deploy.adoc @@ -574,7 +574,7 @@ xref:redeploy.adoc#redeploy[`redeploy`(1)], xref:set.adoc#set[`set`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/deploydir.adoc b/docs/reference-manual/src/main/asciidoc/deploydir.adoc index 90305c70434..c5d80c998ea 100644 --- a/docs/reference-manual/src/main/asciidoc/deploydir.adoc +++ b/docs/reference-manual/src/main/asciidoc/deploydir.adoc @@ -413,7 +413,7 @@ xref:redeploy.adoc#redeploy[`redeploy`(1)], xref:set.adoc#set[`set`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/disable.adoc b/docs/reference-manual/src/main/asciidoc/disable.adoc index 4fb483b4dff..f420e503dee 100644 --- a/docs/reference-manual/src/main/asciidoc/disable.adoc +++ b/docs/reference-manual/src/main/asciidoc/disable.adoc @@ -95,7 +95,7 @@ xref:deploy.adoc#deploy[`deploy`(1)], xref:enable.adoc#enable[`enable`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/enable.adoc b/docs/reference-manual/src/main/asciidoc/enable.adoc index b732f595451..bdef937da13 100644 --- a/docs/reference-manual/src/main/asciidoc/enable.adoc +++ b/docs/reference-manual/src/main/asciidoc/enable.adoc @@ -96,7 +96,7 @@ xref:deploy.adoc#deploy[`deploy`(1)], xref:disable.adoc#disable[`disable`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/get-client-stubs.adoc b/docs/reference-manual/src/main/asciidoc/get-client-stubs.adoc index 2f643277c07..b5d61e134b5 100644 --- a/docs/reference-manual/src/main/asciidoc/get-client-stubs.adoc +++ b/docs/reference-manual/src/main/asciidoc/get-client-stubs.adoc @@ -90,7 +90,7 @@ xref:undeploy.adoc#undeploy[`undeploy`(1)] xref:appclient.adoc#appclient[`appclient`(1M)], xref:package-appclient.adoc#package-appclient[`package-appclient`(1M)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/get.adoc b/docs/reference-manual/src/main/asciidoc/get.adoc index 03185a23a3a..d8528f94a27 100644 --- a/docs/reference-manual/src/main/asciidoc/get.adoc +++ b/docs/reference-manual/src/main/asciidoc/get.adoc @@ -189,6 +189,6 @@ xref:list.adoc#list[`list`(1)], xref:set.adoc#set[`set`(1)] xref:dotted-names.adoc#dotted-names[`dotted-names`(5ASC)] -xref:administration-guide.adoc#GSADG[{productName} Administration Guide] +xref:administration-guide.adoc[{productName} Administration Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list-application-refs.adoc b/docs/reference-manual/src/main/asciidoc/list-application-refs.adoc index b2afb7a8d84..9669adbd28b 100644 --- a/docs/reference-manual/src/main/asciidoc/list-application-refs.adoc +++ b/docs/reference-manual/src/main/asciidoc/list-application-refs.adoc @@ -95,7 +95,7 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:create-application-ref.adoc#create-application-ref[`create-application-ref`(1)], xref:delete-application-ref.adoc#delete-application-ref[`delete-application-ref`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list-applications.adoc b/docs/reference-manual/src/main/asciidoc/list-applications.adoc index 3ab5b0d032e..719681465b8 100644 --- a/docs/reference-manual/src/main/asciidoc/list-applications.adoc +++ b/docs/reference-manual/src/main/asciidoc/list-applications.adoc @@ -118,7 +118,7 @@ xref:list-components.adoc#list-components[`list-components`(1)], xref:list-sub-components.adoc#list-sub-components[`list-sub-components`(1)], xref:show-component-status.adoc#show-component-status[`show-component-status`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list-components.adoc b/docs/reference-manual/src/main/asciidoc/list-components.adoc index f566392e398..60a6cbcb20f 100644 --- a/docs/reference-manual/src/main/asciidoc/list-components.adoc +++ b/docs/reference-manual/src/main/asciidoc/list-components.adoc @@ -125,7 +125,7 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:list-applications.adoc#list-applications[`list-applications`(1)], xref:show-component-status.adoc#show-component-status[`show-component-status`(1)] -xref:application-deployment-guide.adoc#GSDPG[ +xref:application-deployment-guide.adoc[ {productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list-persistence-types.adoc b/docs/reference-manual/src/main/asciidoc/list-persistence-types.adoc index 9c3a7303ace..ae2cb1d8037 100644 --- a/docs/reference-manual/src/main/asciidoc/list-persistence-types.adoc +++ b/docs/reference-manual/src/main/asciidoc/list-persistence-types.adoc @@ -29,7 +29,7 @@ built-in persistence types are `memory`, `file`, and `replicated`. The `memory` type does not apply to SFSB instances. Other persistence types can be added using the `StrategyBuilder` class. -For more information, see the xref:add-on-component-development-guide.adoc#GSACG[{productName} Add-On Component Development Guide]. +For more information, see the xref:add-on-component-development-guide.adoc[{productName} Add-On Component Development Guide]. To set the persistence type for HTTP sessions, use the `set` subcommand to set the `persistence-type` attribute. For example: @@ -107,7 +107,7 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:get.adoc#get[`get`(1)], xref:list.adoc#list[`list`(1)], xref:set.adoc#set[`set`(1)] -xref:add-on-component-development-guide.adoc#GSACG[{productName} Add-On Component +xref:add-on-component-development-guide.adoc[{productName} Add-On Component Development Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list-sub-components.adoc b/docs/reference-manual/src/main/asciidoc/list-sub-components.adoc index 1418141d8e6..d1fcad8ea78 100644 --- a/docs/reference-manual/src/main/asciidoc/list-sub-components.adoc +++ b/docs/reference-manual/src/main/asciidoc/list-sub-components.adoc @@ -105,7 +105,7 @@ xref:disable.adoc#disable[`disable`(1)], xref:enable.adoc#enable[`enable`(1)], xref:list-components.adoc#list-components[`list-components`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/list.adoc b/docs/reference-manual/src/main/asciidoc/list.adoc index 696e2746633..3340dc5b0b6 100644 --- a/docs/reference-manual/src/main/asciidoc/list.adoc +++ b/docs/reference-manual/src/main/asciidoc/list.adoc @@ -212,6 +212,6 @@ xref:get.adoc#get[`get`(1)], xref:set.adoc#set[`set`(1)] xref:dotted-names.adoc#dotted-names[`dotted-names`(5ASC)] -xref:administration-guide.adoc#GSADG[{productName} Administration Guide] +xref:administration-guide.adoc[{productName} Administration Guide] diff --git a/docs/reference-manual/src/main/asciidoc/redeploy.adoc b/docs/reference-manual/src/main/asciidoc/redeploy.adoc index 75f8dec3b85..76013e3566c 100644 --- a/docs/reference-manual/src/main/asciidoc/redeploy.adoc +++ b/docs/reference-manual/src/main/asciidoc/redeploy.adoc @@ -446,7 +446,7 @@ xref:deploy.adoc#deploy[`deploy`(1)], xref:get.adoc#get[`get`(1)], xref:list-components.adoc#list-components[`list-components`(1)], xref:undeploy.adoc#undeploy[`undeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/set.adoc b/docs/reference-manual/src/main/asciidoc/set.adoc index 0500ae636b8..cc67364a8ed 100644 --- a/docs/reference-manual/src/main/asciidoc/set.adoc +++ b/docs/reference-manual/src/main/asciidoc/set.adoc @@ -128,6 +128,6 @@ xref:get.adoc#get[`get`(1)], xref:list.adoc#list[`list`(1)] xref:dotted-names.adoc#dotted-names[`dotted-names`(5ASC)] -xref:administration-guide.adoc#GSADG[{productName} Administration Guide] +xref:administration-guide.adoc[{productName} Administration Guide] diff --git a/docs/reference-manual/src/main/asciidoc/show-component-status.adoc b/docs/reference-manual/src/main/asciidoc/show-component-status.adoc index 4fd6ba7ab3f..91efd642b90 100644 --- a/docs/reference-manual/src/main/asciidoc/show-component-status.adoc +++ b/docs/reference-manual/src/main/asciidoc/show-component-status.adoc @@ -94,7 +94,7 @@ xref:asadmin.adoc#asadmin[`asadmin`(1M)] xref:list-applications.adoc#list-applications[`list-applications`(1)], xref:list-sub-components.adoc#list-sub-components[`list-sub-components`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/reference-manual/src/main/asciidoc/undeploy.adoc b/docs/reference-manual/src/main/asciidoc/undeploy.adoc index e870855d13e..5c117790267 100644 --- a/docs/reference-manual/src/main/asciidoc/undeploy.adoc +++ b/docs/reference-manual/src/main/asciidoc/undeploy.adoc @@ -137,7 +137,7 @@ xref:deploy.adoc#deploy[`deploy`(1)], xref:list-components.adoc#list-components[`list-components`(1)], xref:redeploy.adoc#redeploy[`redeploy`(1)] -xref:application-deployment-guide.adoc#GSDPG[{productName} Application Deployment +xref:application-deployment-guide.adoc[{productName} Application Deployment Guide] diff --git a/docs/release-notes/src/main/asciidoc/preface.adoc b/docs/release-notes/src/main/asciidoc/preface.adoc index 6744815115f..353aaefc088 100644 --- a/docs/release-notes/src/main/asciidoc/preface.adoc +++ b/docs/release-notes/src/main/asciidoc/preface.adoc @@ -45,24 +45,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -75,45 +75,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -126,7 +126,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/security-guide/src/main/asciidoc/message-security.adoc b/docs/security-guide/src/main/asciidoc/message-security.adoc index 0d118b0ff94..f07ffb617c7 100644 --- a/docs/security-guide/src/main/asciidoc/message-security.adoc +++ b/docs/security-guide/src/main/asciidoc/message-security.adoc @@ -58,7 +58,7 @@ references declared by client applications. Message-level security can be configured for the entire {productName} or for specific applications or methods. Configuring message security at the application level is discussed in the -xref:application-development-guide.adoc#GSDVG[ +xref:application-development-guide.adoc[ {productName} Application Development Guide]. The following topics are addressed here: diff --git a/docs/security-guide/src/main/asciidoc/preface.adoc b/docs/security-guide/src/main/asciidoc/preface.adoc index 2049b9e969a..6c263bf93b0 100644 --- a/docs/security-guide/src/main/asciidoc/preface.adoc +++ b/docs/security-guide/src/main/asciidoc/preface.adoc @@ -49,24 +49,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -79,45 +79,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -130,7 +130,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/security-guide/src/main/asciidoc/user-security.adoc b/docs/security-guide/src/main/asciidoc/user-security.adoc index 1944a6b542c..c6aea261321 100644 --- a/docs/security-guide/src/main/asciidoc/user-security.adoc +++ b/docs/security-guide/src/main/asciidoc/user-security.adoc @@ -103,7 +103,7 @@ asadmin> create-jvm-options --target=target ---- where target is the {productName} instance or cluster for which you are disabling LDAP group search. For more information about the -`create-jvm-options` subcommand, see the xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +`create-jvm-options` subcommand, see the xref:reference-manual.adoc#create-jvm-options[{productName} Reference Manual]. ==== JDBC realm:: diff --git a/docs/troubleshooting-guide/src/main/asciidoc/faqs.adoc b/docs/troubleshooting-guide/src/main/asciidoc/faqs.adoc index a2beeb276b0..f56d0804f90 100644 --- a/docs/troubleshooting-guide/src/main/asciidoc/faqs.adoc +++ b/docs/troubleshooting-guide/src/main/asciidoc/faqs.adoc @@ -80,7 +80,7 @@ information, see the GlassFish Plugins page: ==== How Do I Develop Add-On Components? -See the xref:add-on-component-development-guide.adoc#GSACG[{productName} Add-On +See the xref:add-on-component-development-guide.adoc[{productName} Add-On Component Development Guide] for complete details. [[how-do-i-add-containers]] diff --git a/docs/troubleshooting-guide/src/main/asciidoc/overview.adoc b/docs/troubleshooting-guide/src/main/asciidoc/overview.adoc index 5fcfaccc775..08ec820e71c 100644 --- a/docs/troubleshooting-guide/src/main/asciidoc/overview.adoc +++ b/docs/troubleshooting-guide/src/main/asciidoc/overview.adoc @@ -79,7 +79,7 @@ supported JDK version. ===== Review Known Issues Your problem might be related to a known issue for the release. Refer to -the xref:release-notes.adoc#GSRLN[{productName} Release Notes] for +the xref:release-notes.adoc[{productName} Release Notes] for the latest information regarding known issues and possible workarounds. Also search the GlassFish issues at `https://github.com/eclipse-ee4j/glassfish/issues`. @@ -97,9 +97,9 @@ information about performing administrative tasks using the graphical interface. The following books will be especially helpful for troubleshooting: -* xref:release-notes.adoc#GSRLN[{productName} Release Notes], +* xref:release-notes.adoc[{productName} Release Notes], which provides the latest information regarding known issues and possible workarounds. -* xref:error-messages-reference.adoc#GSEMR[ +* xref:error-messages-reference.adoc[ {productName} Error Message Reference], which lists error messages you might encounter when using {productName}. @@ -150,7 +150,7 @@ undeployed? * What version of {productName} are you using? What operating system and version? What JDK version? Many problems are caused simply because system requirements for the release are not met. -Refer to the xref:release-notes.adoc#GSRLN[{productName} Release +Refer to the xref:release-notes.adoc[{productName} Release Notes] for the latest information regarding system requirements, and make sure your system meets those requirements. * What resources does your system have, such as memory, disk, and swap @@ -373,9 +373,9 @@ attach to the server using Java Remote Invocation Method (RMI). These resources were mentioned throughout this chapter and are provided again here for easy reference. -* Release Notes: xref:release-notes.adoc#GSRLN[{productName} +* Release Notes: xref:release-notes.adoc[{productName} Release Notes] -* Error messages: xref:error-messages-reference.adoc#GSEMR[{productName} Error +* Error messages: xref:error-messages-reference.adoc[{productName} Error Message Reference] * Mailing lists and forums: See xref:#search-the-glassfish-mailing-lists-and-forums[Search the GlassFish Mailing Lists and Forums] for details about accessing lists and forums. diff --git a/docs/troubleshooting-guide/src/main/asciidoc/preface.adoc b/docs/troubleshooting-guide/src/main/asciidoc/preface.adoc index c379f2df849..8203320a339 100644 --- a/docs/troubleshooting-guide/src/main/asciidoc/preface.adoc +++ b/docs/troubleshooting-guide/src/main/asciidoc/preface.adoc @@ -47,24 +47,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -77,45 +77,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -128,7 +128,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/upgrade-guide/src/main/asciidoc/appendix.adoc b/docs/upgrade-guide/src/main/asciidoc/appendix.adoc index 4ec0ef2df01..7c4d945603c 100644 --- a/docs/upgrade-guide/src/main/asciidoc/appendix.adoc +++ b/docs/upgrade-guide/src/main/asciidoc/appendix.adoc @@ -43,24 +43,24 @@ These guides apply to all {productName} variants. |=== |Book Title |Description -|xref:release-notes.adoc#GSRLN[Release Notes] +|xref:release-notes.adoc[Release Notes] |Provides late-breaking information about the software and the documentation and includes a comprehensive, table-based summary of the supported hardware, operating system, Java Development Kit (JDK), and database drivers. -|xref:application-development-guide.adoc#GSDVG[Application Development Guide] +|xref:application-development-guide.adoc[Application Development Guide] |Explains how to create and implement Java Platform, Enterprise Edition (Jakarta EE platform) applications that are intended to run on the {productName}. These applications follow the open Java standards model for Jakarta EE components and application programmer interfaces (APIs). This guide provides information about developer tools, security, and debugging. -|xref:error-messages-reference.adoc#GSEMR[Error Message Reference] +|xref:error-messages-reference.adoc[Error Message Reference] |Describes error messages that you might encounter when using {productName}. -|xref:performance-tuning-guide.adoc#GSPTG[Performance Tuning Guide] +|xref:performance-tuning-guide.adoc[Performance Tuning Guide] |Explains how to optimize the performance of {productName}. -|xref:reference-manual.adoc#GSRFM[Reference Manual] +|xref:reference-manual.adoc[Reference Manual] |Provides reference information in man page format for {productName} administration commands, utility commands, and related concepts. |=== @@ -73,45 +73,45 @@ These guides are specific to the {productName} Server installation. |=== |Book Title |Description -|xref:quick-start-guide.adoc#GSQSG[Server Quick Start Guide] +|xref:quick-start-guide.adoc[Server Quick Start Guide] |Explains how to get started with the {productName} Server. -|xref:installation-guide.adoc#GSING[Installation Guide] +|xref:installation-guide.adoc[Installation Guide] |Explains how to install the software and its components. -|xref:upgrade-guide.adoc#GSUPG[Upgrade Guide] +|xref:upgrade-guide.adoc[Upgrade Guide] |Explains how to upgrade to the latest version of {productName}. This guide also describes differences between adjacent product releases and configuration options that can result in incompatibility with the product specifications. -|xref:deployment-planning-guide.adoc#GSPLG[Deployment Planning Guide] +|xref:deployment-planning-guide.adoc[Deployment Planning Guide] |Explains how to build a production deployment of {productName} that meets the requirements of your system and enterprise. -|xref:administration-guide.adoc#GSADG[Administration Guide] +|xref:administration-guide.adoc[Administration Guide] |Explains how to configure, monitor, and manage {productName} subsystems and components from the command line by using the xref:reference-manual.adoc#asadmin[`asadmin`] utility. Instructions for performing these tasks from the Administration Console are provided in the Administration Console online help. -|xref:security-guide.adoc#GSSCG[Server Security Guide] +|xref:security-guide.adoc[Server Security Guide] |Provides instructions for configuring and administering {productName} Server security. -|xref:application-deployment-guide.adoc#GSDPG[Application Deployment Guide] +|xref:application-deployment-guide.adoc[Application Deployment Guide] |Explains how to assemble and deploy applications to the {productName} and provides information about deployment descriptors. -|xref:add-on-component-development-guide.adoc#GSACG[Add-On Component Development Guide] +|xref:add-on-component-development-guide.adoc[Add-On Component Development Guide] |Explains how to use published interfaces of {productName} to develop add-on components for {productName}. This document explains how to perform only those tasks that ensure that the add-on component is suitable for {productName}. -|xref:ha-administration-guide.adoc#GSHAG[High Availability Administration Guide] +|xref:ha-administration-guide.adoc[High Availability Administration Guide] |Explains how to configure {productName} to provide higher availability and scalability through failover and load balancing. -|xref:troubleshooting-guide.adoc#GSTSG[Server Troubleshooting Guide] +|xref:troubleshooting-guide.adoc[Server Troubleshooting Guide] |Describes common problems that you might encounter when using {productName} Server and explains how to solve them. |=== @@ -124,7 +124,7 @@ containers, and embedding in applications. |=== |Book Title |Description -|xref:embedded-server-guide.adoc#GSESG[Embedded Server Guide] +|xref:embedded-server-guide.adoc[Embedded Server Guide] |Explains how to run applications with Embedded {productName} from the command line or as a library, suitable for cloud deployments, containers, and integration testing. |=== diff --git a/docs/upgrade-guide/src/main/asciidoc/upgrade-compatibility-issues.adoc b/docs/upgrade-guide/src/main/asciidoc/upgrade-compatibility-issues.adoc index 167139c5af1..8642eec72d6 100644 --- a/docs/upgrade-guide/src/main/asciidoc/upgrade-compatibility-issues.adoc +++ b/docs/upgrade-guide/src/main/asciidoc/upgrade-compatibility-issues.adoc @@ -190,7 +190,7 @@ The following sections describe changes to the command line utility `asadmin`: * xref:#deprecated-unsupported-and-obsolete-options[Deprecated, Unsupported, and Obsolete Options] For more information about `asadmin` and its subcommands, see the -xref:reference-manual.adoc#GSRFM[{productName} Reference Manual]. +xref:reference-manual.adoc[{productName} Reference Manual]. [[deprecated-asadmin-subcommands]] diff --git a/docs/upgrade-guide/src/main/asciidoc/upgrading-legacy-installation.adoc b/docs/upgrade-guide/src/main/asciidoc/upgrading-legacy-installation.adoc index 23772018180..2ad42125e97 100644 --- a/docs/upgrade-guide/src/main/asciidoc/upgrading-legacy-installation.adoc +++ b/docs/upgrade-guide/src/main/asciidoc/upgrading-legacy-installation.adoc @@ -75,7 +75,7 @@ To do that: 1. Perform new (not upgrade) {productName} {product-majorVersion} installations on each node host. {productName} {product-majorVersion} installation instructions are provided -in the xref:installation-guide.adoc#GSING[ +in the xref:installation-guide.adoc[ {productName} Installation Guide]. 2. Correct the node configuration on the upgraded DAS, if necessary. diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java index 5a2bd6519b8..6de76f86fe4 100644 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java +++ b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/AuthRealm.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation + * Copyright (c) 2022, 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 @@ -21,7 +21,6 @@ import com.sun.enterprise.config.serverbeans.customvalidators.JDBCRealmPropertyCheck; import com.sun.enterprise.config.serverbeans.customvalidators.JavaClassName; import com.sun.enterprise.config.serverbeans.customvalidators.LDAPRealmPropertyCheck; -import com.sun.enterprise.config.serverbeans.customvalidators.SolarisRealmPropertyCheck; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Pattern; @@ -55,10 +54,9 @@ @FileRealmPropertyCheck @LDAPRealmPropertyCheck @JDBCRealmPropertyCheck -@SolarisRealmPropertyCheck @RestRedirects({ - @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-auth-realm"), - @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-auth-realm") + @RestRedirect(opType = RestRedirect.OpType.POST, commandName = "create-auth-realm"), + @RestRedirect(opType = RestRedirect.OpType.DELETE, commandName = "delete-auth-realm") }) public interface AuthRealm extends ConfigBeanProxy, PropertyBag { diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheck.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheck.java deleted file mode 100644 index 62f3ddb8329..00000000000 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheck.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2009, 2020 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.enterprise.config.serverbeans.customvalidators; - -import jakarta.validation.Constraint; -import jakarta.validation.Payload; - -import java.lang.annotation.Documented; -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.ElementType.TYPE; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - -@Retention(RUNTIME) -@Target({ METHOD, FIELD, TYPE }) -@Documented -@Constraint(validatedBy = SolarisRealmPropertyCheckValidator.class) -public @interface SolarisRealmPropertyCheck { - String message() default "jaas-context has to be specified for SolarisRealm"; - - Class[] groups() default {}; - - Class[] payload() default {}; -} diff --git a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheckValidator.java b/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheckValidator.java deleted file mode 100644 index 156121e1553..00000000000 --- a/nucleus/admin/config-api/src/main/java/com/sun/enterprise/config/serverbeans/customvalidators/SolarisRealmPropertyCheckValidator.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2009, 2020 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.enterprise.config.serverbeans.customvalidators; - -import com.sun.enterprise.config.serverbeans.AuthRealm; - -import jakarta.validation.ConstraintValidator; -import jakarta.validation.ConstraintValidatorContext; - -import org.jvnet.hk2.config.types.Property; - -/** - * - * @author Nandini Ektare - */ -public class SolarisRealmPropertyCheckValidator implements ConstraintValidator { - - private static final String SOLARIS_REALM = "com.sun.enterprise.security.auth.realm.solaris.SolarisRealm"; - - public void initialize(final SolarisRealmPropertyCheck fqcn) { - } - - public boolean isValid(final AuthRealm realm, final ConstraintValidatorContext constraintValidatorContext) { - - if (realm.getClassname().equals(SOLARIS_REALM)) { - Property jaas_context = realm.getProperty("jaas-context"); - if (jaas_context == null || jaas_context.getName().equals("")) - return false; - } - - return true; - } -} diff --git a/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncher.java b/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncher.java index d6199e5a813..165f3f8d1cd 100644 --- a/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncher.java +++ b/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncher.java @@ -65,7 +65,7 @@ public abstract class GFLauncher { /** * The full commandline string used to start GlassFish in process - * glassFishProcess + * glassFishProcess */ private CommandLine commandLine; diff --git a/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncherInfo.java b/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncherInfo.java index 4c21c8e2bdd..33906042db9 100644 --- a/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncherInfo.java +++ b/nucleus/admin/launcher/src/main/java/com/sun/enterprise/admin/launcher/GFLauncherInfo.java @@ -342,7 +342,7 @@ public List getArgsAsList() throws GFLauncherException { /** * - * @return a Map of processed and packaged args + * @return a {@code Map} of processed and packaged args * @throws com.sun.enterprise.admin.launcher.GFLauncherException */ public Map getArgs() throws GFLauncherException { diff --git a/nucleus/admin/monitor/src/main/java/org/glassfish/admin/monitor/jvm/JVMRuntimeStatsProvider.java b/nucleus/admin/monitor/src/main/java/org/glassfish/admin/monitor/jvm/JVMRuntimeStatsProvider.java index 723766824c5..bfceb5e5dde 100644 --- a/nucleus/admin/monitor/src/main/java/org/glassfish/admin/monitor/jvm/JVMRuntimeStatsProvider.java +++ b/nucleus/admin/monitor/src/main/java/org/glassfish/admin/monitor/jvm/JVMRuntimeStatsProvider.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 @@ -39,8 +40,6 @@ public class JVMRuntimeStatsProvider { private RuntimeMXBean rtBean = ManagementFactory.getRuntimeMXBean(); - private StringStatisticImpl bootClassPath = new StringStatisticImpl("BootClassPath", "String", - "Boot class path that is used by the bootstrap class loader to search for class files"); private StringStatisticImpl classPath = new StringStatisticImpl("ClassPath", "String", "Java class path that is used by the system class loader to search for class files"); private StringStatisticImpl inputArguments = new StringStatisticImpl("InputArguments", "String", @@ -60,13 +59,6 @@ public class JVMRuntimeStatsProvider { private StringStatisticImpl vmVendor = new StringStatisticImpl("VmVendor", "String", "Java virtual machine implementation vendor"); private StringStatisticImpl vmVersion = new StringStatisticImpl("VmVersion", "String", "Java virtual machine implementation version"); - @ManagedAttribute(id = "bootclasspath-current") - @Description("boot class path that is used by the bootstrap class loader to search for class files") - public StringStatistic getBootClassPath() { - bootClassPath.setCurrent(rtBean.getBootClassPath()); - return bootClassPath; - } - @ManagedAttribute(id = "classpath-current") @Description("Java class path that is used by the system class loader to search for class files") public StringStatistic getClassPath() { diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/RestLogging.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/RestLogging.java index 6c6d54ed6c7..dce1f2c5ca4 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/RestLogging.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/RestLogging.java @@ -34,18 +34,12 @@ public class RestLogging { @LoggerInfo(subsystem = "REST", description = "Main REST Logger", publish = true) public static final String REST_MAIN_LOGGER = "jakarta.enterprise.admin.rest"; public static final Logger restLogger = Logger.getLogger(REST_MAIN_LOGGER, SHARED_LOGMESSAGE_RESOURCE); - @LogMessageInfo(message = "Listening to REST requests at context: {0}/domain.", level = "INFO") - public static final String REST_INTERFACE_INITIALIZED = "NCLS-REST-00001"; @LogMessageInfo(message = "Incorrectly formatted entry in {0}: {1}", level = "INFO") public static final String INCORRECTLY_FORMATTED_ENTRY = "NCLS-REST-00002"; @LogMessageInfo(message = "An error occurred while processing the request. Please see the server logs for details.", cause = "A runtime error occurred. Please see the log file for more details", action = "See the log file for more details", level = "SEVERE") public static final String SERVER_ERROR = "NCLS-REST-00003"; - @LogMessageInfo(message = "The class specified by generator does not implement DefaultsGenerator", cause = "The generator does not implement the DefaultsGenerator interface", action = "Modify the generator to implement the DefaultsGenerator interface", level = "SEVERE") - public static final String DOESNT_IMPLEMENT_DEFAULTS_GENERATOR = "NCLS-REST-00004"; @LogMessageInfo(message = "Unsupported fixed value. Supported types are String, boolean, Boolean, int, Integer, long, Long, double, Double, float, and Float", cause = "The RestModel property has specified an unsupported data type", action = "Modify the model to use one of the supported types", level = "SEVERE") public static final String UNSUPPORTED_FIXED_VALUE = "NCLS-REST-00005"; - @LogMessageInfo(message = "Fixed value type does not match the property type", cause = "The value for the given property can not be converted to the property's type", action = "Check the input data", level = "SEVERE") - public static final String VALUE_DOES_NOT_MATCH_TYPE = "NCLS-REST-00006"; @LogMessageInfo(message = "Cannot marshal", cause = "The system is unable to generate XML for the given object", action = "Check the logs for more details", level = "SEVERE") public static final String CANNOT_MARSHAL = "NCLS-REST-00007"; @LogMessageInfo(message = "Unable to delete directory {0}. Will attempt deletion again upon JVM exit.", level = "WARNING") @@ -62,6 +56,4 @@ public class RestLogging { public static final String DIR_CREATION_FAILED = "NCLS-REST-00014"; @LogMessageInfo(message = "Unexpected exception during initilization.", cause = "The system is unable to init ReST interface", action = "Check the logs for more details", level = "SEVERE") public static final String INIT_FAILED = "NCLS-REST-00015"; - @LogMessageInfo(message = "I/O exception", cause = "See server log for details", action = "See server log for details.", level = "SEVERE") - public static final String IO_EXCEPTION = "NCLS-REST-00016"; } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/AbstractRestResourceProvider.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/AbstractRestResourceProvider.java index 04ee805708d..ec6bc763858 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/AbstractRestResourceProvider.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/AbstractRestResourceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2024, 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -33,6 +33,7 @@ import org.glassfish.hk2.utilities.Binder; import org.glassfish.internal.api.ServerContext; import org.glassfish.jersey.jettison.JettisonFeature; +import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.message.MessageProperties; import org.glassfish.jersey.server.ResourceConfig; @@ -79,30 +80,12 @@ public ResourceConfig getResourceConfig(Set> classes, final ServerConte ResourceConfig rc = new ResourceConfig(classes); rc.property(ServerProperties.MEDIA_TYPE_MAPPINGS, getMimeMappings()); rc.register(CsrfProtectionFilter.class); - - // TODO - JERSEY2 - // RestConfig restConf = ResourceUtil.getRestConfig(habitat); - // if (restConf != null) { - // if (restConf.getLogOutput().equalsIgnoreCase("true")) { //enable output logging - // rc.getContainerResponseFilters().add(LoggingFilter.class); - // } - // if (restConf.getLogInput().equalsIgnoreCase("true")) { //enable input logging - // rc.getContainerRequestFilters().add(LoggingFilter.class); - // } - // if (restConf.getWadlGeneration().equalsIgnoreCase("false")) { //disable WADL - // rc.getFeatures().put(ResourceConfig.FEATURE_DISABLE_WADL, Boolean.TRUE); - // } - // } - // else { - // rc.getFeatures().put(ResourceConfig.FEATURE_DISABLE_WADL, Boolean.TRUE); - // } - // + rc.register(LoggingFeature.class); final Reloader reloader = new Reloader(); rc.register(new CdiBridge(serviceLocator, reloader, serverContext)); rc.register(reloader); rc.register(ReloadResource.class); rc.register(new MultiPartFeature()); - //rc.register(getJsonFeature()); for (Binder binder : additionalBinders) { rc.register(binder); diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/ExceptionFilter.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/ExceptionFilter.java index 8ef060497b6..c7051bec933 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/ExceptionFilter.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/ExceptionFilter.java @@ -57,7 +57,7 @@ public void filter(ContainerRequestContext reqCtx, ContainerResponseContext resC return; } - // Normally the cliend sends in an X-Skip-Resource-Links header + // Normally the client sends in an X-Skip-Resource-Links header // to say that resource links should not be returned, and the resource // looks for that header in the request and, if present, tells // the ResponseBody constructor to ignore resource links. diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainer.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainer.java index 7e615a6d70a..b6053be782e 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainer.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainer.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -28,9 +29,8 @@ * * @author sanjeeb.sahoo@oracle.com */ +@FunctionalInterface public interface JerseyContainer { - // TODO(Sahoo): Abstract out Request and Response instead of using Grizzly Request and Response. - // It requires more effort than just interface, because many other places in GlassFish admin infrastructure, - // we reference Grizzly directly. + void service(Request request, Response response) throws Exception; } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainerCommandService.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainerCommandService.java index 775f09c32c8..ec02d4374b2 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainerCommandService.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/JerseyContainerCommandService.java @@ -38,8 +38,6 @@ import org.glassfish.api.admin.ParameterMap; import org.glassfish.api.container.EndpointRegistrationException; import org.glassfish.grizzly.http.server.HttpHandler; -import org.glassfish.grizzly.http.server.Request; -import org.glassfish.grizzly.http.server.Response; import org.glassfish.hk2.api.PerLookup; import org.glassfish.hk2.api.PostConstruct; import org.glassfish.hk2.api.ServiceLocator; @@ -143,12 +141,7 @@ private JerseyContainer getJerseyContainer(ResourceConfig config) { final GrizzlyHttpContainer httpHandler = ContainerFactory.createContainer(GrizzlyHttpContainer.class, config); final ServiceLocator jerseyLocator = httpHandler.getApplicationHandler().getInjectionManager().getInstance(ServiceLocator.class); ExtrasUtilities.enableTopicDistribution(jerseyLocator); - return new JerseyContainer() { - @Override - public void service(Request request, Response response) throws Exception { - httpHandler.service(request, response); - } - }; + return httpHandler::service; } finally { iteratorProvider.disable(); } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestAdapter.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestAdapter.java index 3d300bfedfa..c45e1543078 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestAdapter.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2024, 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -25,6 +25,7 @@ import jakarta.inject.Provider; import java.io.IOException; +import java.lang.System.Logger; import java.net.HttpURLConnection; import java.util.Collections; import java.util.HashSet; @@ -32,7 +33,6 @@ import java.util.StringTokenizer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.logging.Level; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; @@ -73,6 +73,9 @@ import org.glassfish.jersey.server.ContainerFactory; import org.glassfish.jersey.server.ResourceConfig; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.INFO; +import static java.lang.System.Logger.Level.WARNING; import static java.nio.charset.StandardCharsets.UTF_8; /** @@ -82,6 +85,7 @@ * @author sanjeeb.sahoo@oracle.com */ public abstract class RestAdapter extends HttpHandler implements ProxiedRestAdapter, PostConstruct { + protected static final String COOKIE_REST_TOKEN = "gfresttoken"; protected static final String COOKIE_GF_REST_UID = "gfrestuid"; protected static final String HEADER_ACCEPT = "Accept"; @@ -89,6 +93,7 @@ public abstract class RestAdapter extends HttpHandler implements ProxiedRestAdap protected static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token"; protected static final String HEADER_AUTHENTICATE = "WWW-Authenticate"; + private static final Logger LOG = System.getLogger(RestAdapter.class.getName()); private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(RestService.class); private final CountDownLatch latch = new CountDownLatch(1); @@ -133,7 +138,7 @@ public HttpHandler getHttpService() { @Override public void service(Request req, Response res) { - RestLogging.restLogger.log(Level.FINER, "Received resource request: {0}", req.getRequestURI()); + LOG.log(DEBUG, "{0}: Received resource request to URI {1}", this, req.getRequestURI()); try { res.setCharacterEncoding(UTF_8.name()); @@ -141,7 +146,7 @@ public void service(Request req, Response res) { if (serverEnvironment.isInstance()) { if (!Method.GET.equals(req.getMethod()) && !getRestResourceProvider().enableModifAccessToInstances()) { reportError(req, res, HttpURLConnection.HTTP_FORBIDDEN, localStrings.getLocalString( - "rest.resource.only.GET.on.instance", "Only GET requests are allowed on an instance that is not DAS.")); + "rest.resource.only.GET.on.instance", "Only GET requests are allowed on an instance that is not DAS."), null); return; } } @@ -151,40 +156,49 @@ public void service(Request req, Response res) { String context = getContextRoot(); if (context != null && !context.isEmpty() && adapter == null) { - RestLogging.restLogger.log(Level.FINE, "Exposing rest resource context root: {0}", context); + LOG.log(DEBUG, "Exposing rest resource context root: {0}", context); adapter = exposeContext(); - RestLogging.restLogger.log(Level.INFO, RestLogging.REST_INTERFACE_INITIALIZED, context); + LOG.log(INFO, "Listening to REST requests at context: {0}/domain.", context); } //delegate to adapter managed by Jersey. adapter.service(req, res); } else { // !latch.await(...) reportError(req, res, HttpURLConnection.HTTP_UNAVAILABLE, localStrings.getLocalString("rest.adapter.server.wait", - "Server cannot process this command at this time, please wait")); + "Server cannot process this command at this time, please wait"), null); } } catch (InterruptedException e) { reportError(req, res, HttpURLConnection.HTTP_UNAVAILABLE, localStrings.getLocalString("rest.adapter.server.wait", - "Server cannot process this command at this time, please wait")); //service unavailable + "Server cannot process this command at this time, please wait"), e); } catch (IOException e) { reportError(req, res, HttpURLConnection.HTTP_UNAVAILABLE, - localStrings.getLocalString("rest.adapter.server.ioexception", "REST: IO Exception " + e.getLocalizedMessage())); //service unavailable + localStrings.getLocalString("rest.adapter.server.ioexception", "REST: IO Exception " + e.getLocalizedMessage()), e); } catch (RemoteAdminAccessException e) { reportError(req, res, HttpURLConnection.HTTP_FORBIDDEN, localStrings.getLocalString("rest.adapter.auth.forbidden", - "Remote access not allowed. If you desire remote access, please turn on secure admin")); + "Remote access not allowed. If you desire remote access, please turn on secure admin"), e); } catch (LoginException e) { int status = HttpURLConnection.HTTP_UNAUTHORIZED; String msg = localStrings.getLocalString("rest.adapter.auth.userpassword", "Invalid user name or password"); res.setHeader(HEADER_AUTHENTICATE, "BASIC"); - reportError(req, res, status, msg); + reportError(req, res, status, msg, e); } catch (Exception e) { // TODO: This string is duplicated. Can we pull this text out of the logging bundle? String msg = localStrings.getLocalString("rest.adapter.server.exception", "An error occurred while processing the request. Please see the server logs for details."); - RestLogging.restLogger.log(Level.INFO, RestLogging.SERVER_ERROR, e); - reportError(req, res, HttpURLConnection.HTTP_UNAVAILABLE, msg); //service unavailable + LOG.log(INFO, RestLogging.SERVER_ERROR, e); + reportError(req, res, HttpURLConnection.HTTP_UNAVAILABLE, msg, e); } } + @Override + public String toString() { + return getClass().getSimpleName() + "[" + + "name=" + getName() + + ", contextRoot=" + getContextRoot() + + ", instanceName=" + serverContext.getInstanceName() + + "]"; + } + private String getAcceptedMimeType(Request req) { String type = null; String requestURI = req.getRequestURI(); @@ -280,22 +294,17 @@ protected JerseyContainer exposeContext() throws EndpointRegistrationException { } private JerseyContainer getJerseyContainer(ResourceConfig config) { - RestLogging.restLogger.log(Level.FINEST, - () -> this + ": Creating Jersey container for " + HttpHandler.class + " and " + config); + LOG.log(DEBUG, () -> this + ": Creating Jersey container for " + HttpHandler.class + " and " + config); final GrizzlyHttpContainer httpHandler = ContainerFactory.createContainer(GrizzlyHttpContainer.class, config); final ServiceLocator jerseyLocator = httpHandler.getApplicationHandler().getInjectionManager().getInstance(ServiceLocator.class); ExtrasUtilities.enableTopicDistribution(jerseyLocator); - return new JerseyContainer() { - @Override - public void service(Request request, Response response) throws Exception { - httpHandler.service(request, response); - } - }; + return httpHandler::service; } - private void reportError(Request req, Response res, int statusCode, String msg) { + private void reportError(Request req, Response res, int statusCode, String msg, Exception exception) { + LOG.log(WARNING, "reportError(req, res, statusCode=" + statusCode + ", msg, e)", exception); try { - // TODO: There's a lot of arm waving and flailing here. I'd like this to be cleaner, but I don't + // TODO: There's a lot of arm waving and failing here. I'd like this to be cleaner, but I don't // have time at the moment. jdlee 8/11/10 RestActionReporter report = new RestActionReporter(); //getClientActionReport(req); report.setActionExitCode(ActionReport.ExitCode.FAILURE); @@ -318,7 +327,9 @@ private void reportError(Request req, Response res, int statusCode, String msg) res.getOutputStream().flush(); res.finish(); } catch (Exception e) { - throw new RuntimeException(e); + RuntimeException failure = new RuntimeException(exception); + failure.addSuppressed(e); + throw failure; } } } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestCommandResourceProvider.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestCommandResourceProvider.java index f7fa51ae47a..aedb4859257 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestCommandResourceProvider.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestCommandResourceProvider.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -37,6 +38,7 @@ import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.hk2.utilities.Binder; import org.glassfish.internal.api.ServerContext; +import org.glassfish.jersey.logging.LoggingFeature; import org.glassfish.jersey.media.sse.SseFeature; import org.glassfish.jersey.message.MessageProperties; import org.glassfish.jersey.server.ResourceConfig; @@ -52,10 +54,6 @@ */ public class RestCommandResourceProvider extends AbstractRestResourceProvider { - public RestCommandResourceProvider() { - super(); - } - @Override public boolean enableModifAccessToInstances() { return true; @@ -94,8 +92,6 @@ public static Set> getResourceClasses() { //ProgressStatus r.add(ProgressStatusJsonProvider.class); r.add(ProgressStatusEventJsonProvider.class); - // //Debuging filters - // r.add(LoggingFilter.class); return r; } @@ -125,6 +121,7 @@ public ResourceConfig getResourceConfig(Set> classes, final ServerConte rc.property(ServerProperties.WADL_FEATURE_DISABLE, true); rc.property(ServerProperties.BV_FEATURE_DISABLE, true); rc.property(ServerProperties.RESOURCE_VALIDATION_DISABLE, true); + rc.register(LoggingFeature.class); return rc; } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestManagementResourceProvider.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestManagementResourceProvider.java index 52d135dff1a..6ec82723757 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestManagementResourceProvider.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestManagementResourceProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2024, 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -21,13 +21,12 @@ import jakarta.ws.rs.core.Feature; +import java.lang.System.Logger; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.logging.Level; import org.glassfish.admin.rest.JavadocWadlGeneratorConfig; -import org.glassfish.admin.rest.RestLogging; import org.glassfish.admin.rest.RestResource; import org.glassfish.admin.rest.generator.ASMResourcesGenerator; import org.glassfish.admin.rest.generator.ResourcesGenerator; @@ -46,16 +45,19 @@ import org.glassfish.jersey.server.ServerProperties; import org.jvnet.hk2.config.Dom; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.ERROR; + /** * Responsible for providing ReST resources for management operations. */ public class RestManagementResourceProvider extends AbstractRestResourceProvider { + private static final Logger LOG = System.getLogger(RestManagementResourceProvider.class.getName()); @Override public Feature getJsonFeature() { - RestLogging.restLogger.log(Level.SEVERE, "Hey, you... FIX ME!!! {0}", RestManagementResourceProvider.class.getName()); + LOG.log(ERROR, "Hey, you... FIX ME!!! {0}", RestManagementResourceProvider.class.getName()); return super.getJsonFeature(); - // return new JacksonFeature(); } @Override @@ -68,7 +70,7 @@ public ResourceConfig getResourceConfig(Set> classes, final ServerConte final ServiceLocator serviceLocator, final Set additionalBinders) throws EndpointRegistrationException { ResourceConfig rc = super.getResourceConfig(classes, serverContext, serviceLocator, additionalBinders); - RestLogging.restLogger.log(Level.FINEST, () -> "Extending binding configuration with " + this); + LOG.log(DEBUG, () -> "Extending binding configuration with " + this); registerExtendedWadlConfig(classes, rc, serviceLocator); rc.register(ExceptionFilter.class); @@ -78,6 +80,7 @@ public ResourceConfig getResourceConfig(Set> classes, final ServerConte @Override public Set> getResourceClasses(ServiceLocator serviceLocator) { + LOG.log(DEBUG, "getResourceClasses(serviceLocator={0})", serviceLocator); // return getLazyJersey().getResourcesConfigForManagement(locatorBridge); generateASM(serviceLocator); @@ -85,7 +88,7 @@ public Set> getResourceClasses(ServiceLocator serviceLocator) { try { domainResourceClass = Class.forName("org.glassfish.admin.rest.resources.generatedASM.DomainResource"); } catch (ClassNotFoundException ex) { - RestLogging.restLogger.log(Level.SEVERE, null, ex); + LOG.log(ERROR, "Failed to load DomainResource class!", ex); } final Set> r = new HashSet<>(); @@ -177,7 +180,7 @@ private void generateASM(ServiceLocator habitat) { resourcesGenerator.generateSingle(dom.document.getRoot().model, dom.document); resourcesGenerator.endGeneration(); } catch (Exception ex) { - RestLogging.restLogger.log(Level.SEVERE, null, ex); + LOG.log(ERROR, "Failed resource generation.", ex); } } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestMonitoringResourceProvider.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestMonitoringResourceProvider.java index 8b5a430b37d..b2b15284f3e 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestMonitoringResourceProvider.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/adapter/RestMonitoringResourceProvider.java @@ -30,9 +30,6 @@ public class RestMonitoringResourceProvider extends AbstractRestResourceProvider @Override public Set> getResourceClasses(ServiceLocator habitat) { - // return getLazyJersey().getResourcesConfigForMonitoring(habitat); - // @Override - // public Set> getResourcesConfigForMonitoring(ServiceLocator habitat) { final Set> r = new HashSet<>(); r.add(org.glassfish.admin.rest.resources.MonitoringResource.class); diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/metadata/ParamMetadata.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/metadata/ParamMetadata.java index 4e082d13bdf..9df639b8643 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/metadata/ParamMetadata.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/composite/metadata/ParamMetadata.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -16,31 +17,34 @@ package org.glassfish.admin.rest.composite.metadata; +import java.lang.System.Logger; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.util.logging.Level; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.glassfish.admin.rest.OptionsCapable; -import org.glassfish.admin.rest.RestLogging; import org.glassfish.admin.rest.composite.CompositeUtil; import org.jvnet.hk2.config.Attribute; +import static java.lang.System.Logger.Level.ERROR; + /** * * @author jdlee */ public class ParamMetadata { + private static final Logger LOG = System.getLogger(ParamMetadata.class.getName()); + private String name; private Type type; private String help; private Object defaultValue; - private boolean readOnly = false; - private boolean confidential = false; - private boolean immutable = false; - private boolean createOnly = false; + private boolean readOnly; + private boolean confidential; + private boolean immutable; + private boolean createOnly; private OptionsCapable context; public ParamMetadata() { @@ -157,16 +161,17 @@ private Object getDefaultValue(Annotation[] annos) { defval = ((DefaultsGenerator) context).getDefaultValue(name); } else if (clazz != null && clazz != Void.class) { if (DefaultsGenerator.class.isAssignableFrom(clazz)) { - defval = ((DefaultsGenerator) clazz.newInstance()).getDefaultValue(name); + defval = ((DefaultsGenerator) clazz.getDeclaredConstructor().newInstance()).getDefaultValue(name); } else { - RestLogging.restLogger.log(Level.SEVERE, RestLogging.DOESNT_IMPLEMENT_DEFAULTS_GENERATOR); + LOG.log(ERROR, + "The " + clazz + " specified by generator does not implement DefaultsGenerator"); } } else { defval = parseValue(def.value()); } break; - } catch (Exception ex) { - RestLogging.restLogger.log(Level.SEVERE, null, ex); + } catch (Exception e) { + LOG.log(ERROR, "Failed to resolve the default value for annotation " + annos, e); } } else if (Attribute.class.isAssignableFrom(annotation.getClass())) { Attribute attr = (Attribute) annotation; @@ -199,10 +204,9 @@ private Object parseValue(String value) { if (clazz.equals(Float.TYPE) || clazz.equals(Float.class)) { return Float.valueOf(value); } - // TBD - arrays/lists of values - RestLogging.restLogger.log(Level.SEVERE, RestLogging.UNSUPPORTED_FIXED_VALUE); + LOG.log(ERROR, "The value '" + value + "' cannot be converted to the property " + type); } catch (NumberFormatException e) { - RestLogging.restLogger.log(Level.SEVERE, RestLogging.VALUE_DOES_NOT_MATCH_TYPE); + LOG.log(ERROR, "The value '" + value + "' cannot be converted to the property " + type); } return null; } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMClassWriter.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMClassWriter.java index 6e39eccd684..50a496d9541 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMClassWriter.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMClassWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022, 2025 Contributors to the Eclipse Foundation. + * Copyright (c) 2022, 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 @@ -22,19 +22,22 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.lang.System.Logger; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.ProtectionDomain; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Level; -import org.glassfish.admin.rest.RestLogging; import org.glassfish.admin.rest.utils.ResourceUtil; import org.glassfish.hk2.api.ServiceLocator; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; +import static java.lang.System.Logger.Level.DEBUG; +import static java.lang.System.Logger.Level.ERROR; import static org.glassfish.embeddable.GlassFishVariable.INSTALL_ROOT; import static org.objectweb.asm.Opcodes.AASTORE; import static org.objectweb.asm.Opcodes.ACC_PROTECTED; @@ -73,20 +76,18 @@ public class ASMClassWriter implements ClassWriter { private final static String CREATE_AND_INITIALIZE_SIG = "(Ljava/lang/Class;)Ljava/lang/Object;"; private final org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(0); + private static final Logger LOG = System.getLogger(ASMClassWriter.class.getName()); private String className; private ServiceLocator habitat; private final String generatedPath; private final Map generatedMethods = new HashMap<>(); - // private String baseClassName; - // private String resourcePath; public ASMClassWriter(ServiceLocator habitat, String generatedPath, String className, String baseClassName, String resourcePath) { this.habitat = habitat; this.className = className; this.generatedPath = generatedPath; - // this.baseClassName = baseClassName; - // this.resourcePath = resourcePath; - if (baseClassName.indexOf("TemplateCommand") != -1) { //constructor is created in createCommandResourceConstructor + if (baseClassName.indexOf("TemplateCommand") != -1) { + // constructor is created in createCommandResourceConstructor return; } if (baseClassName.indexOf(".") != -1) { @@ -97,7 +98,7 @@ public ASMClassWriter(ServiceLocator habitat, String generatedPath, String class cw.visit(V17, ACC_PUBLIC + ACC_SUPER, generatedPath + className, null, baseClassName, null); if (resourcePath != null) { - RestLogging.restLogger.log(Level.FINE, "Creating resource with path {0} (1)", resourcePath); + LOG.log(DEBUG, "Creating resource with path {0} (in constructor)", resourcePath); AnnotationVisitor av0 = cw.visitAnnotation("Ljakarta/ws/rs/Path;", true); av0.visit("value", "/" + resourcePath + "/"); av0.visitEnd(); @@ -121,7 +122,7 @@ public void createCustomResourceMapping(String resourceClassName, String mapping String baseClassName = generatedPath + className; MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "get" + resourceClassName, "()L" + completeName + ";", null, null); - RestLogging.restLogger.log(Level.FINE, "Creating resource with path {0} (2)", mappingPath); + LOG.log(DEBUG, "Creating resource with path {0} (in createCustomResourceMapping)", mappingPath); AnnotationVisitor av0 = mv.visitAnnotation("Ljakarta/ws/rs/Path;", true); av0.visit("value", mappingPath + "/"); av0.visitEnd(); @@ -229,7 +230,7 @@ public void createGetCommandResource(String commandResourceClassName, String res MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "get" + commandResourceClassName, "()L" + generatedPath + commandResourceClassName + ";", null, null); - RestLogging.restLogger.log(Level.FINE, "Creating resource with path {0} (3)", resourcePath); + LOG.log(DEBUG, "Creating resource with path {0} (in createGetCommandResource)", resourcePath); AnnotationVisitor av0 = mv.visitAnnotation("Ljakarta/ws/rs/Path;", true); av0.visit("value", resourcePath + "/"); av0.visitEnd(); @@ -331,12 +332,12 @@ public void createCommandResourceConstructor(String commandResourceClassName, St public void done() { cw.visitEnd(); try { - defineClass(this.getClass(), cw.toByteArray()); + defineClass(getClass(), cw.toByteArray()); if ("true".equals(System.getenv("REST_DEBUG"))) { debug(className, cw.toByteArray()); } } catch (Exception ex) { - RestLogging.restLogger.log(Level.SEVERE, null, ex); + LOG.log(ERROR, "Failed to define " + getClass(), ex); } } @@ -378,7 +379,7 @@ public void createGetChildResource(String path, String childResourceClassName) { generatedMethods.put(methodName, childClass); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, methodName, "()L" + childClass + ";", null, null); - RestLogging.restLogger.log(Level.FINE, "Creating resource with path {0} (4)", path); + LOG.log(DEBUG, "Creating resource with path {0} (in createGetChildResource)", path); AnnotationVisitor av0 = mv.visitAnnotation("Ljakarta/ws/rs/Path;", true); av0.visit("value", path + "/"); av0.visitEnd(); @@ -406,7 +407,7 @@ public void createGetChildResourceForListResources(String keyAttributeName, Stri MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "get" + childResourceClassName, "(Ljava/lang/String;)L" + generatedPath + childResourceClassName + ";", null, null); - RestLogging.restLogger.log(Level.FINE, "Creating resource with path {0} (5)", keyAttributeName); + LOG.log(DEBUG, "Creating resource with path {0} (in createGetChildResourceForListResources)", keyAttributeName); AnnotationVisitor av0 = mv.visitAnnotation("Ljakarta/ws/rs/Path;", true); av0.visit("value", "{" + keyAttributeName + "}/"); av0.visitEnd(); @@ -472,14 +473,13 @@ public byte[] getByteClass() { private void defineClass(Class similarClass, byte[] classBytes) throws Exception { String generatedClassName = "org.glassfish.admin.rest.resources.generatedASM." + className; - RestLogging.restLogger.log(Level.FINEST, "Generating class {0}", generatedClassName); + LOG.log(DEBUG, "Generating class {0}", generatedClassName); ClassLoader loader = similarClass.getClassLoader(); ProtectionDomain pd = similarClass.getProtectionDomain(); - byte[] byteContent = getByteClass(); - ClassGenerator.defineClass(loader, generatedClassName, byteContent, pd); + ClassGenerator.defineClass(loader, generatedClassName, getByteClass(), pd); try { loader.loadClass(generatedClassName); - } catch (ClassNotFoundException cnfEx) { + } catch (Exception cnfEx) { throw new GeneratorException(cnfEx); } } @@ -500,31 +500,21 @@ private void debug(String clsName, byte[] classData) { clsName = clsName.substring(index + 1); } - FileOutputStream fos = null; - try { - String rootPath = System.getProperty(INSTALL_ROOT.getSystemPropertyName()) + File.separator - + "lib" + File.separator + "rest" + File.separator; - File parentDir = new File(rootPath); - if (!parentDir.exists()) { - if (!parentDir.mkdirs()) { - throw new RuntimeException("Unable to create parent directory for generated class file logging"); - } + Path parentDir = Path.of(System.getProperty(INSTALL_ROOT.getSystemPropertyName())).resolve(Path.of("lib", "rest")); + if (!Files.isDirectory(parentDir)) { + try { + Files.createDirectories(parentDir); + } catch (IOException e) { + throw new RuntimeException("Unable to create parent directory for generated class file logging", e); } + } - fos = new FileOutputStream(new File(parentDir, clsName + ".class")); + File classFile = parentDir.resolve(clsName + ".class").toFile(); + try (FileOutputStream fos = new FileOutputStream(classFile)) { fos.write(classData); fos.flush(); - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException ex) { - RestLogging.restLogger.log(Level.SEVERE, null, ex); - } - } + } catch (Exception e) { + LOG.log(ERROR, "Failed to write the generated class to " + classFile, e); } } - } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMResourcesGenerator.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMResourcesGenerator.java index f3ea2421d2a..9f4ec70a992 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMResourcesGenerator.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ASMResourcesGenerator.java @@ -17,16 +17,20 @@ package org.glassfish.admin.rest.generator; +import java.lang.System.Logger; + import org.glassfish.hk2.api.ServiceLocator; +import static java.lang.System.Logger.Level.TRACE; + /** * @author Ludovic Champenois */ public class ASMResourcesGenerator extends ResourcesGeneratorBase { + private static final Logger LOG = System.getLogger(ASMResourcesGenerator.class.getName()); - protected final static String GENERATED_PATH = "org/glassfish/admin/rest/resources/generatedASM/"; - - protected final static String GENERATED_PACKAGE = GENERATED_PATH.replace("/", "."); + private final static String GENERATED_PATH = "org/glassfish/admin/rest/resources/generatedASM/"; + private final static String GENERATED_PACKAGE = GENERATED_PATH.replace("/", "."); public ASMResourcesGenerator(ServiceLocator habitat) { super(habitat); @@ -34,8 +38,10 @@ public ASMResourcesGenerator(ServiceLocator habitat) { @Override public ClassWriter getClassWriter(String className, String baseClassName, String resourcePath) { + String fullClassName = GENERATED_PACKAGE + className; try { - Class.forName(GENERATED_PACKAGE + className); + Class.forName(fullClassName); + LOG.log(TRACE, () -> "Class already exists, no need to regenerate it: " + fullClassName); return null; } catch (ClassNotFoundException ex) { return new ASMClassWriter(habitat, GENERATED_PATH, className, baseClassName, resourcePath); @@ -44,6 +50,6 @@ public ClassWriter getClassWriter(String className, String baseClassName, String @Override public String endGeneration() { - return "Code Generation done at "; + return "Code Generation done at "; } } diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ResourcesGeneratorBase.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ResourcesGeneratorBase.java index 6db6a059c31..42bc8d3a44e 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ResourcesGeneratorBase.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/generator/ResourcesGeneratorBase.java @@ -17,6 +17,7 @@ package org.glassfish.admin.rest.generator; +import java.lang.System.Logger; import java.util.HashSet; import java.util.List; import java.util.Locale; @@ -31,6 +32,7 @@ import org.jvnet.hk2.config.ConfigModel; import org.jvnet.hk2.config.DomDocument; +import static java.lang.System.Logger.Level.TRACE; import static java.util.Map.entry; /** @@ -39,6 +41,7 @@ */ public abstract class ResourcesGeneratorBase implements ResourcesGenerator { + private static final Logger LOG = System.getLogger(ResourcesGeneratorBase.class.getName()); private static final Set alreadyGenerated = new HashSet<>(); ServiceLocator habitat; @@ -50,7 +53,6 @@ public ResourcesGeneratorBase(ServiceLocator habitat) { * Generate REST resource for a single config model. */ @Override - @SuppressWarnings("rawtypes") public void generateSingle(ConfigModel model, DomDocument domDocument) { configModelVisited(model); //processRedirectsAnnotation(model); // TODO need to extract info from RestRedirect Annotations @@ -58,8 +60,10 @@ public void generateSingle(ConfigModel model, DomDocument domDocument) { String serverConfigName = ResourceUtil.getUnqualifiedTypeName(model.targetTypeName); String beanName = getBeanName(serverConfigName); String className = getClassName(beanName); + LOG.log(TRACE, () -> "Processing bean " + beanName + ", class " + className); if (alreadyGenerated(className)) { + LOG.log(TRACE, () -> "Nothing to do, already generated: " + className); return; } @@ -72,58 +76,59 @@ public void generateSingle(ConfigModel model, DomDocument domDocument) { } ClassWriter classWriter = getClassWriter(className, baseClassName, resourcePath); - - if (classWriter != null) { - generateCommandResources(beanName, classWriter); - - generateGetDeleteCommandMethod(beanName, classWriter); - - generateCustomResourceMapping(beanName, classWriter); - - for (String elementName : model.getElementNames()) { - ConfigModel.Property childElement = model.getElement(elementName); - if (elementName.equals("*")) { - ConfigModel.Node node = (ConfigModel.Node) childElement; - ConfigModel childModel = node.getModel(); - List subChildConfigModels = ResourceUtil.getRealChildConfigModels(childModel, domDocument); - for (ConfigModel subChildConfigModel : subChildConfigModels) { - if (ResourceUtil.isOnlyATag(childModel) || ResourceUtil.isOnlyATag(subChildConfigModel) - || subChildConfigModel.getAttributeNames().isEmpty() || hasSingletonAnnotation(subChildConfigModel)) { - String childResourceClassName = getClassName( - ResourceUtil.getUnqualifiedTypeName(subChildConfigModel.targetTypeName)); - String childPath = subChildConfigModel.getTagName(); - classWriter.createGetChildResource(childPath, childResourceClassName); - generateSingle(subChildConfigModel, domDocument); - } else { - processNonLeafChildConfigModel(subChildConfigModel, childElement, domDocument, classWriter); - - } - } - } else if (childElement.isLeaf()) { - if (childElement.isCollection()) { - // handle the CollectionLeaf config objects. - // JVM Options is an example of CollectionLeaf object. - String childResourceBeanName = getBeanName(elementName); - String childResourceClassName = getClassName(childResourceBeanName); - classWriter.createGetChildResource(elementName, childResourceClassName); - - // create resource class - generateCollectionLeafResource(childResourceBeanName); + if (classWriter == null) { + LOG.log(TRACE, () -> "Nothing to do, retrieved null classWriter for " + className); + return; + } + generateCommandResources(beanName, classWriter); + + generateGetDeleteCommandMethod(beanName, classWriter); + + generateCustomResourceMapping(beanName, classWriter); + + for (String elementName : model.getElementNames()) { + ConfigModel.Property childElement = model.getElement(elementName); + if (elementName.equals("*")) { + ConfigModel.Node node = (ConfigModel.Node) childElement; + ConfigModel childModel = node.getModel(); + List subChildConfigModels = ResourceUtil.getRealChildConfigModels(childModel, domDocument); + for (ConfigModel subChildConfigModel : subChildConfigModels) { + if (ResourceUtil.isOnlyATag(childModel) || ResourceUtil.isOnlyATag(subChildConfigModel) + || subChildConfigModel.getAttributeNames().isEmpty() || hasSingletonAnnotation(subChildConfigModel)) { + String childResourceClassName = getClassName( + ResourceUtil.getUnqualifiedTypeName(subChildConfigModel.targetTypeName)); + String childPath = subChildConfigModel.getTagName(); + classWriter.createGetChildResource(childPath, childResourceClassName); + generateSingle(subChildConfigModel, domDocument); } else { - String childResourceBeanName = getBeanName(elementName); - String childResourceClassName = getClassName(childResourceBeanName); - classWriter.createGetChildResource(elementName, childResourceClassName); + processNonLeafChildConfigModel(subChildConfigModel, childElement, domDocument, classWriter); - // create resource class - generateLeafResource(childResourceBeanName); } - } else { // => !childElement.isLeaf() - processNonLeafChildElement(elementName, childElement, domDocument, classWriter); } - } + } else if (childElement.isLeaf()) { + if (childElement.isCollection()) { + // handle the CollectionLeaf config objects. + // JVM Options is an example of CollectionLeaf object. + String childResourceBeanName = getBeanName(elementName); + String childResourceClassName = getClassName(childResourceBeanName); + classWriter.createGetChildResource(elementName, childResourceClassName); + + // create resource class + generateCollectionLeafResource(childResourceBeanName); + } else { + String childResourceBeanName = getBeanName(elementName); + String childResourceClassName = getClassName(childResourceBeanName); + classWriter.createGetChildResource(elementName, childResourceClassName); - classWriter.done(); + // create resource class + generateLeafResource(childResourceBeanName); + } + } else { // => !childElement.isLeaf() + processNonLeafChildElement(elementName, childElement, domDocument, classWriter); + } } + + classWriter.done(); } public void generateList(ConfigModel model, DomDocument domDocument) { @@ -284,23 +289,25 @@ void generateGetPostCommandMethod(String resourceName, ClassWriter classWriter) */ private void generateCommandResources(String parentBeanName, ClassWriter parentWriter) { List commandMetaData = CommandResourceMetaData.getMetaData(parentBeanName); - if (commandMetaData.size() > 0) { - for (CommandResourceMetaData metaData : commandMetaData) { - if (ResourceUtil.commandIsPresent(habitat, metaData.command)) { // only if the command really exists - String commandResourceName = parentBeanName + getBeanName(metaData.resourcePath); - String commandResourceClassName = getClassName(commandResourceName); - - // Generate command resource class - generateCommandResourceClass(parentBeanName, metaData); + if (commandMetaData.isEmpty()) { + LOG.log(TRACE, () -> "Nothing to do, null command data for parent bean name: " + parentBeanName); + return; + } + for (CommandResourceMetaData metaData : commandMetaData) { + if (ResourceUtil.commandIsPresent(habitat, metaData.command)) { // only if the command really exists + String commandResourceName = parentBeanName + getBeanName(metaData.resourcePath); + String commandResourceClassName = getClassName(commandResourceName); - // Generate getCommandResource() method in parent - parentWriter.createGetCommandResource(commandResourceClassName, metaData.resourcePath); - } + // Generate command resource class + generateCommandResourceClass(parentBeanName, metaData); + // Generate getCommandResource() method in parent + parentWriter.createGetCommandResource(commandResourceClassName, metaData.resourcePath); } - // Generate GetCommandResourcePaths() method in parent - parentWriter.createGetCommandResourcePaths(commandMetaData); + } + // Generate GetCommandResourcePaths() method in parent + parentWriter.createGetCommandResourcePaths(commandMetaData); } /** diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlInputReader.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlInputReader.java index 28ec58f2d39..6788982fb8e 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlInputReader.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/readers/XmlInputReader.java @@ -123,11 +123,13 @@ public Object nextEntity(char a) throws InputException { return e != null ? e : a + s + ";"; } + /** - * Returns the next XML meta token. This is used for skipping over and structures. + * Returns the next XML meta token. This is used for skipping over {@code } and + * {@code } structures. * - * @return Syntax characters (< > / = ! ?) are returned as Character, and strings and names are returned as - * Boolean. We don't care what the values actually are. + * @return Syntax characters (< > / = ! ?) are returned as Character, and strings + * and names are returned as Boolean. We don't care what the values actually are. * @throws InputException If a string is not properly closed or if the XML is badly structured. */ public Object nextMeta() throws InputException { diff --git a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/ResourceUtil.java b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/ResourceUtil.java index 71f0bcb306c..146b60537ed 100644 --- a/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/ResourceUtil.java +++ b/nucleus/admin/rest/rest-service/src/main/java/org/glassfish/admin/rest/utils/ResourceUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024, 2025 Contributors to the Eclipse Foundation. + * Copyright (c) 2024, 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -30,6 +30,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; +import java.lang.System.Logger; import java.lang.reflect.Method; import java.net.URI; import java.net.URISyntaxException; @@ -45,14 +46,12 @@ import java.util.Properties; import java.util.Set; import java.util.TreeMap; -import java.util.logging.Level; import java.util.regex.Pattern; import javax.security.auth.Subject; import javax.security.auth.login.LoginException; import org.glassfish.admin.rest.Constants; -import org.glassfish.admin.rest.RestLogging; import org.glassfish.admin.rest.generator.CommandResourceMetaData; import org.glassfish.admin.rest.provider.MethodMetaData; import org.glassfish.admin.rest.provider.ParameterMetaData; @@ -82,6 +81,9 @@ import org.jvnet.hk2.config.Dom; import org.jvnet.hk2.config.DomDocument; +import static java.lang.System.Logger.Level.ERROR; +import static java.lang.System.Logger.Level.TRACE; +import static java.lang.System.Logger.Level.WARNING; import static org.glassfish.admin.rest.provider.ProviderUtil.getElementLink; import static org.glassfish.admin.rest.utils.Util.eleminateHypen; import static org.glassfish.admin.rest.utils.Util.getHtml; @@ -96,7 +98,7 @@ * @author Rajeshwar Patil */ public class ResourceUtil { - + private static final Logger LOG = System.getLogger(ResourceUtil.class.getName()); private static final String MESSAGE_PARAMETERS = "messageParameters"; private static RestConfig restConfig = null; // TODO: this is copied from org.jvnet.hk2.config.Dom. If we are not able to encapsulate the conversion in Dom, @@ -125,7 +127,7 @@ protected static byte[] getBytesFromStream(final InputStream is) { buffer.flush(); bytes = buffer.toByteArray(); } catch (IOException ex) { - RestLogging.restLogger.log(Level.SEVERE, RestLogging.IO_EXCEPTION, ex); + LOG.log(ERROR, "Failed reading from stream.", ex); } return bytes; @@ -385,7 +387,7 @@ public static MethodMetaData getMethodMetaData(ConfigModel configBeanModel) { } } } catch (MultiException e) { - e.printStackTrace(); + LOG.log(ERROR, "Metadata loading failed for model " + configBeanModel, e); } return methodMetaData; @@ -427,6 +429,7 @@ public static MethodMetaData getMethodMetaData2(Dom parent, ConfigModel childMod copyParameterMetaDataAttribute(localParam, parameterMetaData, Constants.OPTIONAL); } } catch (NoSuchMethodException e) { + LOG.log(TRACE, () -> "Method not found: " + methodName, e); } } @@ -442,6 +445,7 @@ public static MethodMetaData getMethodMetaData2(Dom parent, ConfigModel childMod copyParameterMetaDataAttribute(localParam, parameterMetaData, Constants.OPTIONAL); } } catch (NoSuchMethodException e) { + LOG.log(TRACE, () -> "Method not found: " + methodName, e); } methodMetaData.putParameterMetaData(attributeName, parameterMetaData); @@ -475,7 +479,7 @@ public static boolean commandIsPresent(ServiceLocator habitat, String commandNam habitat.getService(AdminCommand.class, commandName); return true; } catch (Exception e) { - + LOG.log(WARNING, () -> "Command service could not be loaded: " + commandName, e); } return false; } @@ -817,7 +821,7 @@ public static boolean isDeprecated(ConfigModel model) { Deprecated dep = cbp.getAnnotation(Deprecated.class); return dep != null; } catch (MultiException e) { - // e.printStackTrace(); + LOG.log(TRACE, "Deprecation check failed.", e); } return false; diff --git a/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/services/Service.java b/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/services/Service.java index b647f6a746c..3d5d1436187 100644 --- a/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/services/Service.java +++ b/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/services/Service.java @@ -26,7 +26,6 @@ * server with various service control mechanisms on various platforms. * * @since SJSAS 9.1 - * @see #isConfigValid * @author Kedar Mhaswade */ public interface Service { @@ -57,7 +56,7 @@ public interface Service { * Returns the tokens and values of the service as a map. This method converts a service into corresponding tokens and * their values. * - * @return tokens and values as a Map. + * @return tokens and values as a {@code Map}. */ Map tokensAndValues(); diff --git a/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/stringsubs/impl/algorithm/RadixTreeSubstitution.java b/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/stringsubs/impl/algorithm/RadixTreeSubstitution.java index af9c668b2a5..b7af622efe1 100644 --- a/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/stringsubs/impl/algorithm/RadixTreeSubstitution.java +++ b/nucleus/admin/server-mgmt/src/main/java/com/sun/enterprise/admin/servermgmt/stringsubs/impl/algorithm/RadixTreeSubstitution.java @@ -20,7 +20,7 @@ * Perform's string substitution for the given input. Substitution process look for the matching input in the given * {@link RadixTree} and replaced the string with the corresponding matching value. * - * @see {@link RadixTree} + * @see RadixTree */ class RadixTreeSubstitution { /** {@link RadixTree} used sub. */ diff --git a/nucleus/admin/template/src/main/resources/config/logging.properties b/nucleus/admin/template/src/main/resources/config/logging.properties index 7c67a6ec8c0..f35b703726e 100644 --- a/nucleus/admin/template/src/main/resources/config/logging.properties +++ b/nucleus/admin/template/src/main/resources/config/logging.properties @@ -74,6 +74,7 @@ com.sun.enterprise.security.level=INFO com.sun.enterprise.universal.level=INFO com.sun.enterprise.util.io.level=INFO com.sun.enterprise.v3.admin.level=INFO +com.sun.jdo.level=INFO com.sun.webui.level=INFO jakarta.level=INFO @@ -212,6 +213,7 @@ org.glassfish.hk2.classmodel.level=INFO org.glassfish.jdbc.level=INFO org.glassfish.jersey.level=INFO org.glassfish.jersey.message.internal.TracingLogger.level=INFO +org.glassfish.loadbalancer.level=INFO org.glassfish.main.level=INFO org.glassfish.main.jdke=INFO org.glassfish.naming.level=INFO diff --git a/nucleus/admin/template/src/main/resources/config/login.conf b/nucleus/admin/template/src/main/resources/config/login.conf index 0d7630f8f55..1ee843cc417 100644 --- a/nucleus/admin/template/src/main/resources/config/login.conf +++ b/nucleus/admin/template/src/main/resources/config/login.conf @@ -23,10 +23,6 @@ ldapRealm { com.sun.enterprise.security.auth.login.LDAPLoginModule required; }; -solarisRealm { - com.sun.enterprise.security.auth.login.SolarisLoginModule required; -}; - jdbcRealm { com.sun.enterprise.security.ee.authentication.glassfish.jdbc.JDBCLoginModule required; }; diff --git a/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/AsadminTrustManager.java b/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/AsadminTrustManager.java index 771f4de6821..80706235f3b 100644 --- a/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/AsadminTrustManager.java +++ b/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/AsadminTrustManager.java @@ -78,8 +78,8 @@ public void setInteractive(boolean mode) { /** * Checks if client is trusted given the certificate chain and authorization type string, e.g., "RSA". * - * @throws {@link CertificateException} - * @throws {@link UnsupportedOperationException} + * @throws CertificateException + * @throws UnsupportedOperationException */ @Override public void checkClientTrusted(X509Certificate[] x509Certificate, String authType) throws CertificateException { diff --git a/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/cache/CommandModelDataProvider.java b/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/cache/CommandModelDataProvider.java index 697a69a702d..d770ae34e28 100644 --- a/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/cache/CommandModelDataProvider.java +++ b/nucleus/admin/util/src/main/java/com/sun/enterprise/admin/util/cache/CommandModelDataProvider.java @@ -35,8 +35,8 @@ /** * Works with {@link com.sun.enterprise.admin.util.CachedCommandModel} and - * {@link com.sun.enterprise.admin.util.CommandModelData).
    This is hand made implementation which is focused - * on human readability and fastness. + * {@link com.sun.enterprise.admin.util.CommandModelData}.
    + * This is hand made implementation which is focused on human readability and fastness. * * @author mmares */ diff --git a/nucleus/cluster/ssh/src/main/java/org/glassfish/cluster/ssh/sftp/SFTPPath.java b/nucleus/cluster/ssh/src/main/java/org/glassfish/cluster/ssh/sftp/SFTPPath.java index c340f0238fd..ddd1ea3fbdc 100644 --- a/nucleus/cluster/ssh/src/main/java/org/glassfish/cluster/ssh/sftp/SFTPPath.java +++ b/nucleus/cluster/ssh/src/main/java/org/glassfish/cluster/ssh/sftp/SFTPPath.java @@ -341,7 +341,7 @@ public String toString() { * Converts the file's path to a SFTP path. * If the file is absolute, the path will be absolute. * The root prefix is removed (ie. C:\). - * The file separator in SFTP is always /. + * The file separator in SFTP is always /. * The result is normalized. * * @param file @@ -358,7 +358,7 @@ public static SFTPPath of(File file) { * Converts the file's path to a SFTP path. * If the file is absolute, the path will be absolute. * The root prefix is removed (ie. C:\). - * The file separator in SFTP is always /. + * The file separator in SFTP is always /. * The result is normalized. * * @param path diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java index 0e4cea49ca0..5bbc33dec31 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/base/SystemInfo.java @@ -99,7 +99,7 @@ public interface SystemInfo extends AMXProxy, Singleton, Utility { * Even documented items should be used only for informational purposes, * such as assessing performance. * - * @return Map + * @return {@code Map} */ @ManagedAttribute public Map getPerformanceMillis(); diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java index fbe370b1e08..09e94be25e6 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/config/AttributeResolver.java @@ -44,7 +44,7 @@ public interface AttributeResolver { * If the String is a template string, resolve its value if it can be resolved, or 'null' * if it cannot be resolved. *

    - * Examples:
    + * Examples: * *

          "${com.sun.aas.installRoot}" => "/glassfish"
    @@ -57,6 +57,7 @@ public interface AttributeResolver {
          * @param value any String
          * @return resolved value
          */
    +    @Deprecated
         @ManagedOperation(impact = MBeanOperationInfo.INFO)
         @Description("Resolve a (possible) ${...} attribute *value* to a real value")
         String resolveAttributeValue(
    @@ -65,6 +66,7 @@ String resolveAttributeValue(
     
     
         /** calls getAttribute(), then returns the resolved value or null */
    +    @Deprecated
         @ManagedOperation(impact = MBeanOperationInfo.INFO)
         @Description("Get and resolve a (possible) ${...} attribute to a real value")
         String resolveAttribute(
    @@ -73,6 +75,7 @@ String resolveAttribute(
     
     
         /** Get the Attribute and resolve it to a Boolean or null */
    +    @Deprecated
         @ManagedOperation(impact = MBeanOperationInfo.INFO)
         @Description("Get and resolve a (possible)  ${...} attribute to a Boolean, returns null if not found")
         Boolean resolveBoolean(
    @@ -81,6 +84,7 @@ Boolean resolveBoolean(
     
     
         /** Get the Attribute and resolve it to a Long or null */
    +    @Deprecated
         @ManagedOperation(impact = MBeanOperationInfo.INFO)
         @Description("Get and resolve a (possible)  ${...} attribute to a Long, returns null if not found")
         Long resolveLong(
    @@ -93,6 +97,7 @@ Long resolveLong(
          * have been annotated with @ResolveTo, then the value is of the correct type
          * (eg String, Boolean, Integer).
          */
    +    @Deprecated
         @ManagedOperation(impact = MBeanOperationInfo.INFO)
         @Description("Get and resolve attributes to values")
         AttributeList resolveAttributes(
    diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java
    index bc257ca01dc..88e35768d59 100644
    --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java
    +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/impl/config/AttributeResolverHelper.java
    @@ -27,19 +27,25 @@
      * Helper to resolve attribute configuration values eg
      * ${com.sun.aas.installRoot} once they have already been obtained in "raw"
      * form. If the goal is to fetch the attribute values in already-resolved form,
    - * do so directly via
    + * do so directly via @{link AttributeResolver#resolveAttribute}.
    + * 

    + * Values can be resolved into String, boolean or int. + *

    + * Example usage: * - * @{link AttributeResolver#resolveAttribute}.

    Values can be resolved into - * String, boolean or int.

    Example usage: - *

    + * 
    {@code
      * HTTPListenerConfig l = ...; // or any AMXConfigProxy sub-interface
      * AttributeResolverHelper h = new AttributeResolverHelper( l );
      * int port = h.resolveInt( l.getPort() );
    - * 
    Alternately, the static method form can be used:
    + * }
    + * + * Alternately, the static method form can be used: + * *
    + * {@code
      * HTTPListenerConfig l = ...; // or any AMXConfigProxy sub-interface
      * int port = AttributeResolverHelper.resolveInt( l, value );
    - * 
    + * }
    */ @Taxonomy( stability = Stability.UNCOMMITTED) public class AttributeResolverHelper extends VariableResolver { diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java index e05feba6ee5..a17bb3f3775 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogAnalyzer.java @@ -76,17 +76,17 @@ public interface LogAnalyzer { *

    * The timestamp obtained from each Map may be used as the timestamp when * calling {@link #getErrorDistribution}. For example:
    - * - final Map[] infos = logging.getErrorInfo();
    - for (int i = 0; i < infos.length; ++i) {
    - final Map info = infos[i];
    - final long timestamp = ((Long)info.get( TIMESTAMP_KEY )).longValue();
    -
    - Map counts = getErrorDistribution( timestamp );
    - } -
    * - * @return Map + *

    {@code
    +final Map[] infos = logging.getErrorInfo();
    +for (int i = 0; i < infos.length; ++i) {
    +    final Map info = infos[i];
    +    final long timestamp = ((Long)info.get( TIMESTAMP_KEY )).longValue();
    +    Map counts = getErrorDistribution( timestamp );
    +}
    +    }
    + * + * @return {@code Map} */ @ManagedAttribute Map[] getErrorInfo(); @@ -106,7 +106,7 @@ public interface LogAnalyzer { * returned by {@link #getErrorInfo}. Note that it is a 'long' not a 'Long' and is * required. * @param level - * @return Map + * @return {@code Map} */ @ManagedOperation Map getErrorDistribution( diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java index d4af72f6627..10c017944d2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/logging/LogRecordEmitter.java @@ -46,11 +46,9 @@ * transmitted. Instead, its important fields are extracted and placed into a Map * obtained as follows: * - *
    - * 
    + * 
    {@code
      *    final Map    fields  = (Map)notif.getUserData();
    - * 
    - * 
    + * }
    * * Alternately, you may use {@link Util#getAMXNotificationValue} to extract any] * particular field. @@ -61,12 +59,13 @@ * *

    * Here is an example of how to retrieve the LogRecord information when a Notification is received: - *

    -final Notifcation notif        = ;
    -final String type       = notif.getType();
    -final LogRecord logRecord        = (LogRecord){@link Util#getAMXNotificationValue}( notif, LOG_RECORD_KEY );
    -final String    logRecordString        = (String){@link Util#getAMXNotificationValue}( notif, LOG_RECORD_STRING_KEY );
    -
    + * + *
    {@code
    +final Notifcation notif = ;
    +final String type = notif.getType();
    +final LogRecord logRecord = (LogRecord){@link Util#getAMXNotificationValue}( notif, LOG_RECORD_KEY );
    +final String logRecordString = (String){@link Util#getAMXNotificationValue}( notif, LOG_RECORD_STRING_KEY );
    +}
    * * @since AS 9.0 */ diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java index 5022e2364d2..b8ff043b4b2 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/AMXDebug.java @@ -52,7 +52,7 @@ potentially cause infinite recursion (and thus stack overflow). Notifications is complicated. This logging facility makes it possible to selectively view specific entities in the interactions that are occuring, on a fine-grained level, -something not possible with the server logging mechanism
  • +something not possible with the server logging mechanism
  • There is reason and justification for considering debugging diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java index 958fe06dea2..e7847ebe38d 100644 --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/FeatureAvailability.java @@ -41,7 +41,7 @@ class unless they are of general system interest. Features that are not FeatureAvailability.registerFeature( FeatureAvailability.MBEAN_SERVER_FEATURE, mbeanServer );

    Client Example
    -(arbitrary number of clients, multiple calls OK)
    +(arbitrary number of clients, multiple calls OK)

     ...client runs until feature is needed...
     final MBeanServer mbeanServer = (MBeanServer)
    diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java
    index 7a57e90bdf5..2eb71305801 100644
    --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java
    +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/TypeCast.java
    @@ -86,7 +86,7 @@ public final class TypeCast
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  Collection asCollection(final Object o)
         {
    -        return (Collection) Collection.class.cast(o);
    +        return Collection.class.cast(o);
         }
     
         /**
    @@ -106,20 +106,19 @@ public static  Collection asSerializableCollection(fi
         The caller should take appropriate care that the type of keys/values
         is correct, and may want to call {@link #checkMap} instead if there is
         any doubt.
    -    @return Map
    -    @return Map
    +    @return retyped original map
          */
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  Map asMap(final Object m)
         {
    -        return (Map) Map.class.cast(m);
    +        return Map.class.cast(m);
         }
     
         /**
         The caller should take appropriate care that the type of keys/values
         is correct, and may want to call {@link #checkSerializable} instead if there is
         any doubt.
    -    @return Map
    +    @return retyped original map
          */
         public static  Map asSerializableMap(final Object m)
         {
    @@ -133,12 +132,12 @@ public static  Map asSeria
         The caller should take appropriate care that the type of element
         is correct, and may want to call {@link #checkMap} instead if there is
         any doubt.
    -    @return Hashtable
    +    @return retyped original {@link Hashtable}
          */
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  Hashtable asHashtable(final Object o)
         {
    -        return (Hashtable) Hashtable.class.cast(o);
    +        return Hashtable.class.cast(o);
         }
     
         /**
    @@ -150,7 +149,7 @@ public static  Hashtable asHashtable(final Object o)
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  List asList(final Object list)
         {
    -        return (List) List.class.cast(list);
    +        return List.class.cast(list);
         }
     
         /**
    @@ -175,7 +174,7 @@ public static  List asSerializableList(final Object l
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  Set asSet(final Object s)
         {
    -        return (Set) Set.class.cast(s);
    +        return Set.class.cast(s);
         }
     
         /**
    @@ -210,7 +209,7 @@ public static  Set asSerializableSet(final Object s)
         @SuppressWarnings("unchecked")  // inherent/unavoidable for this method
         public static  Class asClass(final Class c)
         {
    -        return (Class) Class.class.cast(c);
    +        return Class.class.cast(c);
         }
     
         /**
    @@ -460,7 +459,7 @@ public static List checkedStringList(final List l)
         }
     
         /**
    -    Create a checked Map, first verifying that all keys
    +    Create a checked {@code Map}, first verifying that all keys
         and values are in fact String.
         @param m the Map
         @throws ClassCastException
    @@ -507,7 +506,7 @@ public static  List checkedList(final List l, final Class theClass)
         }
     
         /**
    -    Create a checked Map, first verifying that all keys
    +    Create a checked {@code Map}, first verifying that all keys
         and values are in fact String.
         @param m the Map
         @throws ClassCastException
    @@ -519,19 +518,3 @@ public static  Map checkedMap(final Map m, final Class keyC
         }
     
     }
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    diff --git a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java
    index 265ba0d8072..15e2851c0a7 100644
    --- a/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java
    +++ b/nucleus/common/amx-core/src/main/java/org/glassfish/admin/amx/util/jmx/JMXUtil.java
    @@ -681,7 +681,7 @@ public static Map attributeListToStringMap(final AttributeList a
                 final Attribute attr = (Attribute) attrs.get(i);
     
                 final Object value = attr.getValue();
    -            final String s = (String) (value == null ? null : "" + value);
    +            final String s = value == null ? null : "" + value;
                 map.put(attr.getName(), s);
             }
     
    @@ -1741,7 +1741,7 @@ public static Set queryNames(
     
         /**
         Get a Map from the user data field of a Notification.
    -    This variant requires Map.
    +    This variant requires {@code Map}.
          */
         public static  Map getUserDataMapString_Serializable(final Notification notif)
         {
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BaseCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BaseCache.java
    index 3f3068936df..b879e79cb40 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BaseCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BaseCache.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,7 +32,7 @@
      * BaseCache
      * Generic in-memory, abstract cache
      */
    -public class BaseCache implements Cache {
    +public class BaseCache implements Cache {
     
         /**
          * The resource bundle containing the localized message strings.
    @@ -76,17 +77,17 @@ public class BaseCache implements Cache {
         private Object  overflowCountLk = new Object();
     
         // table size
    -        protected int maxBuckets;
    +    protected int maxBuckets;
     
         // cache entries hash table
    -        protected CacheItem[] buckets;
    +    protected CacheItem[] buckets;
         // bucket-wide locks
    -        protected Object[]    bucketLocks;
    +    protected Object[] bucketLocks;
     
         // boolean status and locks for item thread-safe refreshes
    -        protected boolean[]   refreshFlags;
    +    protected boolean[] refreshFlags;
     
    -    protected ArrayList listeners = new ArrayList();
    +    protected ArrayList listeners = new ArrayList<>();
     
         /**
          * default constructor for the basic cache
    @@ -99,6 +100,7 @@ public BaseCache() { }
          * @param props opaque list of properties for a given cache implementation
          * @throws a generic Exception if the initialization failed
          */
    +    @Override
         public void init(int maxEntries, Properties props) throws Exception {
             init(maxEntries, DEFAULT_LOAD_FACTOR, props);
         }
    @@ -110,6 +112,7 @@ public void init(int maxEntries, Properties props) throws Exception {
          * @param props opaque list of properties for a given cache implementation
          * @throws a generic Exception if the initialization failed
          */
    +    @Override
         public void init(int maxEntries, float loadFactor, Properties props) {
     
             if (maxEntries <= 0) {
    @@ -122,19 +125,22 @@ public void init(int maxEntries, float loadFactor, Properties props) {
                 throw new IllegalArgumentException(msg);
             }
     
    -        if (maxEntries > MAX_ENTRIES)
    -             maxEntries = MAX_ENTRIES;
    +        if (maxEntries > MAX_ENTRIES) {
    +            maxEntries = MAX_ENTRIES;
    +        }
     
             this.maxEntries = maxEntries;
     
             // find a power of 2 >= maxEntries
             maxBuckets = 1;
    -        while (maxBuckets < maxEntries)
    +        while (maxBuckets < maxEntries) {
                 maxBuckets <<= 1;
    +        }
     
             //Cannot have the loadfactor as a negative value
    -        if( loadFactor < 0 )
    +        if( loadFactor < 0 ) {
                 loadFactor = 0;
    +        }
     
             /** initialize the threshold; a zero value for maxEntries
              *  implies no caching.
    @@ -160,6 +166,7 @@ public void init(int maxEntries, float loadFactor, Properties props) {
          * add the cache module listener
          * @param listener CacheListener implementation
          */
    +    @Override
         public void addCacheListener(CacheListener listener) {
             listeners.add(listener);
         }
    @@ -201,7 +208,7 @@ protected void handleOverflow() {
          *
          * Subclasses should enhance this implemntation.
          */
    -    protected CacheItem itemAdded(CacheItem item) {
    +    protected CacheItem itemAdded(CacheItem item) {
             if (isThresholdReached()) {
                 handleOverflow();
             }
    @@ -214,7 +221,7 @@ protected CacheItem itemAdded(CacheItem item) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemAccessed(CacheItem item) { }
    +    protected void itemAccessed(CacheItem item) { }
     
         /**
          * item value has been refreshed
    @@ -222,7 +229,7 @@ protected void itemAccessed(CacheItem item) { }
          * @param oldSize size of the previous value that was refreshed
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRefreshed(CacheItem item, int oldSize) { }
    +    protected void itemRefreshed(CacheItem item, int oldSize) { }
     
         /**
          * item value has been removed from the cache
    @@ -230,7 +237,7 @@ protected void itemRefreshed(CacheItem item, int oldSize) { }
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRemoved(CacheItem item) { }
    +    protected void itemRemoved(CacheItem item) { }
     
         /**
          * Cannot find an item with the given key and hashCode
    @@ -240,7 +247,7 @@ protected void itemRemoved(CacheItem item) { }
          * @returns the Object value associated with the item
          * Cache bucket is already synchronized by the caller
          */
    -    protected Object loadValue(Object key, int hashCode) {
    +    protected V loadValue(K key, int hashCode) {
             return null;
         }
     
    @@ -253,9 +260,8 @@ protected Object loadValue(Object key, int hashCode) {
          * subclasses may override to provide their own CacheItem extensions
          * e.g. one that permits persistence.
          */
    -    protected CacheItem createItem(int hashCode, Object key,
    -                                        Object value, int size) {
    -        return new CacheItem(hashCode, key, value, size);
    +    protected CacheItem createItem(int hashCode, K key, V value, int size) {
    +        return new CacheItem<>(hashCode, key, value, size);
         }
     
         /**
    @@ -280,7 +286,8 @@ protected final int getIndex(int hashCode) {
          * @param key of the entry
          * @return the index to be used in the cache
          */
    -    public final int getIndex(Object key) {
    +    @Override
    +    public final int getIndex(K key) {
             return getIndex(hash(key));
         }
     
    @@ -289,7 +296,8 @@ public final int getIndex(Object key) {
          * @param key lookup key
          * @returns the item stored at the key; null if not found.
          */
    -    public Object get(Object key) {
    +    @Override
    +    public V get(K key) {
             int hashCode = hash(key);
     
             return get(hashCode, key);
    @@ -300,34 +308,34 @@ public Object get(Object key) {
          * @param key lookup key
          * @returns the item stored at the key; null if not found.
          */
    -    public Object get(int hashCode, Object key) {
    +    public V get(int hashCode, K key) {
    +        int index = getIndex(hashCode);
    +        V value;
    +        CacheItem item = null;
     
    -                int index = getIndex(hashCode);
    -        Object value;
    -        CacheItem item = null;
    -
    -                synchronized (bucketLocks[index]) {
    -                    item = buckets[index];
    +        synchronized (bucketLocks[index]) {
    +            item = buckets[index];
     
    -                        for (; item != null; item = item.next) {
    -                                if ( (hashCode == item.hashCode) && eq(key, item.key) ) {
    -                                        break;
    -                                }
    -                        }
    +            for (; item != null; item = item.next) {
    +                if ((hashCode == item.hashCode) && eq(key, item.key)) {
    +                    break;
    +                }
    +            }
     
                 // update the stats in line
                 if (item != null) {
                     value = item.getValue();
                     itemAccessed(item);
    -            }
    -            else
    +            } else {
                     value = loadValue(key, hashCode);
    -                }
    +            }
    +        }
     
    -        if (item != null)
    +        if (item != null) {
                 incrementHitCount();
    -        else
    +        } else {
                 incrementMissCount();
    +        }
     
             return value;
         }
    @@ -337,8 +345,9 @@ public Object get(int hashCode, Object key) {
          * @param key lookup key
          * @returns true if there is an item stored at the key; false if not.
          */
    -    public boolean contains(Object key) {
    -            return (get(key) != null);
    +    @Override
    +    public boolean contains(K key) {
    +            return get(key) != null;
         }
     
         /**
    @@ -346,22 +355,23 @@ public boolean contains(Object key) {
          * @param key lookup key
          * @returns an Iterator over the items with the given key.
          */
    -    public Iterator getAll(Object key) {
    +    @Override
    +    public Iterator getAll(K key) {
             int hashCode = hash(key);
    -                int index = getIndex(hashCode);
    +        int index = getIndex(hashCode);
     
    -        ArrayList valueList = new ArrayList(entryCount);
    -                synchronized (bucketLocks[index]) {
    -                    CacheItem item = buckets[index];
    +        ArrayList valueList = new ArrayList<>(entryCount);
    +        synchronized (bucketLocks[index]) {
    +            CacheItem item = buckets[index];
     
    -                        for (; item != null; item = item.next) {
    -                                if ( (hashCode == item.hashCode) && eq(key, item.key) ) {
    +            for (; item != null; item = item.next) {
    +                if ((hashCode == item.hashCode) && eq(key, item.key)) {
                         incrementHitCount();
                         valueList.add(item.getValue());
    -                                }
    -                        }
    -
                     }
    +            }
    +
    +        }
     
             return valueList.iterator();
         }
    @@ -370,13 +380,13 @@ public Iterator getAll(Object key) {
          * get an Iterator for the keys stored in the cache
          * @returns an Iterator
          */
    -    public Iterator keys() {
    -        ArrayList keyList = new ArrayList(entryCount);
    +    @Override
    +    public Iterator keys() {
    +        ArrayList keyList = new ArrayList<>(entryCount);
     
             for (int index=0; index < maxBuckets; index++) {
                 synchronized (bucketLocks[index]) {
    -                for (CacheItem item = buckets[index]; item != null;
    -                                item = item.next) {
    +                for (CacheItem item = buckets[index]; item != null; item = item.next) {
                         keyList.add(item.key);
                     }
                 }
    @@ -390,13 +400,12 @@ public Iterator keys() {
          * @returns an Enumeration
          * XXX: should use Iterator which is based on Collections
          */
    -    public Enumeration elements() {
    -        Vector keyList = new Vector();
    -
    -        for (int index=0; index < maxBuckets; index++) {
    +    @Override
    +    public Enumeration elements() {
    +        Vector keyList = new Vector<>();
    +        for (int index = 0; index < maxBuckets; index++) {
                 synchronized (bucketLocks[index]) {
    -                for (CacheItem item = buckets[index]; item != null;
    -                                item = item.next) {
    +                for (CacheItem item = buckets[index]; item != null; item = item.next) {
                         keyList.addElement(item.key);
                     }
                 }
    @@ -409,12 +418,13 @@ public Enumeration elements() {
          * get an Iterator for the values stored in the cache
          * @returns an Iterator
          */
    -    public Iterator values() {
    -        ArrayList valueList = new ArrayList(entryCount);
    +    @Override
    +    public Iterator values() {
    +        ArrayList valueList = new ArrayList<>(entryCount);
     
             for (int index=0; index < maxBuckets; index++) {
                 synchronized (bucketLocks[index]) {
    -                for (CacheItem item = buckets[index]; item != null;
    +                for (CacheItem item = buckets[index]; item != null;
                                     item = item.next) {
                         valueList.add(item.value);
                     }
    @@ -431,7 +441,8 @@ public Iterator values() {
          * @param object item value to be stored
          * @returns the previous item stored at the key; null if not found.
          */
    -    public Object put(Object key, Object value) {
    +    @Override
    +    public V put(K key, V value) {
             int hashCode = hash(key);
     
             return _put(hashCode, key, value, -1, false);
    @@ -444,7 +455,8 @@ public Object put(Object key, Object value) {
          * @param size in bytes of the value being cached
          * @returns the previous item stored at the key; null if not found.
          */
    -    public Object put(Object key, Object value, int size) {
    +    @Override
    +    public V put(K key, V value, int size) {
             int hashCode = hash(key);
     
             return _put(hashCode, key, value, size, false);
    @@ -455,7 +467,8 @@ public Object put(Object key, Object value, int size) {
          * @param key lookup key
          * @param object item value to be stored
          */
    -    public void add(Object key, Object value) {
    +    @Override
    +    public void add(K key, V value) {
             int hashCode = hash(key);
     
             _put(hashCode, key, value, -1, true);
    @@ -469,7 +482,8 @@ public void add(Object key, Object value) {
          *
          * This function is suitable for multi-valued keys.
          */
    -    public void add(Object key, Object value, int size) {
    +    @Override
    +    public void add(K key, V value, int size) {
             int hashCode = hash(key);
     
             _put(hashCode, key, value, size, true);
    @@ -488,52 +502,51 @@ public void add(Object key, Object value, int size) {
          * it may call trimCache() if the cache reached its threshold -- which is
          * is probably not very intuitive.
          */
    -    protected Object _put(int hashCode, Object key,
    -                            Object value, int size, boolean addValue) {
    -                int index = getIndex(hashCode);
    +    protected V _put(int hashCode, K key, V value, int size, boolean addValue) {
    +        int index = getIndex(hashCode);
     
    -                CacheItem item, newItem = null, oldItem = null, overflow = null;
    -        Object oldValue;
    +        CacheItem item, newItem = null, oldItem = null, overflow = null;
    +        V oldValue;
             int oldSize = 0;
     
             // lookup the item
    -                synchronized (bucketLocks[index]) {
    -                        for (item = buckets[index]; item != null; item = item.next) {
    -                                if ((hashCode == item.hashCode) && eq(key, item.key)) {
    +        synchronized (bucketLocks[index]) {
    +            for (item = buckets[index]; item != null; item = item.next) {
    +                if ((hashCode == item.hashCode) && eq(key, item.key)) {
     
                         oldItem = item;
    -                                        break;
    -                                }
    -                        }
    +                    break;
    +                }
    +            }
     
                 // if there was no item in the cache, insert the given item
    -                        if (addValue || oldItem == null) {
    +            if (addValue || oldItem == null) {
                     newItem = createItem(hashCode, key, value, size);
     
                     // add the item at the head of the bucket list
    -                            newItem.next = buckets[index];
    -                            buckets[index] = newItem;
    +                newItem.next = buckets[index];
    +                buckets[index] = newItem;
     
                     oldValue = null;
                     overflow = itemAdded(newItem);
    -                        }
    -            else {
    +            } else {
                     oldSize = oldItem.getSize();
                     oldValue = oldItem.refreshValue(value, size);
                     itemRefreshed(oldItem, oldSize);
                 }
    -                }
    +        }
     
             if (newItem != null) {
                 incrementEntryCount();
                 incrementAddCount();
     
                 // make sure we are are not crossing the threshold
    -            if (overflow != null)
    +            if (overflow != null) {
                     trimItem(overflow);
    -        }
    -        else
    +            }
    +        } else {
                 incrementRefreshCount();
    +        }
     
             return oldValue;
         }
    @@ -543,14 +556,16 @@ protected Object _put(int hashCode, Object key,
          * @param key lookup key
          * @returns the item stored at the key; null if not found.
          */
    -    public Object remove(Object key) {
    +    @Override
    +    public V remove(K key) {
             int hashCode = hash(key);
     
    -        Object retVal  = null;
    -        CacheItem removed = _remove( hashCode, key, null);
    +        V retVal  = null;
    +        CacheItem removed = _remove( hashCode, key, null);
     
    -        if (removed != null)
    +        if (removed != null) {
                 retVal = removed.getValue();
    +        }
             return retVal;
         }
     
    @@ -560,12 +575,13 @@ public Object remove(Object key) {
          * @param key lookup key
          * @returns the item stored at the key; null if not found.
          */
    -    public Object remove(int hashCode, Object key) {
    -        Object retVal  = null;
    -        CacheItem removed = _remove( hashCode, key, null);
    +    public V remove(int hashCode, K key) {
    +        V retVal  = null;
    +        CacheItem removed = _remove( hashCode, key, null);
     
    -        if (removed != null)
    +        if (removed != null) {
                 retVal = removed.getValue();
    +        }
             return retVal;
         }
     
    @@ -575,14 +591,16 @@ public Object remove(int hashCode, Object key) {
          * @param value to match (for a multi-valued keys)
          * @returns the item stored at the key; null if not found.
          */
    -    public Object remove(Object key, Object value) {
    +    @Override
    +    public V remove(Object key, Object value) {
             int hashCode = hash(key);
     
    -        Object retVal  = null;
    -        CacheItem removed = _remove( hashCode, key, value);
    +        V retVal  = null;
    +        CacheItem removed = _remove( hashCode, key, value);
     
    -        if (removed != null)
    +        if (removed != null) {
                 retVal = removed.getValue();
    +        }
             return retVal;
         }
     
    @@ -593,20 +611,20 @@ public Object remove(Object key, Object value) {
          * @param value of the item to be matched
          * @returns the item stored at the key; null if not found.
          */
    -    protected CacheItem _remove(int hashCode, Object key, Object value) {
    -                int index = getIndex(hashCode);
    +    protected CacheItem _remove(int hashCode, Object key, Object value) {
    +        int index = getIndex(hashCode);
     
    -                CacheItem prev = null, item = null;
    +        CacheItem prev = null, item = null;
     
    -                synchronized (bucketLocks[index]) {
    -                        for (item = buckets[index]; item != null; item = item.next) {
    -                            if (hashCode == item.hashCode && key.equals(item.key)) {
    +        synchronized (bucketLocks[index]) {
    +            for (item = buckets[index]; item != null; item = item.next) {
    +                if (hashCode == item.hashCode && key.equals(item.key)) {
     
    -                                    if (value == null || value == item.value) {
    +                    if (value == null || value == item.value) {
     
                             if (prev == null) {
                                 buckets[index] = item.next;
    -                        } else  {
    +                        } else {
                                 prev.next = item.next;
                             }
                             item.next = null;
    @@ -614,9 +632,9 @@ protected CacheItem _remove(int hashCode, Object key, Object value) {
                             itemRemoved(item);
                             break;
                         }
    -                            }
    -                            prev = item;
    -                        }
    +                }
    +                prev = item;
    +            }
             }
     
             if (item != null) {
    @@ -624,8 +642,9 @@ protected CacheItem _remove(int hashCode, Object key, Object value) {
                 incrementRemovalCount();
     
                 incrementHitCount();
    -        } else
    +        } else {
                 incrementMissCount();
    +        }
     
             return item;
         }
    @@ -635,25 +654,24 @@ protected CacheItem _remove(int hashCode, Object key, Object value) {
          * @param item CacheItem to be removed
          * @return the item stored at the key; null if not found.
          */
    -    protected CacheItem _removeItem(CacheItem ritem) {
    +    protected CacheItem _removeItem(CacheItem ritem) {
    +        int index = getIndex(ritem.hashCode);
     
    -                int index = getIndex(ritem.hashCode);
    +        CacheItem prev = null, item = null;
     
    -                CacheItem prev = null, item = null;
    -
    -                synchronized (bucketLocks[index]) {
    -                        for (item = buckets[index]; item != null; item = item.next) {
    -                            if (item == ritem) {
    +        synchronized (bucketLocks[index]) {
    +            for (item = buckets[index]; item != null; item = item.next) {
    +                if (item == ritem) {
                         if (prev == null) {
                             buckets[index] = item.next;
    -                    } else  {
    +                    } else {
                             prev.next = item.next;
                         }
                         item.next = null;
                         break;
    -                            }
    -                            prev = item;
    -                        }
    +                }
    +                prev = item;
    +            }
             }
     
             if (item != null) {
    @@ -667,36 +685,36 @@ protected CacheItem _removeItem(CacheItem ritem) {
          * remove all the item with the given key.
          * @param key lookup key
          */
    -    public void removeAll(Object key) {
    +    @Override
    +    public void removeAll(K key) {
             int hashCode = hash(key);
    -                int index = getIndex(hashCode);
    +        int index = getIndex(hashCode);
     
    -                CacheItem prev = null, item = null;
    -        ArrayList items = new ArrayList(entryCount);
    +        CacheItem prev = null, item = null;
    +        ArrayList> items = new ArrayList<>(entryCount);
     
    -                synchronized (bucketLocks[index]) {
    -                        for (item = buckets[index]; item != null;
    -                                    item = item.next) {
    -                            if (hashCode == item.hashCode && key.equals(item.key)) {
    -                        if (prev == null) {
    -                            buckets[index] = item.next;
    -                        } else  {
    -                            prev.next = item.next;
    -                        }
    -                        item.next = null;
    +        synchronized (bucketLocks[index]) {
    +            for (item = buckets[index]; item != null; item = item.next) {
    +                if (hashCode == item.hashCode && key.equals(item.key)) {
    +                    if (prev == null) {
    +                        buckets[index] = item.next;
    +                    } else {
    +                        prev.next = item.next;
    +                    }
    +                    item.next = null;
     
    -                        decrementEntryCount();
    -                        incrementRemovalCount();
    +                    decrementEntryCount();
    +                    incrementRemovalCount();
     
    -                        items.add(item);
    -                            }
    -                            prev = item;
    -                        }
    +                    items.add(item);
    +                }
    +                prev = item;
    +            }
             }
     
             // notify subclasses
             for (int i = 0; i < items.size(); i++) {
    -            itemRemoved((CacheItem)items.get(i));
    +            itemRemoved(items.get(i));
             }
         }
     
    @@ -704,12 +722,12 @@ public void removeAll(Object key) {
          * trim the item from the cache and notify listeners
          * @param item to be trimmed
          */
    -    protected void trimItem(CacheItem item) {
    -        CacheItem removed = _removeItem(item);
    +    protected void trimItem(CacheItem item) {
    +        CacheItem removed = _removeItem(item);
     
             if (removed != null) {
                 for (int i = 0; i < listeners.size(); i++) {
    -                CacheListener listener = (CacheListener) listeners.get(i);
    +                CacheListener listener = listeners.get(i);
                     listener.trimEvent(removed.key, removed.value);
                 }
             }
    @@ -721,6 +739,7 @@ protected void trimItem(CacheItem item) {
          * @returns true on successful notification, or false if there is
          *  no thread refreshing this entry.
          */
    +    @Override
         public boolean waitRefresh(int index) {
                     synchronized (bucketLocks[index]) {
                 if (refreshFlags[index] == false) {
    @@ -730,8 +749,9 @@ public boolean waitRefresh(int index) {
     
                 // wait till refresh is finished
                 try {
    -                while(refreshFlags[index])
    -                        bucketLocks[index].wait();
    +                while(refreshFlags[index]) {
    +                    bucketLocks[index].wait();
    +                }
                 } catch (InterruptedException ie) {}
             }
             return true;
    @@ -741,9 +761,10 @@ public boolean waitRefresh(int index) {
          * notify threads waiting for a refresh on the object associated with the key
          * @param key lookup key
          */
    +    @Override
         public void notifyRefresh(int index) {
             // notify other threads waiting for refresh
    -                synchronized (bucketLocks[index]) {
    +        synchronized (bucketLocks[index]) {
                 refreshFlags[index] = false;
                 bucketLocks[index].notifyAll();
             }
    @@ -753,32 +774,32 @@ public void notifyRefresh(int index) {
          * clear all the entries from the cache.
          * @returns the number of entries cleared from the cache
          */
    +    @Override
         public int clear() {
    -
    -                CacheItem item=null;
    +        CacheItem item = null;
             int count = 0;
     
             for (int index = 0; index < maxBuckets; index++) {
    -                    synchronized (bucketLocks[index]) {
    -                            for (item = buckets[index]; item != null;
    -                                            item = item.next) {
    +            synchronized (bucketLocks[index]) {
    +                for (item = buckets[index]; item != null; item = item.next) {
                         item.next = null;
     
                         count++;
                         decrementEntryCount();
                         itemRemoved(item);
     
    -                    if (entryCount == 0)
    +                    if (entryCount == 0) {
                             break;
    -                            }
    +                    }
    +                }
                     buckets[index] = null;
                 }
             }
     
    -
             return count;
         }
     
    +
         /**
          * trim the expired entries from the cache.
          * @param maxCount maximum number of invalid entries to trim
    @@ -786,22 +807,23 @@ public int clear() {
          *
          * This call is to be scheduled by a thread managed by the container.
          */
    +    @Override
         public void trimExpiredEntries(int maxCount) {}
     
         /**
          * get the number of entries in the cache
          * @return the number of entries the cache currently holds
          */
    +    @Override
         public int getEntryCount() {
             return entryCount;
         }
     
    -    /*** methods for monitoring the cache          ***/
    -
         /**
          * is this cache empty?
          * @returns true if the cache is empty; false otherwise.
          */
    +    @Override
         public boolean isEmpty() {
             return (entryCount == 0);
         }
    @@ -867,32 +889,35 @@ protected final void incrementOverflowCount() {
          * @return an Object corresponding to the stat
          * See also: Constant.java for the key
          */
    +    @Override
         public Object getStatByName(String key) {
    -        Object stat = null;
    +        Number stat = null;
     
    -        if (key == null)
    +        if (key == null) {
                 return null;
    +        }
     
    -        if (key.equals(Constants.STAT_BASECACHE_MAX_ENTRIES))
    +        if (key.equals(Constants.STAT_BASECACHE_MAX_ENTRIES)) {
                 stat = Integer.valueOf(maxEntries);
    -        else if (key.equals(Constants.STAT_BASECACHE_THRESHOLD))
    +        } else if (key.equals(Constants.STAT_BASECACHE_THRESHOLD)) {
                 stat = Integer.valueOf(threshold);
    -        else if (key.equals(Constants.STAT_BASECACHE_TABLE_SIZE))
    +        } else if (key.equals(Constants.STAT_BASECACHE_TABLE_SIZE)) {
                 stat = Integer.valueOf(maxBuckets);
    -        else if (key.equals(Constants.STAT_BASECACHE_ENTRY_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_ENTRY_COUNT)) {
                 stat = Integer.valueOf(entryCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_HIT_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_HIT_COUNT)) {
                 stat = Integer.valueOf(hitCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_MISS_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_MISS_COUNT)) {
                 stat = Integer.valueOf(missCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_REMOVAL_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_REMOVAL_COUNT)) {
                 stat = Integer.valueOf(removalCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_REFRESH_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_REFRESH_COUNT)) {
                 stat = Integer.valueOf(refreshCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_OVERFLOW_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_OVERFLOW_COUNT)) {
                 stat = Integer.valueOf(overflowCount);
    -        else if (key.equals(Constants.STAT_BASECACHE_ADD_COUNT))
    +        } else if (key.equals(Constants.STAT_BASECACHE_ADD_COUNT)) {
                 stat = Integer.valueOf(addCount);
    +        }
     
             return stat;
         }
    @@ -902,29 +927,20 @@ else if (key.equals(Constants.STAT_BASECACHE_ADD_COUNT))
          * @return a Map of stats
          * See also: Constant.java for the keys
          */
    -    public Map getStats() {
    -        HashMap stats = new HashMap();
    -
    -        stats.put(Constants.STAT_BASECACHE_MAX_ENTRIES,
    -                  Integer.valueOf(maxEntries));
    -        stats.put(Constants.STAT_BASECACHE_THRESHOLD,
    -                  Integer.valueOf(threshold));
    -        stats.put(Constants.STAT_BASECACHE_TABLE_SIZE,
    -                  Integer.valueOf(maxBuckets));
    -        stats.put(Constants.STAT_BASECACHE_ENTRY_COUNT,
    -                  Integer.valueOf(entryCount));
    -        stats.put(Constants.STAT_BASECACHE_HIT_COUNT,
    -                  Integer.valueOf(hitCount));
    -        stats.put(Constants.STAT_BASECACHE_MISS_COUNT,
    -                  Integer.valueOf(missCount));
    -        stats.put(Constants.STAT_BASECACHE_REMOVAL_COUNT,
    -                  Integer.valueOf(removalCount));
    -        stats.put(Constants.STAT_BASECACHE_REFRESH_COUNT,
    -                  Integer.valueOf(refreshCount));
    -        stats.put(Constants.STAT_BASECACHE_OVERFLOW_COUNT,
    -                  Integer.valueOf(overflowCount));
    -        stats.put(Constants.STAT_BASECACHE_ADD_COUNT,
    -                  Integer.valueOf(addCount));
    +    @Override
    +    public Map getStats() {
    +        HashMap stats = new HashMap<>();
    +
    +        stats.put(Constants.STAT_BASECACHE_MAX_ENTRIES, Integer.valueOf(maxEntries));
    +        stats.put(Constants.STAT_BASECACHE_THRESHOLD, Integer.valueOf(threshold));
    +        stats.put(Constants.STAT_BASECACHE_TABLE_SIZE, Integer.valueOf(maxBuckets));
    +        stats.put(Constants.STAT_BASECACHE_ENTRY_COUNT, Integer.valueOf(entryCount));
    +        stats.put(Constants.STAT_BASECACHE_HIT_COUNT, Integer.valueOf(hitCount));
    +        stats.put(Constants.STAT_BASECACHE_MISS_COUNT, Integer.valueOf(missCount));
    +        stats.put(Constants.STAT_BASECACHE_REMOVAL_COUNT, Integer.valueOf(removalCount));
    +        stats.put(Constants.STAT_BASECACHE_REFRESH_COUNT, Integer.valueOf(refreshCount));
    +        stats.put(Constants.STAT_BASECACHE_OVERFLOW_COUNT, Integer.valueOf(overflowCount));
    +        stats.put(Constants.STAT_BASECACHE_ADD_COUNT, Integer.valueOf(addCount));
     
             return stats;
         }
    @@ -933,6 +949,7 @@ public Map getStats() {
          * Sets all references to null. This method should be called
          * at the end of this object's life cycle.
          */
    +    @Override
         public void destroy() {
             if ((listeners != null) && (buckets != null) && (bucketLocks != null)) {
                 clear();
    @@ -955,6 +972,7 @@ public void destroy() {
         /**
          * clear the stats
          */
    +    @Override
         public void clearStats() {
             hitCount = 0;
             missCount = 0;
    @@ -965,15 +983,15 @@ public void clearStats() {
         }
     
         /** default CacheItem class implementation  ***/
    -    public static class CacheItem {
    +    public static class CacheItem {
             int hashCode;
    -        Object key;
    -        Object value;
    +        K key;
    +        V value;
             int size;
     
    -        CacheItem next;
    +        CacheItem next;
     
    -        protected CacheItem(int hashCode, Object key, Object value, int size) {
    +        protected CacheItem(int hashCode, K key, V value, int size) {
                 this.hashCode = hashCode;
                 this.key = key;
                 this.value = value;
    @@ -990,28 +1008,28 @@ public int getHashCode() {
             /**
              * get the item's key
              */
    -        public Object getKey() {
    +        public K getKey() {
                 return key;
             }
     
             /**
              * get the item's next reference
              */
    -        public CacheItem getNext() {
    +        public CacheItem getNext() {
                 return next;
             }
     
             /**
              * set the item's next reference
              */
    -        public void setNext(CacheItem next) {
    +        public void setNext(CacheItem next) {
                 this.next = next;
             }
     
             /**
              * get the item's value
              */
    -        public Object getValue() {
    +        public V getValue() {
                 return value;
             }
     
    @@ -1028,16 +1046,17 @@ public int getSize() {
              * @param value value to be updated
              * @param newSize of the field
              */
    -        protected Object refreshValue(Object value, int newSize) {
    -            Object oldValue = this.value;
    +        protected V refreshValue(V value, int newSize) {
    +            V oldValue = this.value;
                 this.value = value;
                 this.size = newSize;
     
                 return oldValue;
             }
     
    +        @Override
             public String toString() {
    -            return "key: " + key + "; value: " + value.toString();
    +            return "key: " + key + "; value: " + value;
             }
         }
     }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BoundedMultiLruCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BoundedMultiLruCache.java
    index cde64e51087..6f27e5ed93e 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BoundedMultiLruCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/BoundedMultiLruCache.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,7 +29,7 @@
      * Underlying Hashtable is made into logical segments, with each segment
      * having its own LRU list.
      */
    -public class BoundedMultiLruCache extends MultiLruCache {
    +public class BoundedMultiLruCache extends MultiLruCache {
     
         // upper bound on the cache size
         protected long maxSize = Constants.DEFAULT_MAX_CACHE_SIZE;
    @@ -39,6 +40,7 @@ public class BoundedMultiLruCache extends MultiLruCache {
          * initialize the LRU cache
          * @param maxCapacity maximum number of entries this cache may hold
          */
    +    @Override
         public void init(int maxCapacity, Properties props) throws Exception {
             super.init(maxCapacity, props);
             currentSize = 0;
    @@ -70,9 +72,9 @@ public void init(int maxCapacity, Properties props) throws Exception {
                 }
     
                 // sanity check and convert
    -            if (size > 0)
    +            if (size > 0) {
                     maxSize = (size * multiplier);
    -            else  {
    +            } else  {
                     String msg = CULoggerInfo.getString(CULoggerInfo.boundedMultiLruCacheIllegalMaxSize);
     
                     Object[] params = { strMaxSize };
    @@ -90,8 +92,9 @@ public void init(int maxCapacity, Properties props) throws Exception {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected CacheItem itemAdded(CacheItem item) {
    -        LruCacheItem overflow = (LruCacheItem) super.itemAdded(item);
    +    @Override
    +    protected CacheItem itemAdded(CacheItem item) {
    +        LruCacheItem overflow = (LruCacheItem) super.itemAdded(item);
     
             // update the size
             if (overflow != null) {
    @@ -108,7 +111,8 @@ protected CacheItem itemAdded(CacheItem item) {
          * @param oldSize size of the previous value that was refreshed
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRefreshed(CacheItem item, int oldSize) {
    +    @Override
    +    protected void itemRefreshed(CacheItem item, int oldSize) {
             super.itemRefreshed(item, oldSize);
     
             /** reduce the cache by the size of the size of the previous value
    @@ -124,7 +128,8 @@ protected void itemRefreshed(CacheItem item, int oldSize) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRemoved(CacheItem item) {
    +    @Override
    +    protected void itemRemoved(CacheItem item) {
             super.itemRemoved(item);
     
             // update the size
    @@ -135,6 +140,7 @@ protected void itemRemoved(CacheItem item) {
          * has cache reached its threshold
          * @return true when the cache reached its threshold
          */
    +    @Override
         protected boolean isThresholdReached() {
             return (currentSize > maxSize || super.isThresholdReached());
         }
    @@ -164,37 +170,26 @@ protected final void decrementCurrentSize(int size) {
          * @return an Object corresponding to the stat
          * See also: Constant.java for the key
          */
    +    @Override
         public Object getStatByName(String key) {
             Object stat = super.getStatByName(key);
    -
             if (stat == null && key != null) {
    -            if (key.equals(Constants.STAT_BOUNDEDMULTILRUCACHE_CURRENT_SIZE))
    +            if (key.equals(Constants.STAT_BOUNDEDMULTILRUCACHE_CURRENT_SIZE)) {
                     stat = Long.valueOf(currentSize);
    -            else if (key.equals(Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE)) {
    -                if (maxSize == Constants.DEFAULT_MAX_CACHE_SIZE)
    -                    stat = Constants.STAT_DEFAULT;
    -                else
    -                    stat = Long.valueOf(maxSize);
    +            } else if (key.equals(Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE)) {
    +                stat = Long.valueOf(maxSize);
                 }
             }
     
             return stat;
         }
     
    -    public Map getStats() {
    -        Map stats = super.getStats();
    -
    +    @Override
    +    public Map getStats() {
    +        Map stats = super.getStats();
             // cache size in KB
    -        stats.put(Constants.STAT_BOUNDEDMULTILRUCACHE_CURRENT_SIZE,
    -                  Long.valueOf(currentSize));
    -        if (maxSize == Constants.DEFAULT_MAX_CACHE_SIZE) {
    -            stats.put(Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE,
    -                      Constants.STAT_DEFAULT);
    -        }
    -        else {
    -            stats.put(Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE,
    -                      Long.valueOf(maxSize));
    -        }
    +        stats.put(Constants.STAT_BOUNDEDMULTILRUCACHE_CURRENT_SIZE, currentSize);
    +        stats.put(Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE, maxSize);
             return stats;
         }
     }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/Cache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/Cache.java
    index 1bac7ed78c9..0c1b13f6c01 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/Cache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/Cache.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
    @@ -25,7 +26,7 @@
      * Cache
      * Generic cache interface
      */
    -public interface Cache {
    +public interface Cache {
     
         /**
          * initialize the cache
    @@ -56,7 +57,7 @@ public void init(int maxEntries,
          * @param key of the entry
          * @return the index to be used in the cache
          */
    -    public int getIndex(Object key);
    +    public int getIndex(K key);
     
         /**
          * get the item stored at the key.
    @@ -65,40 +66,40 @@ public void init(int maxEntries,
          *
          * This function returns first value, for a multi-valued key.
          */
    -    public Object get(Object key);
    +    public V get(K key);
     
         /**
          * get all the items with the given key.
          * @param key lookup key
          * @returns an Iterator over the items with the given key
          */
    -    public Iterator getAll(Object key);
    +    public Iterator getAll(K key);
     
         /**
          * check if the cache contains the item at the key
          * @param key lookup key
          * @returns true if there is an item stored at the key; false if not.
          */
    -    public boolean contains(Object key);
    +    public boolean contains(K key);
     
         /**
          * get an Iterator for the keys stored in the cache
          * @returns an Iterator
          */
    -    public Iterator keys();
    +    public Iterator keys();
     
         /**
          * get an Enumeration for the keys stored in the cache
          * @returns an Enumeration
          * XXX: should use Iterator which is based on Collections
          */
    -    public Enumeration elements();
    +    public Enumeration elements();
     
         /**
          * get an Iterator for the values stored in the cache
          * @returns an Iterator
          */
    -    public Iterator values();
    +    public Iterator values();
     
         /**
          * cache the given value at the specified key and return previous value
    @@ -108,7 +109,7 @@ public void init(int maxEntries,
          *
          * This function replaces first value, for a multi-valued key.
          */
    -    public Object put(Object key, Object value);
    +    public V put(K key, V value);
     
         /**
          * cache the given value at the specified key and return previous value
    @@ -119,7 +120,7 @@ public void init(int maxEntries,
          *
          * This function replaces first value, for a multi-valued key.
          */
    -    public Object put(Object key, Object value, int size);
    +    public V put(K key, V value, int size);
     
         /**
          * add the given value to the cache at the specified key
    @@ -128,7 +129,7 @@ public void init(int maxEntries,
          *
          * This function is suitable for multi-valued keys.
          */
    -    public void add(Object key, Object value);
    +    public void add(K key, V value);
     
         /**
          * add the given value with specified size to the cache at specified key
    @@ -138,7 +139,7 @@ public void init(int maxEntries,
          *
          * This function is suitable for multi-valued keys.
          */
    -    public void add(Object key, Object value, int size);
    +    public void add(K key, V value, int size);
     
         /**
          * remove the item with the given key.
    @@ -147,7 +148,7 @@ public void init(int maxEntries,
          *
          * This function removes first value, for a multi-valued key.
          */
    -    public Object remove(Object key);
    +    public V remove(K key);
     
         /**
          * remove the given value stored at the key.
    @@ -155,13 +156,13 @@ public void init(int maxEntries,
          * @param value to match (for multi-valued keys)
          * @returns the item stored at the key; null if not found.
          */
    -    public Object remove(Object key, Object value);
    +    public V remove(K key, V value);
     
         /**
          * remove all the item with the given key.
          * @param key lookup key
          */
    -    public void removeAll(Object key);
    +    public void removeAll(K key);
     
         /**
          * wait for a refresh on the object associated with the key
    @@ -213,7 +214,7 @@ public void init(int maxEntries,
          * @return a Map of stats
          * See also: Constant.java for the keys
          */
    -    public Map getStats();
    +    public Map getStats();
     
         /**
          * clear all stats
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/LruCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/LruCache.java
    index c65ed7469cb..50970400e5b 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/LruCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/LruCache.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
    @@ -24,14 +25,14 @@
      * LRUCache
      * in-memory bounded cache with an LRU list
      */
    -public class LruCache extends BaseCache {
    +public class LruCache extends BaseCache {
     
         // the item never expires
         public static final long NO_TIMEOUT = -1;
     
         // LRU list
    -    protected LruCacheItem head;
    -    protected LruCacheItem tail;
    +    protected LruCacheItem head;
    +    protected LruCacheItem tail;
     
         // the number of times the cache was trimmed
         protected int trimCount;
    @@ -84,8 +85,9 @@ public void init(int maxEntries, long timeout, float loadFactor, Properties prop
          */
         public void setTimeout(long timeout) {
             // accept a positive timeout
    -        if (timeout > 0)
    +        if (timeout > 0) {
                 this.timeout = timeout;
    +        }
         }
     
         /**
    @@ -98,9 +100,9 @@ public void setTimeout(long timeout) {
          * subclasses may override to provide their own CacheItem extensions
          * e.g. one that permits persistence.
          */
    -    protected CacheItem createItem(int hashCode, Object key,
    -                                        Object value, int size) {
    -        return new LruCacheItem(hashCode, key, value, size);
    +    @Override
    +    protected CacheItem createItem(int hashCode, K key, V value, int size) {
    +        return new LruCacheItem<>(hashCode, key, value, size);
         }
     
         /**
    @@ -110,12 +112,13 @@ protected CacheItem createItem(int hashCode, Object key,
          *
          * list synchronization is handled by the caller
          */
    -    protected CacheItem trimLru(long currentTime) {
    +    protected CacheItem trimLru(long currentTime) {
     
    -        if(tail == null)
    +        if(tail == null) {
                 return null;
    +        }
     
    -        LruCacheItem trimItem = tail;
    +        LruCacheItem trimItem = tail;
     
             if (tail != head) {
                 tail = trimItem.lPrev;
    @@ -149,12 +152,14 @@ protected CacheItem trimLru(long currentTime) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected CacheItem itemAdded(CacheItem item) {
    +    @Override
    +    protected CacheItem itemAdded(CacheItem item) {
             boolean updateThreshold = false;
    -        CacheItem overflow = null;
    -        if(! (item instanceof LruCacheItem))
    +        CacheItem overflow = null;
    +        if(! (item instanceof LruCacheItem)) {
                 return null;
    -        LruCacheItem lc = (LruCacheItem) item;
    +        }
    +        LruCacheItem lc = (LruCacheItem) item;
     
             // set the timestamp
             lc.lastAccessed = System.currentTimeMillis();
    @@ -175,16 +180,18 @@ protected CacheItem itemAdded(CacheItem item) {
                 listSize++;
     
                 if (isThresholdReached()) {
    -                if (!isUnbounded)
    +                if (!isUnbounded) {
                         overflow = trimLru(lc.lastAccessed);
    -                else
    +                } else {
                         updateThreshold = true;
    +                }
                 }
             }
     
             // update the base cache threshold if needed
    -        if (updateThreshold)
    +        if (updateThreshold) {
                 super.handleOverflow();
    +        }
     
             return overflow;
         }
    @@ -195,26 +202,31 @@ protected CacheItem itemAdded(CacheItem item) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemAccessed(CacheItem item) {
    -        if(head == null)
    +    @Override
    +    protected void itemAccessed(CacheItem item) {
    +        if(head == null) {
                 return;
    -        if(item == null)
    +        }
    +        if(item == null) {
                 return;
    -        if(! (item instanceof LruCacheItem))
    +        }
    +        if(! (item instanceof LruCacheItem)) {
                 return;
    -        LruCacheItem lc = (LruCacheItem) item;
    +        }
    +        LruCacheItem lc = (LruCacheItem) item;
     
             synchronized (this) {
     
                 // if the item is already trimmed from the LRU list, nothing to do.
    -            if (lc.isTrimmed)
    +            if (lc.isTrimmed) {
                     return;
    +            }
     
                 // update the timestamp
                 lc.lastAccessed = System.currentTimeMillis();
     
    -            LruCacheItem prev = lc.lPrev;
    -            LruCacheItem next = lc.lNext;
    +            LruCacheItem prev = lc.lPrev;
    +            LruCacheItem next = lc.lNext;
                 // update the LRU list
                 if (prev != null) {
                     // put the item at the head of LRU list
    @@ -225,10 +237,11 @@ protected void itemAccessed(CacheItem item) {
     
                     // patch up the previous neighbors
                     prev.lNext = next;
    -                if (next != null)
    +                if (next != null) {
                         next.lPrev = prev;
    -                else
    +                } else {
                         tail = prev;
    +                }
                }
             }
         }
    @@ -239,7 +252,8 @@ protected void itemAccessed(CacheItem item) {
          * @param oldSize size of the previous value that was refreshed
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRefreshed(CacheItem item, int oldSize) {
    +    @Override
    +    protected void itemRefreshed(CacheItem item, int oldSize) {
             itemAccessed(item);
         }
     
    @@ -249,30 +263,35 @@ protected void itemRefreshed(CacheItem item, int oldSize) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRemoved(CacheItem item) {
    -        if(! (item instanceof LruCacheItem))
    +    @Override
    +    protected void itemRemoved(CacheItem item) {
    +        if(! (item instanceof LruCacheItem)) {
                 return;
    -        LruCacheItem l = (LruCacheItem) item;
    +        }
    +        LruCacheItem l = (LruCacheItem) item;
     
             // remove the item from the LRU list
             synchronized (this) {
    -            LruCacheItem prev = l.lPrev;
    -            LruCacheItem next = l.lNext;
    +            LruCacheItem prev = l.lPrev;
    +            LruCacheItem next = l.lNext;
     
                 // if the item is already trimmed from the LRU list, nothing to do.
    -            if (l.isTrimmed)
    +            if (l.isTrimmed) {
                     return;
    +            }
     
                 // patch up the neighbors and make sure head/tail are correct
    -            if (prev != null)
    +            if (prev != null) {
                     prev.lNext = next;
    -            else
    +            } else {
                     head = next;
    +            }
     
    -            if (next != null)
    +            if (next != null) {
                     next.lPrev = prev;
    -            else
    +            } else {
                     tail = prev;
    +            }
     
                 l.lPrev = l.lNext = null;
                 listSize--;
    @@ -288,12 +307,13 @@ protected void itemRemoved(CacheItem item) {
          * NOTE: this algorithm assumes that all the entries in the cache have
          * identical timeout (otherwise traversing from tail won't be right).
          */
    +    @Override
         public void trimExpiredEntries(int maxCount) {
     
             int count = 0;
    -        LruCacheItem item;
    +        LruCacheItem item;
             long currentTime = System.currentTimeMillis();
    -        ArrayList list = new ArrayList();
    +        ArrayList> list = new ArrayList<>();
     
             synchronized (this) {
                 // traverse LRU list till we reach a valid item; remove them at once
    @@ -313,10 +333,11 @@ public void trimExpiredEntries(int maxCount) {
     
                 // if there was at least one invalid item then item != tail.
                 if (item != tail) {
    -                if (item != null)
    +                if (item != null) {
                         item.lNext = null;
    -                else
    +                } else {
                         head = null;
    +                }
     
                     tail = item;
                 }
    @@ -326,7 +347,7 @@ public void trimExpiredEntries(int maxCount) {
     
             // trim the items from the BaseCache from the old tail backwards
             for (int index=list.size()-1; index >= 0; index--) {
    -            trimItem((LruCacheItem) list.get(index));
    +            trimItem(list.get(index));
             }
         }
     
    @@ -341,66 +362,66 @@ public void trimExpiredEntries(int maxCount) {
          * @return an Object corresponding to the stat
          * See also: Constant.java for the key
          */
    +    @Override
         public Object getStatByName(String key) {
             Object stat = super.getStatByName(key);
     
             if (stat == null && key != null) {
    -            if (key.equals(Constants.STAT_LRUCACHE_LIST_LENGTH))
    +            if (key.equals(Constants.STAT_LRUCACHE_LIST_LENGTH)) {
                     stat = Integer.valueOf(listSize);
    -            else if (key.equals(Constants.STAT_LRUCACHE_TRIM_COUNT))
    +            } else if (key.equals(Constants.STAT_LRUCACHE_TRIM_COUNT)) {
                     stat = Integer.valueOf(trimCount);
    +            }
             }
             return stat;
         }
     
    -    public Map getStats() {
    -        Map stats = super.getStats();
    -        stats.put(Constants.STAT_LRUCACHE_LIST_LENGTH,
    -                  Integer.valueOf(listSize));
    -        stats.put(Constants.STAT_LRUCACHE_TRIM_COUNT,
    -                  Integer.valueOf(trimCount));
    -
    +    @Override
    +    public Map getStats() {
    +        Map stats = super.getStats();
    +        stats.put(Constants.STAT_LRUCACHE_LIST_LENGTH, Integer.valueOf(listSize));
    +        stats.put(Constants.STAT_LRUCACHE_TRIM_COUNT, Integer.valueOf(trimCount));
             return stats;
         }
     
         /** default CacheItem class implementation  ***/
    -    protected static class LruCacheItem extends CacheItem {
    +    protected static class LruCacheItem extends CacheItem {
     
             // double linked LRU list
    -        protected LruCacheItem lNext;
    -        protected LruCacheItem lPrev;
    +        protected LruCacheItem lNext;
    +        protected LruCacheItem lPrev;
             protected boolean isTrimmed;
             protected long lastAccessed;
     
    -        protected LruCacheItem(int hashCode, Object key, Object value, int size) {
    +        protected LruCacheItem(int hashCode, K key, V value, int size) {
                 super(hashCode, key, value, size);
             }
     
             /**
              * Return the next item
              */
    -         public LruCacheItem getLNext() {
    +         public LruCacheItem getLNext() {
                  return lNext;
              }
     
             /**
              * Reset the next item reference
              */
    -         public void setLNext(LruCacheItem item) {
    +         public void setLNext(LruCacheItem item) {
                  lNext = item;
              }
     
             /**
              * Return the previous item
              */
    -         public LruCacheItem getLPrev() {
    +         public LruCacheItem getLPrev() {
                  return lPrev;
              }
     
             /**
              * Reset the previous item reference
              */
    -         public void setLPrev(LruCacheItem item) {
    +         public void setLPrev(LruCacheItem item) {
                  lPrev = item;
              }
     
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/MultiLruCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/MultiLruCache.java
    index 4895b62bf72..edd6377d6e2 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/MultiLruCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/MultiLruCache.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
    @@ -24,7 +25,7 @@
      * Underlying Hashtable is made into logical segments, with each segment
      * having its own LRU list.
      */
    -public class MultiLruCache extends BaseCache {
    +public class MultiLruCache extends BaseCache {
     
         /* an array of LRU lists; each element in this array is actually
          * LruCacheItem[2] with LRU list (lru[0] is head and lru[1] the tail
    @@ -34,7 +35,7 @@ public class MultiLruCache extends BaseCache {
         public static final int DEFAULT_HASHTABLE_SEGMENT_SIZE = 4096;
     
         int segmentSize;
    -    LruCacheItem[][] lists;
    +    LruCacheItem[][] lists;
         protected int[] listsLength;
     
         int trimCount;
    @@ -45,6 +46,7 @@ public class MultiLruCache extends BaseCache {
          * initialize the LRU cache
          * @param maxCapacity maximum number of entries this cache may hold
          */
    +    @Override
         public void init(int maxCapacity, Properties props) throws Exception {
             super.init(maxCapacity, props);
     
    @@ -60,9 +62,8 @@ public void init(int maxCapacity, Properties props) throws Exception {
             }
     
             // create the array of LRU lists
    -        int segments = ((maxBuckets / segmentSize) +
    -                        (((maxBuckets % segmentSize) != 0) ? 1 : 0));
    -               lists = new LruCacheItem[segments][2];
    +        int segments = ((maxBuckets / segmentSize) + (((maxBuckets % segmentSize) != 0) ? 1 : 0));
    +        lists = new LruCacheItem[segments][2];
             listsLength = new int[lists.length];
             for (int i = 0; i < lists.length; i++) {
                 lists[i][LRU_HEAD] = null;
    @@ -82,9 +83,9 @@ public void init(int maxCapacity, Properties props) throws Exception {
          * subclasses may override to provide their own CacheItem extensions
          * e.g. one that permits persistence.
          */
    -    protected CacheItem createItem(int hashCode, Object key,
    -                                        Object value, int size) {
    -        return new LruCacheItem(hashCode, key, value, size);
    +    @Override
    +    protected CacheItem createItem(int hashCode, K key, V value, int size) {
    +        return new LruCacheItem<>(hashCode, key, value, size);
         }
     
         /**
    @@ -92,9 +93,9 @@ protected CacheItem createItem(int hashCode, Object key,
          * @param the LRU segment index to trim
          * @return the item that was successfully trimmed
          */
    -    protected CacheItem trimLru(int segment) {
    -        LruCacheItem[] list = lists[segment];
    -        LruCacheItem l = null;
    +    protected CacheItem trimLru(int segment) {
    +        LruCacheItem[] list = lists[segment];
    +        LruCacheItem l = null;
     
             l = list[LRU_TAIL];
     
    @@ -118,25 +119,27 @@ protected CacheItem trimLru(int segment) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected CacheItem itemAdded(CacheItem item) {
    -        CacheItem overflow = null;
    -        if(! (item instanceof LruCacheItem))
    +    @Override
    +    protected CacheItem itemAdded(CacheItem item) {
    +        CacheItem overflow = null;
    +        if(! (item instanceof LruCacheItem)) {
                 return null;
    +        }
     
    -        LruCacheItem lc = (LruCacheItem) item;
    +        LruCacheItem lc = (LruCacheItem) item;
     
             int index = getIndex(item.hashCode());
             int segment = (index/segmentSize);
    -        LruCacheItem[] list = lists[segment];
    +        LruCacheItem[] list = lists[segment];
     
             // update the LRU
             synchronized (list) {
                 if (list[LRU_HEAD] != null) {
                     list[LRU_HEAD].lPrev = lc;
                     lc.lNext = list[LRU_HEAD];
    -            }
    -            else
    +            } else {
                     list[LRU_TAIL] = lc;
    +            }
                 list[LRU_HEAD] = lc;
     
                 listsLength[segment]++;
    @@ -157,19 +160,21 @@ protected CacheItem itemAdded(CacheItem item) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemAccessed(CacheItem item) {
    +    @Override
    +    protected void itemAccessed(CacheItem item) {
             int index = getIndex(item.hashCode());
             int segment = (index/segmentSize);
    -        LruCacheItem[] list = lists[segment];
    +        LruCacheItem[] list = lists[segment];
     
    -        if(! (item instanceof LruCacheItem))
    +        if(! (item instanceof LruCacheItem)) {
                 return;
    -        LruCacheItem lc = (LruCacheItem) item;
    +        }
    +        LruCacheItem lc = (LruCacheItem) item;
     
             // update the LRU list
             synchronized (list) {
    -            LruCacheItem prev = lc.lPrev;
    -            LruCacheItem next = lc.lNext;
    +            LruCacheItem prev = lc.lPrev;
    +            LruCacheItem next = lc.lNext;
     
                 if (prev != null) {
                     // put the item at the head of LRU list
    @@ -180,10 +185,11 @@ protected void itemAccessed(CacheItem item) {
     
                     // patch up the previous neighbors
                     prev.lNext = next;
    -                if (next != null)
    +                if (next != null) {
                         next.lPrev = prev;
    -                else
    +                } else {
                         list[LRU_TAIL] = prev;
    +                }
     
                }
             }
    @@ -195,7 +201,8 @@ protected void itemAccessed(CacheItem item) {
          * @param oldSize size of the previous value that was refreshed
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRefreshed(CacheItem item, int oldSize) {
    +    @Override
    +    protected void itemRefreshed(CacheItem item, int oldSize) {
             itemAccessed(item);
         }
     
    @@ -205,34 +212,39 @@ protected void itemRefreshed(CacheItem item, int oldSize) {
          *
          * Cache bucket is already synchronized by the caller
          */
    -    protected void itemRemoved(CacheItem item) {
    -        if(! (item instanceof LruCacheItem))
    +    @Override
    +    protected void itemRemoved(CacheItem item) {
    +        if(! (item instanceof LruCacheItem)) {
                 return;
    -        LruCacheItem l = (LruCacheItem) item;
    +        }
    +        LruCacheItem l = (LruCacheItem) item;
     
             int index = getIndex(item.hashCode());
             int segment = (index/segmentSize);
    -        LruCacheItem[] list = lists[segment];
    +        LruCacheItem[] list = lists[segment];
     
             // remove the item from the LRU list
             synchronized (list) {
                 // if the item is already trimmed from the LRU list, nothing to do.
    -            if (l.isTrimmed)
    +            if (l.isTrimmed) {
                     return;
    +            }
     
    -            LruCacheItem prev = l.lPrev;
    -            LruCacheItem next = l.lNext;
    +            LruCacheItem prev = l.lPrev;
    +            LruCacheItem next = l.lNext;
     
                 // patch up the neighbors and make sure head/tail are correct
    -            if (prev != null)
    +            if (prev != null) {
                     prev.lNext = next;
    -            else
    +            } else {
                     list[LRU_HEAD] = next;
    +            }
     
    -            if (next != null)
    +            if (next != null) {
                     next.lPrev = prev;
    -            else
    +            } else {
                     list[LRU_TAIL] = prev;
    +            }
     
                 listsLength[segment]--;
             }
    @@ -242,6 +254,7 @@ protected void itemRemoved(CacheItem item) {
          * cache has reached threshold so trim its size. subclasses are expected
          * to provide a robust cache replacement algorithm.
          */
    +    @Override
         protected void handleOverflow() {
         }
     
    @@ -265,19 +278,20 @@ protected void incrementTrimIndex() {
          * @return an Object corresponding to the stat
          * See also: Constant.java for the key
          */
    +    @Override
         public Object getStatByName(String key) {
             Object stat = super.getStatByName(key);
     
             if (stat == null && key != null) {
    -            if (key.equals(Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE))
    +            if (key.equals(Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE)) {
                     stat = Integer.valueOf(segmentSize);
    -            else if (key.equals(Constants.STAT_MULTILRUCACHE_TRIM_COUNT))
    +            } else if (key.equals(Constants.STAT_MULTILRUCACHE_TRIM_COUNT)) {
                     stat = Integer.valueOf(trimCount);
    -            else if (key.equals(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH)) {
    +            } else if (key.equals(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH)) {
                     stat = new Integer[lists.length];
     
                     for (int i = 0; i < lists.length; i++) {
    -                    ((Integer[])stat)[i] = Integer.valueOf(listsLength[i]);
    +                    ((Integer[]) stat)[i] = Integer.valueOf(listsLength[i]);
                     }
                 }
             }
    @@ -290,30 +304,26 @@ else if (key.equals(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH)) {
          * @return a Map of stats
          * See also: Constant.java for the keys
          */
    -    public Map getStats() {
    -        Map stats = super.getStats();
    -
    -        stats.put(Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE,
    -                  Integer.valueOf(segmentSize));
    +    @Override
    +    public Map getStats() {
    +        Map stats = super.getStats();
    +        stats.put(Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE, Integer.valueOf(segmentSize));
             for (int i = 0; i < lists.length; i++) {
    -            stats.put(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH + "["
    -                      + i + "]:",
    -                      Integer.valueOf(listsLength[i]));
    +            stats.put(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH + "[" + i + "]:", Integer.valueOf(listsLength[i]));
             }
    -        stats.put(Constants.STAT_MULTILRUCACHE_TRIM_COUNT,
    -                  Integer.valueOf(trimCount));
    +        stats.put(Constants.STAT_MULTILRUCACHE_TRIM_COUNT, Integer.valueOf(trimCount));
             return stats;
         }
     
         /** default CacheItem class implementation  ***/
    -    static class LruCacheItem extends BaseCache.CacheItem {
    +    static class LruCacheItem extends BaseCache.CacheItem {
     
             // double linked LRU list
    -            LruCacheItem lNext;
    -            LruCacheItem lPrev;
    +        LruCacheItem lNext;
    +        LruCacheItem lPrev;
             boolean isTrimmed;
     
    -        LruCacheItem(int hashCode, Object key, Object value, int size) {
    +        LruCacheItem(int hashCode, K key, V value, int size) {
                 super(hashCode, key, value, size);
             }
         }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBaseCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBaseCache.java
    index 3c31ed66c6a..5ac654fc267 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBaseCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBaseCache.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,11 +15,6 @@
      * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
      */
     
    -/**
    - * @Version $Id: JmxBaseCache.java,v 1.4 2005/12/25 04:25:22 tcfujii Exp $
    - * Created on May 4, 2005 11:55 AM
    - */
    -
     package com.sun.appserv.util.cache.mbeans;
     
     import com.sun.appserv.util.cache.BaseCache;
    @@ -27,103 +23,115 @@
     /**
      * This class provides implementation for JmxBaseCacheMBean
      *
    - * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com)
    - *
    + * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com) 2005
      */
     public class JmxBaseCache implements JmxBaseCacheMBean {
     
         private String name;
    -    private BaseCache baseCache;
    +    private BaseCache baseCache;
     
    -    public JmxBaseCache(BaseCache baseCache, String name) {
    +    public JmxBaseCache(BaseCache baseCache, String name) {
             this.baseCache = baseCache;
             this.name = name;
         }
    +
    +
         /**
          * Returns a unique identifier for this MBean inside the domain
          */
    +    @Override
         public String getName() {
             return name;
         }
     
    +
         /**
          * Returns maximum possible number of entries
          */
    +    @Override
         public Integer getMaxEntries() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_MAX_ENTRIES);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_MAX_ENTRIES);
         }
     
    +
         /**
          * Returns threshold. This when reached, an overflow will occur
          */
    +    @Override
         public Integer getThreshold() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_THRESHOLD);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_THRESHOLD);
         }
     
    +
         /**
          * Returns current number of buckets
          */
    +    @Override
         public Integer getTableSize() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_TABLE_SIZE);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_TABLE_SIZE);
         }
     
    +
         /**
          * Returns current number of Entries
          */
    +    @Override
         public Integer getEntryCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_ENTRY_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_ENTRY_COUNT);
         }
     
    +
         /**
          * Return the number of cache hits
          */
    +    @Override
         public Integer getHitCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_HIT_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_HIT_COUNT);
         }
     
    +
         /**
          * Returns the number of cache misses
          */
    +    @Override
         public Integer getMissCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_MISS_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_MISS_COUNT);
         }
     
    +
         /**
          * Returns the number of entries that have been removed
          */
    +    @Override
         public Integer getRemovalCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_REMOVAL_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_REMOVAL_COUNT);
         }
     
    +
         /**
          * Returns the number of values that have been refreshed
          * (replaced with a new value in an existing extry)
          */
    +    @Override
         public Integer getRefreshCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_REFRESH_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_REFRESH_COUNT);
         }
     
    +
         /**
          * Returns the number of times that an overflow has occurred
          */
    +    @Override
         public Integer getOverflowCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_OVERFLOW_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_OVERFLOW_COUNT);
         }
     
    +
         /**
          * Returns the number of times new entries have been added
          */
    +    @Override
         public Integer getAddCount() {
    -        return (Integer) baseCache.getStatByName(
    -                                        Constants.STAT_BASECACHE_ADD_COUNT);
    +        return (Integer) baseCache.getStatByName(Constants.STAT_BASECACHE_ADD_COUNT);
         }
     }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBoundedMultiLruCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBoundedMultiLruCache.java
    index a757643a2d0..0cb30e7ce53 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBoundedMultiLruCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxBoundedMultiLruCache.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,28 +15,21 @@
      * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
      */
     
    -/**
    - * @Version $Id: JmxBoundedMultiLruCache.java,v 1.5 2006/10/23 20:55:57 jluehe Exp $
    - * Created on May 4, 2005 07:40 PM
    - */
    -
     package com.sun.appserv.util.cache.mbeans;
     
     import com.sun.appserv.util.cache.BoundedMultiLruCache;
     import com.sun.appserv.util.cache.Constants;
    +
     /**
      * This class provides implementation for JmxLruCache MBean
      *
    - * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com)
    - *
    + * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com) 2005
      */
    -public class JmxBoundedMultiLruCache extends JmxMultiLruCache
    -                              implements JmxBoundedMultiLruCacheMBean {
    +public class JmxBoundedMultiLruCache extends JmxMultiLruCache implements JmxBoundedMultiLruCacheMBean {
     
    -    private BoundedMultiLruCache boundedMultiLruCache;
    +    private BoundedMultiLruCache boundedMultiLruCache;
     
    -    public JmxBoundedMultiLruCache(BoundedMultiLruCache boundedMultiLruCache,
    -                                   String name) {
    +    public JmxBoundedMultiLruCache(BoundedMultiLruCache boundedMultiLruCache, String name) {
             super(boundedMultiLruCache, name);
             this.boundedMultiLruCache = boundedMultiLruCache;
         }
    @@ -43,6 +37,7 @@ public JmxBoundedMultiLruCache(BoundedMultiLruCache boundedMultiLruCache,
         /**
          * Returns the current size of the cache in bytes
          */
    +    @Override
         public Long getCurrentSize() {
             return (Long) boundedMultiLruCache.getStatByName(
                                             Constants.STAT_BOUNDEDMULTILRUCACHE_CURRENT_SIZE);
    @@ -51,6 +46,7 @@ public Long getCurrentSize() {
         /**
          * Returns the upper bound on the cache size
          */
    +    @Override
         public Long getMaxSize() {
             Object object = boundedMultiLruCache.getStatByName(
                                             Constants.STAT_BOUNDEDMULTILRUCACHE_MAX_SIZE);
    @@ -59,11 +55,9 @@ public Long getMaxSize() {
              * "default" if the maxSize == Constants.DEFAULT_MAX_CACHE_SIZE
              * To take care of this case, the if/else is added below
              */
    -        if (object instanceof String &&
    -            ((String) object).equals(Constants.STAT_DEFAULT)) {
    +        if (object instanceof String && ((String) object).equals(Constants.STAT_DEFAULT)) {
                 return Long.valueOf(Constants.DEFAULT_MAX_CACHE_SIZE);
    -        }
    -        else {
    +        } else {
                 return (Long) object;
             }
         }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxMultiLruCache.java b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxMultiLruCache.java
    index aa32c6d8599..961101d7820 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxMultiLruCache.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/appserv/util/cache/mbeans/JmxMultiLruCache.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,52 +15,49 @@
      * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
      */
     
    -/**
    - * @Version $Id: JmxMultiLruCache.java,v 1.4 2005/12/25 04:25:23 tcfujii Exp $
    - * Created on May 4, 2005 02:30 PM
    - */
    -
     package com.sun.appserv.util.cache.mbeans;
     
     import com.sun.appserv.util.cache.Constants;
     import com.sun.appserv.util.cache.MultiLruCache;
    +
     /**
      * This class provides implementation for JmxLruCache MBean
      *
    - * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com)
    - *
    + * @author Krishnamohan Meduri (Krishna.Meduri@Sun.com) 2005
      */
    -public class JmxMultiLruCache extends JmxBaseCache
    -                              implements JmxMultiLruCacheMBean {
    +public class JmxMultiLruCache extends JmxBaseCache implements JmxMultiLruCacheMBean {
     
         private MultiLruCache multiLruCache;
     
         public JmxMultiLruCache(MultiLruCache multiLruCache, String name) {
    -        super(multiLruCache,name);
    +        super(multiLruCache, name);
             this.multiLruCache = multiLruCache;
         }
     
    +
         /**
          * Returns the number of entries that have been trimmed
          */
    +    @Override
         public Integer getTrimCount() {
    -        return (Integer) multiLruCache.getStatByName(
    -                                        Constants.STAT_MULTILRUCACHE_TRIM_COUNT);
    +        return (Integer) multiLruCache.getStatByName(Constants.STAT_MULTILRUCACHE_TRIM_COUNT);
         }
     
    +
         /**
          * Returns the size of each segment
          */
    +    @Override
         public Integer getSegmentSize() {
    -        return (Integer) multiLruCache.getStatByName(
    -                                        Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE);
    +        return (Integer) multiLruCache.getStatByName(Constants.STAT_MULTILRUCACHE_SEGMENT_SIZE);
         }
     
    +
         /**
          * Returns the legnth of the segment list
          */
    +    @Override
         public Integer[] getSegmentListLength() {
    -        return (Integer[]) multiLruCache.getStatByName(
    -                                        Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH);
    +        return (Integer[]) multiLruCache.getStatByName(Constants.STAT_MULTILRUCACHE_SEGMENT_LIST_LENGTH);
         }
     }
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/collections/CollectionUtils.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/collections/CollectionUtils.java
    index 3789ec1b896..b20225a571a 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/collections/CollectionUtils.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/collections/CollectionUtils.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2021, 2022 Contributors to Eclipse Foundation.
    + * Copyright (c) 2021, 2026 Contributors to Eclipse Foundation.
      * Copyright (c) 2008, 2018 Oracle and/or its affiliates. All rights reserved.
      *
      * This program and the accompanying materials are made available under the
    @@ -38,7 +38,8 @@ private CollectionUtils() {
     
     
         /**
    -     * Convert a Properties object, which is a Map<Object,Object> into a 
    +     * Convert a Properties object, which is a {@code Map} into
    +     * a {@code Map}
          *
          * @param p The Properties object to convert
          * @return The converted Map
    @@ -46,13 +47,11 @@ private CollectionUtils() {
         public static Map propertiesToStringMap(Properties p) {
             Map map = new HashMap<>();
             Set> entries = p.entrySet();
    -
             for (Map.Entry entry : entries) {
                 Object name = entry.getKey();
                 Object value = entry.getValue();
    -
                 if (name == null) {
    -                continue; // impossible. Ignore if I was wrong...
    +                continue;
                 }
                 if (value == null) {
                     map.put(name.toString(), null);
    @@ -60,7 +59,6 @@ public static Map propertiesToStringMap(Properties p) {
                     map.put(name.toString(), value.toString());
                 }
             }
    -
             return map;
         }
     
    diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/ASenvPropertyReader.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/ASenvPropertyReader.java
    index 5116bcdc408..8d7770fd7cb 100644
    --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/ASenvPropertyReader.java
    +++ b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/ASenvPropertyReader.java
    @@ -1,5 +1,5 @@
     /*
    - * Copyright (c) 2024, 2025 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
    @@ -75,7 +75,7 @@ public class ASenvPropertyReader {
          * There are no arguments because the installation directory is calculated
          * relative to the jar file you are calling from.
          * Unlike V2 this class will not set any System Properties.  Instead it will
    -     * give you a Map containing the properties.
    +     * give you a {@code {@code Map}} containing the properties.
          * 

    To use the class, create an instance and then call getProps(). */ public ASenvPropertyReader() { @@ -101,14 +101,14 @@ public ASenvPropertyReader(File installDir) { /** * Returns the properties that were processed from asenv.[bat|conf]. - * @return A Map with all the system properties like properties. + * @return A {@code {@code Map}} with all the system properties like properties. */ public Map getProps() { return props; } /** - * Returns a string representation of the properties in the Map. + * Returns a string representation of the properties in the {@code {@code Map}}. * Format: name=value\nname2=value2\n etc. * @return the string representation. */ diff --git a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/TokenResolver.java b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/TokenResolver.java index cfa9732e786..552b6081262 100644 --- a/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/TokenResolver.java +++ b/nucleus/common/common-util/src/main/java/com/sun/enterprise/universal/glassfish/TokenResolver.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 @@ -26,9 +26,8 @@ /** * Here is the contract: - * You give me a Map object. - * Then you can call resolve(List) and/or resolve(String) and/or - * resolve(Map) + * You give me a {@code Map} object. + * Then you can call {@link #resolve(String)}, {@link #resolve(List)}, {@link #resolve(Map)}. * I will find and replace the tokens, e.g., ${foo} with the value of "foo" in the properties. * If the token has no such property -- then I leave the token as is. * It purposely does not handle nested tokens. E.g. if the "foo" property has another diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/AsadminInput.java b/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/AsadminInput.java index ff5cf16aec7..7d226c33bfb 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/AsadminInput.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/AsadminInput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Contributors to the Eclipse Foundation. + * Copyright (c) 2024, 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 @@ -50,8 +50,8 @@ * Currently there is only one version supported. The lines following * the version spec must be in the format of a properties file, with the convention * that each property name is (category).(property-within-category)=value - * The {@link InputReader} returned will return a Map from - * its {@link InputReader#settings() } method. The map will contain one entry for + * The {@link InputReader} returned will return a {@code Map} from + * its {@link InputReader#settings()} method. The map will contain one entry for * each category in the input, and the associated Properties object will map each * property-within-category to its value. * diff --git a/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/MapInjectionResolver.java b/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/MapInjectionResolver.java index e3ddd3ac342..6f8c6a2af10 100644 --- a/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/MapInjectionResolver.java +++ b/nucleus/common/common-util/src/main/java/org/glassfish/common/util/admin/MapInjectionResolver.java @@ -268,10 +268,10 @@ static String getParamValueString(final ParameterMap parameters, /** * Get the value of the field. This value is defined in the * annotated Param declaration. For example: - * - * @Param(optional=true) - * String name="server" - * + *

    +     * {@code @Param(optional=true)
    +     * String name="server"}
    +     * 
    * The Field, name's value, "server" is returned. * * @param component command class object diff --git a/nucleus/common/common-util/src/test/java/com/sun/enterprise/util/net/NetUtilsIT.java b/nucleus/common/common-util/src/test/java/com/sun/enterprise/util/net/NetUtilsIT.java index 29ba6856b23..e5c994134f4 100644 --- a/nucleus/common/common-util/src/test/java/com/sun/enterprise/util/net/NetUtilsIT.java +++ b/nucleus/common/common-util/src/test/java/com/sun/enterprise/util/net/NetUtilsIT.java @@ -295,7 +295,7 @@ void hostnameUnreachable() throws Exception { } private GenericContainer createContainerWitHosts(String hostFileContent, String containerClass) throws IOException { - String command = "echo \"" + hostFileContent + "\" > /etc/hosts && " + COMMAND_SUFFIX; + String command = "echo \"" + hostFileContent + "\" > /etc/hosts && echo \"hosts: files\" > /etc/nsswitch.conf && " + COMMAND_SUFFIX; return createContainer(command, containerClass); } diff --git a/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/jdbc/DataSource.java b/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/jdbc/DataSource.java index b9c866a423e..5e8ee6b5a55 100644 --- a/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/jdbc/DataSource.java +++ b/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/jdbc/DataSource.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 @@ -45,9 +46,9 @@ public interface DataSource extends javax.sql.DataSource { * Retrieves the actual SQLConnection from the Connection wrapper implementation of SunONE application server. If an * actual connection is supplied as argument, then it will be just returned. * - * @param con Connection obtained from Datasource.getConnection() - * @return java.sql.Connection implementation of the driver. - * @throws java.sql.SQLException If connection cannot be obtained. + * @param con {@link Connection} obtained from Datasource.getConnection() + * @return {@link Connection} implementation of the driver. + * @throws SQLException If connection cannot be obtained. */ Connection getConnection(Connection con) throws SQLException; @@ -56,8 +57,8 @@ public interface DataSource extends javax.sql.DataSource { * on enlisting/delisting each connection got, irrespective of whether its required or not. Note here that this meethod * does not fit in the connector contract per se. * - * @return java.sql.Connection - * @throws java.sql.SQLException If connection cannot be obtained + * @return {@link Connection} + * @throws SQLException If connection cannot be obtained */ Connection getNonTxConnection() throws SQLException; @@ -66,35 +67,36 @@ public interface DataSource extends javax.sql.DataSource { * on enlisting/delisting each connection got, irrespective of whether its required or not. Note here that this meethod * does not fit in the connector contract per se. * - * @param user User name for authenticating the connection + * @param userName 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 + * @return {@link Connection} + * @throws SQLException If connection cannot be obtained */ Connection getNonTxConnection(String userName, String password) throws SQLException; /** - * API to mark a connection as bad. If the application can determine that the connection is bad, using this api, it can - * notify the resource-adapter which inturn will notify the connection-pool. Connection-pool will drop and create a new - * connection. eg: + * API to mark a connection as bad. If the application can determine that the connection is bad, + * using this api, it can notify the resource-adapter which inturn will notify the + * connection-pool. Connection-pool will drop and create a new connection. eg: * - *
    -        com.sun.appserv.jdbc.DataSource ds=
    -           (com.sun.appserv.jdbc.DataSource)context.lookup("dataSource");
    -              Connection con = ds.getConnection();
    -              Statement stmt = null;
    -              try{
    -                      stmt = con.createStatement();
    -                      stmt.executeUpdate("Update");
    -             }catch(BadConnectionException e){
    -                     dataSource.markConnectionAsBad(con) //marking it as bad for removal
    -             }finally{
    -                     stmt.close();
    -                     con.close(); //Connection will be destroyed while close or Tx completion
    -        }
    -     * 
    + *
    {@code
    +     * com.sun.appserv.jdbc.DataSource ds = (com.sun.appserv.jdbc.DataSource) context.lookup("dataSource");
    +     * Connection con = ds.getConnection();
    +     * Statement stmt = null;
    +     * try ({
    +     *     stmt = con.createStatement();
    +     *     stmt.executeUpdate("Update");
    +     * } catch (BadConnectionException e) {
    +     *     //marking it as bad for removal
    +     *     dataSource.markConnectionAsBad(con)
    +     * } finally {
    +     *     stmt.close();
    +     *     //Connection will be destroyed while close or Tx completion
    +     *     con.close();
    +     * }
    +     * }
    * - * @param conn java.sql.Connection + * @param conn {@link Connection} */ void markConnectionAsBad(Connection conn); diff --git a/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/server/LifecycleListener.java b/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/server/LifecycleListener.java index c0da2fbafe8..56279807130 100755 --- a/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/server/LifecycleListener.java +++ b/nucleus/common/glassfish-api/src/main/java/com/sun/appserv/server/LifecycleListener.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,7 +42,7 @@ public interface LifecycleListener { * receive a server lifecycle event * * @param event associated event - * @throws ServerLifecycleException for exception condition. + * @throws ServerLifecycleException for exception condition. * */ void handleEvent(LifecycleEvent event) throws ServerLifecycleException; diff --git a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/StartupRunLevel.java b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/StartupRunLevel.java index 543c45db31a..6b02017f7f2 100644 --- a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/StartupRunLevel.java +++ b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/StartupRunLevel.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 @@ * The meta annotation representing the Startup RunLevel. * * @author Jeff Trent - * @see {@link RunLevelService} in Hk2 + * @see RunLevel service in Hk2 */ @Retention(RUNTIME) @Target(TYPE) diff --git a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/PasswordAliasStore.java b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/PasswordAliasStore.java index 93e32a76062..0894d22f7c5 100644 --- a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/PasswordAliasStore.java +++ b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/PasswordAliasStore.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2013, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -24,11 +25,13 @@ /** * Represents a fully-functional password alias store. *

    - * If the implementation holds the aliases and passwords in memory, it handles loading and saving the in-memory contents - * from and to persistent storage, at the discretion of the implementer. For example, loading would typically happen - * when the password alias store implementation is first instantiated, although an implementation could choose to load - * lazily on first read. Saving is at the discretion of the implementer as well, although to maximize reliability the - * implementation should persist changes as they occur. The {@link #putAll ) methods can help optimize that. + * If the implementation holds the aliases and passwords in memory, it handles loading and saving + * the in-memory contents from and to persistent storage, at the discretion of the implementer. + * For example, loading would typically happen when the password alias store implementation is first + * instantiated, although an implementation could choose to load lazily on first read. Saving is at + * the discretion of the implementer as well, although to maximize reliability the implementation + * should persist changes as they occur. + * The {@link #putAll(Map)} and {@link #putAll(PasswordAliasStore)} can help optimize that. * * @author tjquinn */ @@ -52,23 +55,17 @@ public interface PasswordAliasStore { char[] get(String alias); /** - * Reports whether the alias store is empty. - * - * @return + * @return true if the alias store is empty. */ boolean isEmpty(); /** - * Returns an Iterator over aliases present in the alias store. - * - * @return + * @return an Iterator over aliases present in the alias store. */ Iterator keys(); /** - * Reports the number of aliases present in the store. - * - * @return + * @return the number of aliases present in the store. */ int size(); @@ -95,8 +92,9 @@ public interface PasswordAliasStore { /** * Adds a group of alias/password pairs in a single operation. *

    - * Callers might prefer to invoke this method once rather than invoking {@link #put ) repeatedly, for example if an - * implementation persists each change as it is made. + * Callers might prefer to invoke this method once rather than invoking + * {@link #put(String, char[])} repeatedly, for example if an implementation persists each + * change as it is made. * * @param settings the alias/password pairs to add */ diff --git a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/config/ConfigParser.java b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/config/ConfigParser.java index 3fa34f533ae..7cfb21d544e 100644 --- a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/config/ConfigParser.java +++ b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/admin/config/ConfigParser.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -30,18 +31,15 @@ public interface ConfigParser { /** - * Parse a Container's configuration defined by it's XML template pointed by configuration URL.
    - *
    - * Example:
    - * + * Parse a Container's configuration defined by it's XML template pointed by configuration URL. + *

    + * Example:
    * Inside your {@link org.glassfish.api.container.Sniffer}: - * *

          *
    -     * {@link @Inject}
    -     * ConfigParser parser;
    -     *
    -     * {@link @Inject}
    +     * {@code @Inject
    +     * ConfigParser parser;}
    +     * {@code @Inject
          * JrubyContainer container;
          *
          * public Module[] setup(java.lang.String s, java.util.logging.Logger logger) throws java.io.IOException{
    @@ -51,7 +49,7 @@ public interface ConfigParser {
          *         //Now do stuff with config
          *     }
          * }
    -     * 
    + * }
    * * @return Confgured container * @throws IOException diff --git a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/content/WebRequestHandler.java b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/content/WebRequestHandler.java index 8fc0c70273f..fa4cba1e9a4 100644 --- a/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/content/WebRequestHandler.java +++ b/nucleus/common/glassfish-api/src/main/java/org/glassfish/api/content/WebRequestHandler.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2006, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -26,7 +27,7 @@ * this particular context as it can be file servicing, or any other type of behaviour. The type of handling the * annotated class will usually be defined by an interface the class implements * - * @see {link:FileServer} + * @see FileServer * * @author Jerome Dochez */ diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/flashlight/datatree/TreeNode.java b/nucleus/common/internal-api/src/main/java/org/glassfish/flashlight/datatree/TreeNode.java index 3695fa59784..bf6030fda6a 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/flashlight/datatree/TreeNode.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/flashlight/datatree/TreeNode.java @@ -99,7 +99,7 @@ public interface TreeNode extends TreeElement { public List getNodes (String pattern, boolean ignoreDisabled, boolean gfv2Compatible); /** - * Behaves as {@link #getNodes (String, boolean, boolean) with ignoreDisabled set to true + * Behaves as {@link #getNodes(String, boolean, boolean)} with ignoreDisabled set to true * and gfV2Compatible set to true * Pattern is considered to be a GFV2 Compatible Pattern */ diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/ClassLoaderHierarchy.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/ClassLoaderHierarchy.java index 482ee3368cf..7f65f65937f 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/ClassLoaderHierarchy.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/ClassLoaderHierarchy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Contributors to the Eclipse Foundation + * Copyright (c) 2022, 2026 Contributors to the Eclipse Foundation * Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -93,10 +93,9 @@ public interface ClassLoaderHierarchy { * @return class loader that has visibility to appropriate * application specific libraries. * @throws MalformedURLException - * @see #getAppLibClassFinder(List) + * @see #getAppLibClassFinder(List) */ - ClassLoader getAppLibClassLoader(String application, List libURIs) - throws MalformedURLException; + ClassLoader getAppLibClassLoader(String application, List libURIs) throws MalformedURLException; /** * Returns ApplibClassFinder. As the name suggests, this class finder @@ -113,10 +112,9 @@ ClassLoader getAppLibClassLoader(String application, List libURIs) * @return class loader that has visibility to appropriate * application specific libraries. * @throws MalformedURLException - * @see #getAppLibClassLoader(String, List) + * @see #getAppLibClassLoader(String, List) */ - DelegatingClassLoader.ClassFinder getAppLibClassFinder(List libURIs) - throws MalformedURLException; + DelegatingClassLoader.ClassFinder getAppLibClassFinder(List libURIs) throws MalformedURLException; /** diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/InitRunLevel.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/InitRunLevel.java index 63c600a21fc..56bee469af8 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/InitRunLevel.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/InitRunLevel.java @@ -29,7 +29,7 @@ * The meta annotation representing the Init RunLevel. * * @author Jeff Trent - * @see {@link RunLevelService} in Hk2 + * @see RunLevel in Hk2 */ @Retention(RUNTIME) @Target(TYPE) diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/PostStartupRunLevel.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/PostStartupRunLevel.java index 237ca541534..60ca63dbb23 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/PostStartupRunLevel.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/PostStartupRunLevel.java @@ -26,10 +26,10 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; /** - * The meta annotation representing the {@link PostStartup} RunLevel. + * The meta annotation representing the Post Startup RunLevel. * * @author Jeff Trent - * @see {@link RunLevelService} in Hk2 + * @see RunLevel in Hk2 */ @Retention(RUNTIME) @Target(TYPE) diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/UndoableCommand.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/UndoableCommand.java index 74d0e237114..aa26d07cc92 100755 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/UndoableCommand.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/api/UndoableCommand.java @@ -59,7 +59,7 @@ * method is invoked (and any supplemented methods). * *

    If the framework is electing that successful commands execution need to be rolled back, it will - * call the {@link #undo(AdminCommandContext, ParameterMap, List)} method on the same instance that was used for the + * call the {@link #undo(AdminCommandContext, ParameterMap, List)} method on the same instance that was used for the * {@link #execute(AdminCommandContext)} invocation, as well as any supplemented commands that implement * this interface. * @@ -76,7 +76,7 @@ public interface UndoableCommand extends AdminCommand { * servers instances are on-line and can be notified of the change. * *

    No changes to the configuration should be made within the implementation of the - * prepare method since {@link #undo(AdminCommandContext, ParameterMap, List)} will not be called if the command + * prepare method since {@link #undo(AdminCommandContext, ParameterMap, List)} will not be called if the command * execution stops at the prepare phase. * *

    Note that if, as part of prepare, remote instances have to be contacted, then it is the responsibility of @@ -97,7 +97,7 @@ public interface UndoableCommand extends AdminCommand { * for undoing the administrative operation should be obtained from either the * parameters passed to the command execution or the command instance context. * The list of servers indicates to the command implementation on which servers the command succeeded - * The command implementation is guaranteed that the {@link #undo(AdminCommandContext, ParameterMap, List)} + * The command implementation is guaranteed that the {@link #undo(AdminCommandContext, ParameterMap, List)} * is called on DAS if the main command execution failed on one instance but it is the responsiblity of the command * implementation to invoke remote instances to do the actual undo if required * diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/EmbeddedDeployer.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/EmbeddedDeployer.java index 61ad93cb6f9..e5883c4d4ba 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/EmbeddedDeployer.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/EmbeddedDeployer.java @@ -82,7 +82,7 @@ public interface EmbeddedDeployer { /** * Undeploys a previously deployed application * - * @param name name returned by {@link EmbeddedDeployer#deploy(File, org.glassfish.api.deployment.DeployCommandParameters} + * @param name name returned by {@link EmbeddedDeployer#deploy(File, DeployCommandParameters)} * @param params the undeployment parameters, can be null for default values */ public void undeploy(String name, UndeployCommandParameters params); diff --git a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredArchive.java b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredArchive.java index ef005afd364..7c09424e5d4 100644 --- a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredArchive.java +++ b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredArchive.java @@ -19,6 +19,7 @@ import java.io.File; import java.io.IOException; +import java.lang.System.Logger; import java.lang.System.Logger.Level; import java.net.URI; import java.util.ArrayList; @@ -29,36 +30,25 @@ /** * Abstraction for a Scattered Jakarta EE module (parts disseminated in various directories). - *

    - *

    - * Usage example : - *

    - * - *

    - *         GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    - *         glassfish.start();
    - * 
    - *         // Create a scattered web application.
    - *         ScatteredArchive archive = new ScatteredArchive("testapp", ScatteredArchive.Type.WAR);
    - *         // target/classes directory contains my complied servlets
    - *         archive.addClassPath(new File("target", "classes"));
    - *         // resources/sun-web.xml is my WEB-INF/sun-web.xml
    - *         archive.addMetadata(new File("resources", "sun-web.xml"));
    - *         // resources/MyLogFactory is my META-INF/services/org.apache.commons.logging.LogFactory
    - *         archive.addMetadata(new File("resources", "MyLogFactory"),
    - *                 "META-INF/services/org.apache.commons.logging.LogFactory");
    - * 
    - *         Deployer deployer = glassfish.getDeployer();
    - *         // Deploy my scattered web application
    - *         deployer.deploy(archive.toURI());
    - * 
    + *

    + * Usage example: + * + *

    {@code
    + * GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    + * glassfish.start();
    + * // Create a scattered web application.
    + * ScatteredArchive archive = ScatteredArchive("testapp", ScatteredArchive.Type.WAR);
    + * // target/classes directory contains my complied servlets
    + * archive.addClassPath(new File("target", "classes"));
    + * // resources/sun-web.xml is my WEB-INF/sun-web.xml
    + * archive.addMetadata(new File("resources", "sun-web.xml"));
    + * // resources/MyLogFactory is my META-INF/services/org.apache.commons.logging.LogFactory
    + * archive.addMetadata(new File("resources", "MyLogFactory"), "META-INF/services/org.apache.commons.logging.LogFactory");
    + *
    + * Deployer deployer = glassfish.getDeployer();
    + * // Deploy my scattered web application
    + * deployer.deploy(archive.toURI());
    + * }
    * * @author Jerome Dochez * @author bhavanishankar@java.net @@ -95,16 +85,6 @@ public ScatteredArchive(String name, Type type) { this.metadataEntryPrefix = (type == Type.WAR) ? "WEB-INF/" : "META-INF/"; } - /** - * Construct a new scattered archive with all the contents from the rootDirectory. - *

    - * Follows the same semantics as {@link ScatteredArchive(String, ScatteredArchive.Type, File)} constructor. - * rootDirectory must be a File location. - */ -// public ScatteredArchive(String name, Type type, String rootDirectory) { -// this(name, type, rootDirectory != null ? new File(rootDirectory) : null); -// } - /** * Construct a new scattered archive with all the contents from the rootDirectory. *

    @@ -148,50 +128,6 @@ public ScatteredArchive(String name, Type type, File rootDirectory) this.rootDirectory = rootDirectory; } - /** - * Construct a new scattered archive with a set of classpaths. - * - * Follows the same semantics as - * {@link ScatteredArchive(String, ScatteredArchive.Type, String, File[])} constructor. - * - * All classpaths[] must be File locations. - */ -// public ScatteredArchive(String name, Type type, String[] classpaths) { -// -// } - - /** - * Construct a new scattered archive with a set of classpaths. - *

    - * classpaths can contain Directory or JAR file locations. - *

    - * Using this constructor has the same effect of doing: - *

    -     *      ScatteredArchive archive = new ScatteredArchive(name, type);
    -     *      for(String classpath : classpaths)
    -     *          archive.addClassPath(classpath);
    -     *      }
    - * - * @param name Name of the archive. - * @param type Type of the archive "war" or "jar" or "rar". - * @param classpaths Directory or JAR file locations. - * @throws NullPointerException if name, type or classpaths is null - * @throws IllegalArgumentException if any of the classpaths is not found. - */ -// public ScatteredArchive(String name, Type type, File[] classpaths) { -// -// } - - /** - * Add a directory or a JAR file to this scattered archive. - *

    - * Follows the same semantics as {@link #addClassPath(File)} method. - * classpath must be a File location. - */ -// public void addClassPath(String classpath) { -// addClassPath(classpath != null ? new File(classpath) : null); -// } - /** * Add a directory or a JAR file to this scattered archive. *

    @@ -246,7 +182,7 @@ public void addClassPath(File classpath) throws IOException { /** * Add all directories and JAR files on the current classpath to this scattered archive - * using {@link #addClassPath(java.io.File). + * using {@link #addClassPath(File)}. * Ignores Jakarta EE API and GlassFish Embedded JAR files (those that match the {@code jakarta.} * and {@code glassfish-embedded-} prefixes). *

    @@ -255,7 +191,7 @@ public void addClassPath(File classpath) throws IOException { *

    * The classpath that is added is considered as a plain Java CLASSPATH. *

    - * If a classpath element is not found, a warning is logged using {@link System.Logger} and + * If a classpath element is not found, a warning is logged using {@link Logger} and * the element is ignored. * * @param excludePatterns If a JAR file name matches any of these regular expressions @@ -274,7 +210,7 @@ public void addCurrentClassPath(String... excludePatterns) { /** * Add all directories and JAR files on the current classpath to this scattered archive - * using {@link #addClassPath(java.io.File). + * using {@link #addClassPath(java.io.File)}. * Ignores Jakarta EE API and GlassFish Embedded JAR files (those that match the {@code jakarta.} * and {@code glassfish-embedded-} prefixes). *

    @@ -283,7 +219,7 @@ public void addCurrentClassPath(String... excludePatterns) { *

    * The classpath that is added is considered as a plain Java CLASSPATH. *

    - * If a classpath element is not found, a warning is logged using {@link System.Logger} and + * If a classpath element is not found, a warning is logged using {@link Logger} and * the element is ignored. * * @param exclude A predicate to exclude mathing elements from the classpath. @@ -320,20 +256,6 @@ private static boolean fileNameMatchesAny(String fileName, String... matches) { return false; } - - /** - * Add a new metadata to this scattered archive. - *

    - * The addMetadata(metadata) method has the same effect as: - *

    -     *      addMetadata(metadata, null)
    -     * 
    - * Follows the same semantics as {@link #addMetadata(String, String)} method. - */ -// public void addMetadata(String metadata) { -// addMetadata(metadata != null ? new File(metadata) : null); -// } - /** * Add a new metadata to this scattered archive. *

    @@ -347,16 +269,6 @@ public void addMetadata(File metadata) throws IOException { addMetadata(metadata, null); } - /** - * Add a new metadata to this scattered archive. - *

    - * Follows the same semantics as {@link #addMetadata(File, String)} method. - * metadata must be a file location. - */ -// public void addMetadata(String metadata, String name) { -// addMetadata(metadata != null ? new File(metadata) : null, name); -// } - /** * Add a new metadata to this scattered archive. *

    @@ -394,44 +306,6 @@ public void addMetadata(File metadata, String name) throws IOException { this.metadatas.put(name, metadata); } - /** - * Set the location of resources files to this scattered archive. - *

    - * Follows the same semantics as {@link #setResourcePath(File)} method. - * resourcespath must be a File location. - */ -// public void setResourcePath(String resourcespath) { -// setResourcePath(resourcespath != null ? new File(resourcespath) : null); -// } - - /** - * Set the location of resources files to this scattered archive. - *

    - * For a WAR type scattered archive, the specified resource location can be - * thought of as a document root of the web application. The document root - * is where JSP pages, and static web resources such as images are stored. - *

    - * For the other type of archive, all the contents under the specified - * resource location will be available in the deployed scattered - * application's classloader. - * - * @param resourcespath Resources directory. - * @throws NullPointerException if resourcepath is null. - * @throws IllegalArgumentException if resourcespath is not found or is not a directory. - */ -// public void setResourcePath(File resourcespath) { -// if (resourcespath == null) { -// throw new NullPointerException("resourcespath must not be null."); -// } -// if (!resourcespath.exists()) { -// throw new IllegalArgumentException(resourcespath + " does not exist."); -// } -// if (!resourcespath.isDirectory()) { -// throw new IllegalArgumentException(resourcespath + " is not a directory"); -// } -// this.resourcespath = resourcespath; -// } - /** * Get the deployable URI for this scattered archive. *

    diff --git a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredEnterpriseArchive.java b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredEnterpriseArchive.java index 818d416d83a..419760a50df 100644 --- a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredEnterpriseArchive.java +++ b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/ScatteredEnterpriseArchive.java @@ -26,46 +26,36 @@ /** * Abstraction for a Scattered Jakarta EE Application. - *

    - *

    + *

    * Usage example : - *

    - * - *

    - *         GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    - *         glassfish.start();
    - * 
    - *         // Create a scattered web application.
    - *         ScatteredArchive webmodule = new ScatteredArchive("testweb", ScatteredArchive.Type.WAR);
    - *         // target/classes directory contains my complied servlets
    - *         webmodule.addClassPath(new File("target", "classes"));
    - *         // resources/sun-web.xml is my WEB-INF/sun-web.xml
    - *         webmodule.addMetadata(new File("resources", "sun-web.xml"));
    - * 
    - *         // Create a scattered enterprise archive.
    - *         ScatteredEnterpriseArchive archive = new ScatteredEnterpriseArchive("testapp");
    - *         // src/application.xml is my META-INF/application.xml
    - *         archive.addMetadata(new File("src", "application.xml"));
    - *         // Add scattered web module to the scattered enterprise archive.
    - *         // src/application.xml references Web module as "scattered.war". Hence specify the name while adding the archive.
    - *         archive.addArchive(webmodule.toURI(), "scattered.war");
    - *         // lib/mylibrary.jar is a library JAR file.
    - *         archive.addArchive(new File("lib", "mylibrary.jar"));
    - *         // target/ejbclasses contain my compiled EJB module.
    - *         // src/application.xml references EJB module as "ejb.jar". Hence specify the name while adding the archive.
    - *         archive.addArchive(new File("target", "ejbclasses"), "ejb.jar");
    - * 
    - *         Deployer deployer = glassfish.getDeployer();
    - *         // Deploy my scattered web application
    - *         deployer.deploy(webmodule.toURI());
    - * 
    + + *
    {@code
    + * GlassFish glassfish = GlassFishRuntime.bootstrap().newGlassFish();
    + * glassfish.start();
    + * // Create a scattered web application.
    + * ScatteredArchive webmodule = new ScatteredArchive("testweb", ScatteredArchive.Type.WAR);
    + * // target/classes directory contains my complied servlets
    + * webmodule.addClassPath(new File("target", "classes"));
    + * // resources/sun-web.xml is my WEB-INF/sun-web.xml
    + * webmodule.addMetadata(new File("resources", "sun-web.xml"));
    + *
    + * // Create a scattered enterprise archive.
    + * ScatteredEnterpriseArchive archive = new ScatteredEnterpriseArchive("testapp");
    + * // src/application.xml is my META-INF/application.xml
    + * archive.addMetadata(new File("src", "application.xml"));
    + * // Add scattered web module to the scattered enterprise archive.
    + * // src/application.xml references Web module as "scattered.war". Hence specify the name while adding the archive.
    + * archive.addArchive(webmodule.toURI(), "scattered.war");
    + * // lib/mylibrary.jar is a library JAR file.
    + * archive.addArchive(new File("lib", "mylibrary.jar"));
    + * // target/ejbclasses contain my compiled EJB module.
    + * // src/application.xml references EJB module as "ejb.jar". Hence specify the name while adding the archive.
    + * archive.addArchive(new File("target", "ejbclasses"), "ejb.jar");
    + *
    + * Deployer deployer = glassfish.getDeployer();
    + * // Deploy my scattered web application
    + * deployer.deploy(webmodule.toURI());
    + * }
    * * @author bhavanishankar@java.net */ @@ -123,30 +113,6 @@ public void addArchive(URI archiveURI, String name) throws IOException { addArchive(archiveURI != null ? new File(archiveURI) : null, name); } - /** - * Add a module or a library to this scattered enterprise archive. - *

    - * The addArchive(archive) method has the same effect as: - *

    -     *      addArchive(archive, null)
    -     * 
    - * Follows the same semantics as {@link #addArchive(File, String)} method. - * archive must be a file location. - */ -// public void addArchive(String archive) { -// addArchive(archive, null); -// } - - /** - * Add a module or a library to this scattered enterprise archive. - *

    - * Follows the same semantics as {@link #addArchive(File, String)} method. - * archive must be a file location. - */ -// public void addArchive(String archive, String name) { -// addArchive(archive != null ? new File(archive) : null, name); -// } - /** * Add a module or a library to this scattered enterprise archive. *

    diff --git a/nucleus/common/simple-glassfish-api/src/main/java/org/glassfish/embeddable/GlassFish.java b/nucleus/common/simple-glassfish-api/src/main/java/org/glassfish/embeddable/GlassFish.java index 3fc6e54a4e8..a56398f8a56 100644 --- a/nucleus/common/simple-glassfish-api/src/main/java/org/glassfish/embeddable/GlassFish.java +++ b/nucleus/common/simple-glassfish-api/src/main/java/org/glassfish/embeddable/GlassFish.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2026 Contributors to the Eclipse Foundation. * Copyright (c) 2009, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -18,64 +19,50 @@ /** * Represents a GlassFish instance and provides the ability to: - * *

      - *
    • perform life cycle operations viz., start, stop and dispose.
    • - *
    • access {@link Deployer} to deploy/undeploy applications.
    • - *
    • access {@link CommandRunner} to perform runtime configurations.
    • - *
    • access to available service(s).
    • + *
    • perform life cycle operations viz., start, stop and dispose.
    • + *
    • access {@link Deployer} to deploy/undeploy applications.
    • + *
    • access {@link CommandRunner} to perform runtime configurations.
    • + *
    • access to available service(s).
    • *
    + *

    + * Usage example: * - *

    Usage example: - * - * - * - *

    -
    -        /** Create and start GlassFish */
    -        {@link GlassFish} glassfish = {@link GlassFishRuntime}.bootstrap().newGlassFish();
    -        glassfish.start();
    -
    -        /** Deploy a web application simple.war with /hello as context root. */
    -        {@link Deployer} deployer = glassfish.getService(Deployer.class);
    -        String deployedApp = deployer.deploy(new File("simple.war").toURI(),
    -                "--contextroot=hello", "--force=true");
    -
    -        /** Run commands (as per your need). Here is an example to create a http listener and dynamically set its thread pool size. */
    -        {@link CommandRunner} commandRunner = glassfish.getService(CommandRunner.class);
    -
    -        // Run a command create 'my-http-listener' to listen at 9090
    -        {@link CommandResult} commandResult = commandRunner.run(
    -                "create-http-listener", "--listenerport=9090",
    -                "--listeneraddress=0.0.0.0", "--defaultvs=server",
    -                "my-http-listener");
    -
    -        // Run a command to create your own thread pool
    -        commandResult = commandRunner.run("create-threadpool",
    -                "--maxthreadpoolsize=200", "--minthreadpoolsize=200",
    -                "my-thread-pool");
    -
    -        // Run a command to associate my-thread-pool with my-http-listener
    -        commandResult = commandRunner.run("set",
    -                "server.network-config.network-listeners.network-listener." +
    -                        "my-http-listener.thread-pool=my-thread-pool");
    -
    -        /** Undeploy the application */
    -        deployer.undeploy(deployedApp);
    -
    -        /**Stop GlassFish.*/
    -        glassfish.stop();
    -
    -        /** Dispose GlassFish. */
    -        glassfish.dispose();
    - * 
    + *
    {@code
    +    // Create and start GlassFish
    +    GlassFish glassfish = {@link GlassFishRuntime}.bootstrap().newGlassFish();
    +    glassfish.start();
    +
    +    // Deploy a web application simple.war with /hello as context root.
    +    Deployer deployer = glassfish.getService(Deployer.class);
    +    String deployedApp = deployer.deploy(new File("simple.war").toURI(), "--contextroot=hello", "--force=true");
    +
    +    // Run commands (as per your need). Here is an example to create
    +    // a http listener and dynamically set its thread pool size.
    +    CommandRunner commandRunner = glassfish.getService(CommandRunner.class);
    +
    +    // Run a command create 'my-http-listener' to listen at 9090
    +    CommandResult commandResult = commandRunner.run(
    +            "create-http-listener", "--listenerport=9090",
    +            "--listeneraddress=0.0.0.0", "--defaultvs=server",
    +            "my-http-listener");
    +
    +    // Run a command to create your own thread pool
    +    commandResult = commandRunner.run("create-threadpool",
    +            "--maxthreadpoolsize=200", "--minthreadpoolsize=200",
    +            "my-thread-pool");
    +
    +    // Run a command to associate my-thread-pool with my-http-listener
    +    commandResult = commandRunner.run("set",
    +            "server.network-config.network-listeners.network-listener.my-http-listener.thread-pool=my-thread-pool");
    +
    +    // Undeploy the application
    +    deployer.undeploy(deployedApp);
    +
    +    /**Stop and dispose GlassFish.
    +    glassfish.stop();
    +    glassfish.dispose();
    + * }
    * * @author Sanjeeb.Sahoo@Sun.COM */ @@ -85,7 +72,7 @@ public interface GlassFish { * When this method is called, all the lifecycle (aka startup) services are started. * Calling this method while the server is in {@link Status#STARTED} state is a no-op. * - * @throws {@link IllegalStateException} if server is already started. + * @throws IllegalStateException if server is already started. * @throws GlassFishException if server can't be started for some unknown reason. */ void start() throws GlassFishException; @@ -95,7 +82,7 @@ public interface GlassFish { * GlassFish can be started again by calling the start method. * Calling this method while the server is in {@link Status#STARTED} state is a no-op. * - * @throws {@link IllegalStateException} if server is already stopped. + * @throws IllegalStateException if server is already stopped. * @throws GlassFishException if server can't be started for some unknown reason. */ void stop() throws GlassFishException; @@ -153,13 +140,13 @@ public interface GlassFish { CommandRunner getCommandRunner() throws GlassFishException; /** - * Represents the status of {@link org.glassfish.embeddable.GlassFish}. + * Represents the status of {@link GlassFish}. */ enum Status { /** * Initial state of a newly created GlassFish. * - *

    This will be the state just after {@link org.glassfish.embeddable.GlassFishRuntime#newGlassFish()} + *

    This will be the state just after {@link GlassFishRuntime#newGlassFish()} * before performing any lifecycle operations. */ INIT, @@ -167,7 +154,7 @@ enum Status { /** * GlassFish is being started. * - *

    This will be the state after {@link org.glassfish.embeddable.GlassFish#start()} has been called + *

    This will be the state after {@link GlassFish#start()} has been called * until the GlassFish is fully started. */ STARTING, @@ -175,7 +162,7 @@ enum Status { /** * GlassFish is up and running. * - *

    This will be the state once {@link org.glassfish.embeddable.GlassFish#start()} has fully + *

    This will be the state once {@link GlassFish#start()} has fully * started the GlassFish. */ STARTED, @@ -183,7 +170,7 @@ enum Status { /** * GlassFish is being stopped. * - *

    This will be the state after {@link org.glassfish.embeddable.GlassFish#stop()} has been + *

    This will be the state after {@link GlassFish#stop()} has been * called until the GlassFish is fully stopped. */ STOPPING, @@ -191,7 +178,7 @@ enum Status { /** * GlassFish is stopped. * - *

    This will be the state after {@link org.glassfish.embeddable.GlassFish#stop()} has + *

    This will be the state after {@link GlassFish#stop()} has * fully stopped the GlassFish. */ STOPPED, @@ -199,8 +186,8 @@ enum Status { /** * GlassFish is disposed and ready to be garbage collected. * - *

    This will be the state after {@link org.glassfish.embeddable.GlassFish#dispose()} or - * {@link org.glassfish.embeddable.GlassFishRuntime#shutdown()} has been called. + *

    This will be the state after {@link GlassFish#dispose()} or + * {@link GlassFishRuntime#shutdown()} has been called. */ DISPOSED } diff --git a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/server/LifecycleListenerImpl.java b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/server/LifecycleListenerImpl.java index ad364c4b8ab..93a8177755a 100755 --- a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/server/LifecycleListenerImpl.java +++ b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/server/LifecycleListenerImpl.java @@ -29,19 +29,17 @@ */ public class LifecycleListenerImpl implements LifecycleListener { - /** receive a server lifecycle event - * @param event associated event - * @throws ServerLifecycleException for exceptional condition. - * + /** * Configure this module as a lifecycle-module in server.xml: - * + *

    {@code
          *  
          *    
    +     *        class-name="com.sun.appserv.server.LifecycleListenerImpl"
    +     *        is-failure-fatal="false">
          *      
          *    
          *  
    +     *  }
    * * Setis-failure-fatalin server.xml to true for * fatal conditions. diff --git a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/ContainerMapper.java b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/ContainerMapper.java index 226896bd5bd..93795b98208 100644 --- a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/ContainerMapper.java +++ b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/ContainerMapper.java @@ -25,7 +25,6 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Logger; -import org.glassfish.api.container.Adapter; import org.glassfish.api.container.Sniffer; import org.glassfish.api.deployment.ApplicationContainer; import org.glassfish.api.logging.LogHelper; @@ -78,7 +77,7 @@ public class ContainerMapper extends ADBAwareHttpHandler { private String defaultHostName = "server"; /** - * Are we running multiple {@ Adapter} or {@link HttpHandlerChain} + * Are we running multiple {@link HttpHandler} or {@link HttpHandlerChain} */ private boolean mapMultipleAdapter; @@ -103,7 +102,7 @@ protected void setDefaultHost(String defaultHost) { } /** - * Set the {@link ContextMapper} instance used for mapping the container and its associated {@link Adapter}. + * Set the {@link ContextMapper} instance used for mapping the container and its associated {@link HttpHandler}. * * @param mapper */ @@ -129,7 +128,7 @@ protected void configureMapper() { } /** - * Map the request to its associated {@link Adapter}. + * Map the request to its associated {@link HttpHandler}. * * @param request * @param response diff --git a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/Endpoint.java b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/Endpoint.java index 5fdb33c15db..b244a523f12 100644 --- a/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/Endpoint.java +++ b/nucleus/core/kernel/src/main/java/com/sun/enterprise/v3/services/impl/Endpoint.java @@ -32,7 +32,7 @@ public abstract class Endpoint { /** * Creates Endpoint based on the passed {@link Adapter} descriptor. - * @param {@link Adapter} + * @param adapter {@link Adapter} * @return {@link Endpoint}, which can be registered on {@link NetworkProxy}. */ public static Endpoint createEndpoint(final Adapter adapter) { diff --git a/nucleus/deployment/admin/src/main/java/org/glassfish/deployment/admin/ListComponentsCommand.java b/nucleus/deployment/admin/src/main/java/org/glassfish/deployment/admin/ListComponentsCommand.java index fb55f9bf70f..1234380722e 100644 --- a/nucleus/deployment/admin/src/main/java/org/glassfish/deployment/admin/ListComponentsCommand.java +++ b/nucleus/deployment/admin/src/main/java/org/glassfish/deployment/admin/ListComponentsCommand.java @@ -149,6 +149,7 @@ public Collection getAccessChecks() { final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(ListComponentsCommand.class); + @Override public void execute(AdminCommandContext context) { final ActionReport report = context.getActionReport(); @@ -273,7 +274,7 @@ boolean isApplicationOfThisType(final Application app, String type) { /** * return all user visible sniffer engines in an application. - * The return format is + * The return format is {@code } * @param module - Application's module * @return sniffer engines */ @@ -283,7 +284,7 @@ String getAppSnifferEngines(final Application app, final boolean format) { /** * return all user visible sniffer engines in an application. - * The return format is + * The return format is {@code } * @param module - Application's module * @return sniffer engines */ diff --git a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployDirectoryScanner.java b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployDirectoryScanner.java index 9a6b06b7d61..c129482d640 100644 --- a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployDirectoryScanner.java +++ b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployDirectoryScanner.java @@ -14,13 +14,6 @@ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ -/* - * DirectoryScanner.java - * - * - * Created on February 19, 2003, 10:17 AM - */ - package org.glassfish.deployment.autodeploy; import java.io.File; @@ -33,13 +26,13 @@ import org.glassfish.logging.annotation.LogMessageInfo; /** - * Implementation of Directory scanner for autodeployment
    - * Providing functionality for scanning the input source directory
    - * and return the list of deployable components for autodeployment.
    - * Provide the list of deployable modules/application, depending upon the "type" entry
    + * Implementation of Directory scanner for autodeployment + * Providing functionality for scanning the input source directory + * and return the list of deployable components for autodeployment. + * Provide the list of deployable modules/application, depending upon the "type" entry * passed to getAllDeployableEntity(File autodeployDir, String type). * - *@author vikas + * @author vikas 2003 */ public class AutoDeployDirectoryScanner implements DirectoryScanner{ @@ -52,19 +45,21 @@ public class AutoDeployDirectoryScanner implements DirectoryScanner{ public AutoDeployDirectoryScanner() { } - public void deployedEntity(File autodeployDir, File deployedEntity) { - try { - AutoDeployedFilesManager adfm = AutoDeployedFilesManager.loadStatus(autodeployDir); - adfm.setDeployedFileInfo(deployedEntity); - adfm.writeStatus(); - } catch (Exception e) { - printException(e); - // Do nothing - } + @Override + public void deployedEntity(File autodeployDir, File deployedEntity) { + try { + AutoDeployedFilesManager adfm = AutoDeployedFilesManager.loadStatus(autodeployDir); + adfm.setDeployedFileInfo(deployedEntity); + adfm.writeStatus(); + } catch (Exception e) { + printException(e); + // Do nothing + } - } + } - public void undeployedEntity(File autodeployDir, File undeployedEntity) { + @Override + public void undeployedEntity(File autodeployDir, File undeployedEntity) { try { AutoDeployedFilesManager adfm = AutoDeployedFilesManager.loadStatus(autodeployDir); adfm.deleteDeployedFileInfo(undeployedEntity); @@ -80,6 +75,7 @@ public void undeployedEntity(File autodeployDir, File undeployedEntity) { * @param autodeployDir * @return */ + @Override public boolean hasNewDeployableEntity(File autodeployDir) { boolean newFilesExist=false; try { @@ -97,6 +93,7 @@ public boolean hasNewDeployableEntity(File autodeployDir) { } // this should never be called from system dir autodeploy code... + @Override public File[] getAllFilesForUndeployment(File autodeployDir, boolean includeSubdir) { try { @@ -112,6 +109,7 @@ public File[] getAllFilesForUndeployment(File autodeployDir, boolean includeSubd * Get the list of all deployable files * @param autodeployDir * @return */ + @Override public File[] getAllDeployableModules(File autodeployDir, boolean includeSubDir) { AutoDeployedFilesManager adfm = null; diff --git a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployer.java b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployer.java index d6a23c49a69..dee28bd6548 100644 --- a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployer.java +++ b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutoDeployer.java @@ -35,18 +35,18 @@ import org.glassfish.logging.annotation.LoggerInfo; /** - * Handles the logic of deploying the module/app to the required destination.
    + * Handles the logic of deploying the module/app to the required destination. * The destination is specified on the constructor and can be modified by * calling setTarget(). The specific directory scanner can be set using * setDirectoryScanner, default is AutoDeployDirectoryScanner - *

    - * Created on February 19, 2003, 10:21 AM * - * @author vikas + * @author vikas 2003 * @author tjquinn */ public class AutoDeployer { + private static final LocalStringManagerImpl localStrings = new LocalStringManagerImpl(AutoDeployer.class); + private Boolean verify=null; private Boolean forceDeploy=null; private Boolean enabled=null; @@ -56,7 +56,6 @@ public class AutoDeployer { private String virtualServer = null; private String target=null; - final private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(AutoDeployer.class); private DirectoryScanner directoryScanner=null; private boolean cancelDeployment =false; @@ -522,7 +521,7 @@ private AutodeploymentStatus undeploy(File applicationFile, File autodeployDir, } /** - * set cancel flag, which will ensure that only if there is any current deployment is in process,
    + * set cancel flag, which will ensure that only if there is any current deployment is in process, * it will be completed but the deployer will not do any more deployment. * @param value the cancel setting */ diff --git a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutodeployRetryManager.java b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutodeployRetryManager.java index dce34d89270..a00251818b6 100644 --- a/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutodeployRetryManager.java +++ b/nucleus/deployment/autodeploy/src/main/java/org/glassfish/deployment/autodeploy/AutodeployRetryManager.java @@ -45,22 +45,22 @@ * failed to deploy earlier and has remained stable in size for a * (configurable) period of time. *

    - * The main public entry point are the {@link �} method and - * the {@link reportSuccessfulDeployment}, - * {@link reportFailedDeployment}, {@link reportSuccessfulUndeployment}, and - * {@link reportUnsuccessfulUndeployment} methods. + * The main public entry point are the + * the {@link #recordSuccessfulDeployment(File)}, + * {@link #recordFailedDeployment(File)}, {@link #recordSuccessfulUndeployment(File)}, and + * {@link #recordFailedUndeployment(File)} methods. *

    - * The client should invoke {@link shouldAttemptDeployment} when it has identified + * The client should invoke {@link #shouldAttemptDeployment(File)} when it has identified * a candidate file for deployment but before trying to deploy that file. This * retry manager will return whether the caller should attempt to deploy the file, * at least based on whether there has been a previous unsuccessful attempt to * deploy it and, if so, whether the file seems to be stable in size or not. *

    * When the caller actually tries to deploy a file, it must invoke - * {@link reportSuccessfulDeployment} or {@link reportFailedDeployment) + * {@link #recordSuccessfulDeployment(File)} or {@link #recordFailedDeployment(File)} * so that the retry manager keeps its information about the file up-to-date. * Similarly, when the caller tries to undeploy a file it must invoke - * {@link reportSuccessfulUndeployment} or {@link reportFailedUndeployment}. + * {@link #recordSuccessfulUndeployment(File)} or {@link #recordFailedUndeployment(File)}. *

    * Internally for each file that has failed to deploy the retry manager records * the file's size and the timestamp of the most recent failure and the timestamp at @@ -70,14 +70,14 @@ *

    * If AutoDeployer previously reported failures to deploy the file and the * file's size has been stable for its retry expiration time, then the - * {@link shouldAttemptDeployment} method returns true to trigger another attempt to + * {@link #shouldAttemptDeployment(File)} method returns true to trigger another attempt to * deploy the file. If the autodeployer reports another failed deployment * then the retry manager concludes that the file is not simply a slow-copying * file but is truly invalid. In that case * it throws an exception. *

    * Once the caller reports a successful deployment of a file by invoking - * {@link reportSuccessfulDeployment} the retry manager discards any record of + * {@link #recordSuccessfulDeployment(File)} the retry manager discards any record of * that file from its internal data structures. Similarly the retry manager * stops monitoring a file once the autodeployer has made an attempt - * successful or unsuccessful - to undeploy it. @@ -124,6 +124,7 @@ public class AutodeployRetryManager implements PostConstruct { @LogMessageInfo(message = "Could not convert configured timeout value of \"{0}\" to a number; using previous value of {1} second{1,choice,0#seconds|1#second|1 + * Interface defining a method for filtering out deployable compenets. * * @author vikas */ +public interface DirectoryScanner { -public interface DirectoryScanner{ + File[] getAllDeployableModules(File autodeployDir, boolean includeSubDir); - public File[] getAllDeployableModules(File autodeployDir, boolean includeSubDir); - public boolean hasNewDeployableEntity(File autodeployDir); - public File[] getAllFilesForUndeployment(File autodeployDir, boolean includeSubdir); - public void deployedEntity(File autodeployDir, File deployedEntity); - public void undeployedEntity(File autodeployDir, File undeployedEntity); + boolean hasNewDeployableEntity(File autodeployDir); + File[] getAllFilesForUndeployment(File autodeployDir, boolean includeSubdir); -} + void deployedEntity(File autodeployDir, File deployedEntity); + void undeployedEntity(File autodeployDir, File undeployedEntity); + +} diff --git a/nucleus/flashlight/framework/src/main/java/org/glassfish/flashlight/xml/StaxParser.java b/nucleus/flashlight/framework/src/main/java/org/glassfish/flashlight/xml/StaxParser.java index e6b62a8e4d8..141888451f5 100644 --- a/nucleus/flashlight/framework/src/main/java/org/glassfish/flashlight/xml/StaxParser.java +++ b/nucleus/flashlight/framework/src/main/java/org/glassfish/flashlight/xml/StaxParser.java @@ -66,7 +66,7 @@ public StaxParser(InputStream is) throws XMLStreamException { * Exception if the end of the document was reached * @return * @throws XMLStreamException - * @throws xml.StaxParser.EndDocumentException if the end of the document is here + * @throws EndDocumentException if the end of the document is here */ protected int next() throws XMLStreamException, EndDocumentException { int event = parser.next(); @@ -83,7 +83,7 @@ protected int next() throws XMLStreamException, EndDocumentException { * sub-element with the same name as an outer element * * @param name the Element to skip to - * @throws javax.xml.stream.XMLStreamException + * @throws XMLStreamException */ protected void skipTo(String name) throws XMLStreamException, EndDocumentException { while (true) { @@ -101,7 +101,7 @@ protected void skipTo(String name) throws XMLStreamException, EndDocumentExcepti /** * The cursor must be pointing at a START_ELEMENT. Returns all attributes * in a Map - * @return Map of all attributes + * @return {@code Map} of all attributes * @throws IllegalStateException if the cursor is not pointing at a START_ELEMENT */ diff --git a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/Attribute.java b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/Attribute.java index cb4b0bb7882..b88c706f369 100644 --- a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/Attribute.java +++ b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/Attribute.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Contributors to the Eclipse Foundation + * Copyright (c) 2023, 2026 Contributors to the Eclipse Foundation * Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -97,14 +97,16 @@ */ String defaultValue() default "\u0000"; - /** Specifies the data type. It should be the fully qualified name of - * the class that identifies the real data type. For attributes that - * are of type defined by basic Java primitives (or wrappers), there is - * no need to specify this field. The default value is derived from - * method/field declaration. + + /** + * Specifies the data type. It should be the fully qualified name of + * the class that identifies the real data type. For attributes that + * are of type defined by basic Java primitives (or wrappers), there is + * no need to specify this field. The default value is derived from + * method/field declaration. + * + * @return String specifying the name of the data type for the values of this attribute * @see DataType - * @return String specifying the name of the data type for the values of this - * attribute */ Class dataType() default String.class; } diff --git a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/ConfigSupport.java b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/ConfigSupport.java index a855bbec6c2..252c1d93e9c 100644 --- a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/ConfigSupport.java +++ b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/ConfigSupport.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2024 Contributors to the Eclipse Foundation + * Copyright (c) 2023, 2026 Contributors to the Eclipse Foundation * Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -400,11 +400,13 @@ public void apply(Map> mapOfChanges) throws Tran } } + /** * Returns the list of sub-elements supported by a ConfigBean + * * @return array of classes reprensenting the sub elements of a particular - * @throws ClassNotFoundException for severe errors with the model associated - * with the passed config bean. + * @throws ClassNotFoundException for severe errors with the model associated with the passed + * config bean. */ public static Class[] getSubElementsTypes(ConfigBean bean) throws ClassNotFoundException { diff --git a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/InjectionResolver.java b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/InjectionResolver.java index d1f09149c74..778789576ca 100644 --- a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/InjectionResolver.java +++ b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/InjectionResolver.java @@ -17,13 +17,15 @@ package org.jvnet.hk2.config; +import jakarta.inject.Inject; + import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; /** * Implementation of this abstract class are handling injection resolution - * for a particular injection annotation {@see Inject} + * for a particular injection annotation {@link Inject} * * Injection targets are identified by the generic parameter and the constructor * of this class. Potential injection targets are fields and methods of the @@ -69,7 +71,7 @@ public Method getSetterMethod(Method annotated, U annotation) { * @param annotated is the annotated java element {@link java.lang.reflect.Method} * or {@link java.lang.reflect.Field} * @param annotation the injection metadata - * @return true if the {@see getValue()} can return null without generating a + * @return true if the getValue() can return null without generating a * faulty injection operation */ public boolean isOptional(AnnotatedElement annotated, U annotation) { diff --git a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/OnDeleteCascade.java b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/OnDeleteCascade.java index f7bbe951a17..5bb65bfade2 100644 --- a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/OnDeleteCascade.java +++ b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/OnDeleteCascade.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Contributors to the Eclipse Foundation + * Copyright (c) 2023, 2026 Contributors to the Eclipse Foundation * Copyright (c) 2007, 2018 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the @@ -25,18 +25,18 @@ * Usage: * {@snippet : * class ExampleDocument extends DomDocument { - * @Override - * public ConfigBean make(final ServiceLocator serviceLocator, XMLStreamReader xmlStreamReader, - * ConfigBean dom, ConfigModel configModel) { - * ConfigBean configBean = new ConfigBean(habitat,this, dom, configModel, xmlStreamReader); - * configBean.addInterceptor(Object.class, new OnDeleteCascade()); - * return configBean; - * } + * + * @Override + * public ConfigBean make(final ServiceLocator serviceLocator, XMLStreamReader xmlStreamReader, ConfigBean dom, + * ConfigModel configModel) { + * ConfigBean configBean = new ConfigBean(habitat, this, dom, configModel, xmlStreamReader); + * configBean.addInterceptor(Object.class, new OnDeleteCascade()); + * return configBean; + * } * } * } * * @author Andriy Zhdanov - * */ public class OnDeleteCascade implements ConfigBeanInterceptor { diff --git a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/tiger/Types.java b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/tiger/Types.java index 1f6122938b1..a87d0998033 100644 --- a/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/tiger/Types.java +++ b/nucleus/hk2-config-generator/src/main/java/org/jvnet/hk2/config/tiger/Types.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Contributors to the Eclipse Foundation + * Copyright (c) 2023, 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 diff --git a/nucleus/parent/pom.xml b/nucleus/parent/pom.xml index ae21dd71efe..9003b3b8a1f 100644 --- a/nucleus/parent/pom.xml +++ b/nucleus/parent/pom.xml @@ -74,31 +74,6 @@ IssueTracker https://github.com/eclipse-ee4j/glassfish/issues - - - - ossrh - Disabled Sonatype Nexus - http://localhost - - false - - - false - - - - ossrh - Disabled Sonatype Nexus - http://localhost - - false - - - false - - - central @@ -118,17 +93,6 @@ false - - central-portal-snapshots - https://central.sonatype.com/repository/maven-snapshots - - false - - - true - fail - - @@ -162,7 +126,7 @@ 2.0.1.MR 4.0.1 - 4.0.1 + ${hk2.version} 5.0.0.Alpha3 @@ -278,7 +242,7 @@ 1.10 - 1.0.21 + 1.0.22 true @@ -292,10 +256,11 @@ 2.7.7 2.7.8 4.13.2 - 1.10.16 - 1.10.2 + + 1.10.17 + 1.10.17 2.21.3 - 2.21 + 2.21 1.7.3 1.0-2 1.5.5 @@ -305,7 +270,7 @@ 1.5.3 5.6.0 - 6.0.2 + 6.0.3 1.37 3.0.0 2.0.17 @@ -350,11 +315,6 @@ INFO true appserver/distributions/glassfish/target/stage/glassfish9/glassfish - - - false - - published @@ -439,34 +399,6 @@ ${project.version} - - - org.glassfish.grizzly - grizzly-http-servlet - ${grizzly.version} - - - org.glassfish.jersey.containers - jersey-container-grizzly2-http - ${jersey.version} - - - org.glassfish.jersey.containers - jersey-container-servlet - ${jersey.version} - - - org.glassfish.jersey.inject - jersey-hk2 - ${jersey.version} - - - org.glassfish.jersey.media - jersey-media-json-jackson - ${jersey.version} - - - jakarta.xml.bind @@ -756,7 +688,7 @@ org.jline jline - 3.30.6 + 3.30.9 @@ -801,27 +733,11 @@ ${asm.version} - - - net.java.dev.jna - jna - ${jna.version} - - - javax.xml.stream stax-api ${stax-api.version} - org.codehaus.jettison @@ -843,7 +759,7 @@ com.fasterxml.jackson.core jackson-annotations - ${jackson.version2} + ${jackson-annotations.version} com.fasterxml.jackson.core @@ -1018,13 +934,8 @@ org.glassfish.external - ant - ${ant.external.version} - - - org.apache.ant - ant-launcher - 1.10.16 + ant-osgi + ${ant-osgi.version} com.github.mwiede @@ -1036,6 +947,11 @@ logging-annotation-processor ${logging-annotation-processor.version} + + net.java.dev.jna + jna + ${jna.version} + @@ -1081,6 +997,13 @@ maven-antrun-plugin 3.2.0 + + + org.glassfish.external + ant-osgi + ${ant-osgi.version} + + org.apache.felix @@ -1237,7 +1160,7 @@ maven-surefire-report-plugin - 3.5.5 + ${surefire.version} maven-checkstyle-plugin @@ -1276,7 +1199,7 @@ com.puppycrawl.tools checkstyle - 13.3.0 + 13.4.0 @@ -1546,187 +1469,885 @@ - org.glassfish.external - ant + org.glassfish.hk2 + osgi-resource-locator regex - 3.2-b.. + 2.5.0-b.. regex - 10.0-b.. + 2.4.0 + + - org.glassfish.hk2 - osgi-resource-locator + jakarta.activation + + range + [2.2.0,) + regex - 2.5.0-b.. + .*-M.* + + + + + + jakarta.annotation + jakarta.annotation-api + + + range + [3.1.0,) regex - 2.4.0 + .*-M.* + - org.glassfish.external - ant + jakarta.authentication + jakarta.authentication-api range - [2,) + [3.2.0,) + + + regex + .*-M.* + - org.slf4j + jakarta.authorization + jakarta.authorization-api + + range + [3.1.0,) + regex - .*-.* + .*-M.* - - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.7.0 - - true - - - - injected-nexus-deploy - none - - - - - org.sonatype.central - central-publishing-maven-plugin - 0.10.0 - true - - ${release.autopublish} - https://central.sonatype.com/repository/maven-snapshots - Eclipse GlassFish ${project.version} - central - ${release.waitUntil} - - - - - - - maven-enforcer-plugin - - - enforce-maven - - enforce - - - - - 3.9.0 - - - - - - + + jakarta.security.enterprise + jakarta.security.enterprise-api + + + range + [4.1.0,) + + + regex + .*-M.* + + + - - org.codehaus.mojo - build-helper-maven-plugin - - - add-resource - generate-resources - - add-resource - - - - - src/main/manpages - - - - - - add-legal-resource - generate-resources - - add-resource - - - - - ${legal.doc.source} - META-INF - - - - - - + + jakarta.data + jakarta.data-api + + + range + [1.1.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + - - org.glassfish.build - glassfishbuild-maven-plugin - + + jakarta.enterprise + jakarta.enterprise.cdi-el-api + + + range + [4.2.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + - - maven-assembly-plugin - false - - - common-resources - generate-resources - - single - - - - src/main/assembly/resources.xml - - - - - + + jakarta.el + jakarta.el-api + + + range + [6.1.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + - - - maven-dependency-plugin - - - unpack-resource - generate-resources - - unpack - - - - - org.glassfish.main - nucleus-parent - ${project.version} - resources - zip - ${project.build.commonResourcesDirectory} + + jakarta.nosql + jakarta.nosql-api + + + range + [1.1.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + + + + jakarta.servlet + jakarta.servlet-api + + + range + [6.2.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + + + + jakarta.servlet.jsp + jakarta.servlet.jsp-api + + + range + [4.1.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + + + + jakarta.servlet.jsp.jstl + jakarta.servlet.jsp.jstl-api + + + range + [3.1.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + + + + jakarta.validation + + + range + [3.2.0,) + + + regex + .*-M.* + + + + + + jakarta.faces + + + range + [5.0,) + + + regex + .*-M.* + + + + + + jakarta.enterprise.concurrent + + + range + [3.2,) + + + regex + .*-M.* + + + regex + .*RC.* + + + + + + jakarta.interceptor + + + range + [2.3,) + + + regex + .*-M.* + + + regex + .*RC.* + + + + + + jakarta.websocket + + + range + [2.3,) + + + regex + .*-M.* + + + + + + jakarta.persistence + + + range + [3.3,) + + + regex + .*-M.* + + + regex + .*-B.* + + + + + + jakarta.platform + + + range + [12.0,) + + + regex + .*-M.* + + + + + + jakarta.enterprise + jakarta.enterprise.cdi-api + + + range + [4.2,) + + + regex + .*-M.* + + + regex + .*CR.* + + + regex + .*RC.* + + + regex + .*Beta.* + + + regex + .*Alpha.* + + + + + + jakarta.enterprise + jakarta.enterprise.lang-model + + + range + [4.2,) + + + regex + .*-M.* + + + regex + .*CR.* + + + regex + .*RC.* + + + regex + .*Beta.* + + + regex + .*Alpha.* + + + + + + jakarta.ws.rs + + + range + [4.1.0,) + + + regex + .*-M.* + + + + + + jakarta.mail + + + range + [2.3,) + + + regex + .*M.* + + + + + + jakarta.mvc + + + range + [3.1,) + + + regex + .*M.* + + + + + + org.glassfish + jakarta.enterprise.concurrent + + + range + [3.2.0,) + + + regex + .*-M.* + + + + + + org.glassfish.jsftemplating + + + range + [4.1.0,) + + + regex + .*-M.* + + + + + + org.glassfish.grizzly + + + range + [4.2.0,) + + + regex + .*-M.* + + + regex + .*payara.* + + + + + + org.glassfish.hk2 + + + range + [4.1.0,) + + + regex + .*-M.* + + + + + + org.glassfish.jersey + + + range + [4.1,) + + + regex + .*-M.* + + + + + + org.glassfish.expressly + + + range + [6.1,) + + + regex + .*-M.* + + + + + + org.glassfish.tyrus + + + range + [2.3,) + + + regex + .*-M.* + + + + + + org.glassfish.wasp + + + range + [4.1,) + + + regex + .*-M.* + + + + + + org.glassfish.soteria + + + range + [4.1,) + + + regex + .*-M.* + + + + + + org.glassfish.epicyro + + + range + [3.2,) + + + regex + .*-M.* + + + + + + org.glassfish.exousia + + + range + [3.1,) + + + regex + .*-M.* + + + + + + org.glassfish + jakarta.faces + + + range + [4.2,) + + + regex + .*-M.* + + + + + + org.glassfish.main + + + range + [9.0,) + + + regex + .*-M.* + + + + + + org.eclipse.angus + angus-activation + + + range + [2.2.0,) + + + regex + .*-M.* + + + + + + org.eclipse.microprofile.jwt + microprofile-jwt-auth-api + + + range + [2.3,) + + + regex + .*-.* + + + + + + org.eclipse.angus + angus-mail + + + range + [2.2.0,) + + + regex + .*-M.* + + + + + + org.hibernate.validator + + + range + [10.0,) + + + regex + .*-M.* + + + regex + .*CR.* + + + regex + .*Beta.* + + + regex + .*Alpha.* + + + + + + org.jboss.weld + + + range + [7.0,) + + + regex + .*-M.* + + + regex + .*CR.* + + + regex + .*Beta.* + + + regex + .*Alpha.* + + + + + + io.helidon.microprofile.config + + + range + [5.0,) + + + regex + .*-M.* + + + regex + .*-RC.* + + + regex + .*-BETA.* + + + regex + .*-ALPHA.* + + + + + + org.omnifaces + microprofile-jwt-auth + + + range + [3.1,) + + + regex + .*-M.* + + + + + + org.slf4j + + + regex + .*-.* + + + + + + + + + + + + + + + maven-enforcer-plugin + + + enforce-maven + + enforce + + + + + 3.9.0 + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-resource + generate-resources + + add-resource + + + + + src/main/manpages + + + + + + add-legal-resource + generate-resources + + add-resource + + + + + ${legal.doc.source} + META-INF + + + + + + + + + org.glassfish.build + glassfishbuild-maven-plugin + + + + maven-assembly-plugin + false + + + common-resources + generate-resources + + single + + + + src/main/assembly/resources.xml + + + + + + + + + maven-dependency-plugin + + + unpack-resource + generate-resources + + unpack + + + + + org.glassfish.main + nucleus-parent + ${project.version} + resources + zip + ${project.build.commonResourcesDirectory} @@ -1866,65 +2487,10 @@ true false + Eclipse GlassFish + false + published - - - - maven-source-plugin - - - attach-sources - - jar-no-fork - - - - - - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.cyclonedx - cyclonedx-maven-plugin - - - false - - - - package - - makeAggregateBom - - - - - - maven-gpg-plugin - - - sign-artifacts - verify - - sign - - - - - - org.sonatype.central - central-publishing-maven-plugin - - - fast diff --git a/nucleus/security/core/pom.xml b/nucleus/security/core/pom.xml index 58e1f616925..c7b5be83045 100644 --- a/nucleus/security/core/pom.xml +++ b/nucleus/security/core/pom.xml @@ -1,7 +1,7 @@