Return-Path: Delivered-To: apmail-db-jdo-commits-archive@www.apache.org Received: (qmail 82675 invoked from network); 19 Mar 2005 05:00:49 -0000 Received: from hermes.apache.org (HELO mail.apache.org) (209.237.227.199) by minotaur.apache.org with SMTP; 19 Mar 2005 05:00:49 -0000 Received: (qmail 83480 invoked by uid 500); 19 Mar 2005 05:00:49 -0000 Mailing-List: contact jdo-commits-help@db.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: jdo-dev@db.apache.org Delivered-To: mailing list jdo-commits@db.apache.org Delivered-To: moderator for jdo-commits@db.apache.org Received: (qmail 82961 invoked by uid 99); 19 Mar 2005 01:06:12 -0000 X-ASF-Spam-Status: No, hits=-9.8 required=10.0 tests=ALL_TRUSTED,NO_REAL_NAME X-Spam-Check-By: apache.org Message-ID: <20050319010608.28185.qmail@minotaur.apache.org> Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable X-Mailer: svnmailer-1.0.0-dev Date: Sat, 19 Mar 2005 01:06:07 -0000 Subject: svn commit: r158176 [40/79] - in incubator/jdo/trunk/ri11: ./ src/ src/conf/ src/java/ src/java/org/ src/java/org/apache/ src/java/org/apache/jdo/ src/java/org/apache/jdo/ejb/ src/java/org/apache/jdo/enhancer/ src/java/org/apache/jdo/impl/ src/java/org/apache/jdo/impl/enhancer/ src/java/org/apache/jdo/impl/enhancer/classfile/ src/java/org/apache/jdo/impl/enhancer/core/ src/java/org/apache/jdo/impl/enhancer/generator/ src/java/org/apache/jdo/impl/enhancer/meta/ src/java/org/apache/jdo/impl/enhancer/meta/model/ src/java/org/apache/jdo/impl/enhancer/meta/prop/ src/java/org/apache/jdo/impl/enhancer/meta/util/ src/java/org/apache/jdo/impl/enhancer/util/ src/java/org/apache/jdo/impl/fostore/ src/java/org/apache/jdo/impl/jdoql/ src/java/org/apache/jdo/impl/jdoql/jdoqlc/ src/java/org/apache/jdo/impl/jdoql/scope/ src/java/org/apache/jdo/impl/jdoql/tree/ src/java/org/apache/jdo/impl/model/ src/java/org/apache/jdo/impl/model/java/ src/java/org/apache/jdo/impl/model/java/runtime/ src/java/org/apache/jdo/impl/model/jdo/ src/java/org/apache/jdo/impl/model/jdo/caching/ src/java/org/apache/jdo/impl/model/jdo/util/ src/java/org/apache/jdo/impl/model/jdo/xml/ src/java/org/apache/jdo/impl/pm/ src/java/org/apache/jdo/impl/sco/ src/java/org/apache/jdo/impl/state/ src/java/org/apache/jdo/jdoql/ src/java/org/apache/jdo/jdoql/tree/ src/java/org/apache/jdo/model/ src/java/org/apache/jdo/model/java/ src/java/org/apache/jdo/model/jdo/ src/java/org/apache/jdo/pm/ src/java/org/apache/jdo/sco/ src/java/org/apache/jdo/state/ src/java/org/apache/jdo/store/ src/java/org/apache/jdo/util/ test/ test/conf/ test/enhancer/ test/enhancer/sempdept/ test/enhancer/sempdept/src/ test/enhancer/sempdept/src/empdept/ test/fsuid2/ test/fsuid2/org/ test/fsuid2/org/apache/ test/fsuid2/org/apache/jdo/ test/fsuid2/org/apache/jdo/pc/ test/java/ test/java/org/ test/java/org/apache/ test/java/org/apache/jdo/ test/java/org/apache/jdo/impl/ test/java/org/apache/jdo/impl/fostore/ test/java/org/apache/jdo/pc/ test/java/org/apache/jdo/pc/appid/ test/java/org/apache/jdo/pc/empdept/ test/java/org/apache/jdo/pc/serializable/ test/java/org/apache/jdo/pc/xempdept/ test/java/org/apache/jdo/test/ test/java/org/apache/jdo/test/query/ test/java/org/apache/jdo/test/util/ test/jdo/ test/jdo/org/ test/jdo/org/apache/ test/jdo/org/apache/jdo/ test/jdo/org/apache/jdo/pc/ test/jdo/org/apache/jdo/pc/appid/ test/jdo/org/apache/jdo/pc/empdept/ test/jdo/org/apache/jdo/pc/serializable/ test/jdo/org/apache/jdo/pc/xempdept/ xdocs/ To: jdo-commits@db.apache.org From: mbo@apache.org X-Virus-Checked: Checked X-Spam-Rating: minotaur.apache.org 1.6.2 0/1000/N Added: incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/= JDOHandlerImpl.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/src/java/org/ap= ache/jdo/impl/model/jdo/xml/JDOHandlerImpl.java?view=3Dauto&rev=3D158176 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/JDO= HandlerImpl.java (added) +++ incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/JDO= HandlerImpl.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,629 @@ +/* + * Copyright 2005 The Apache Software Foundation. + *=20 + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at=20 + *=20 + * http://www.apache.org/licenses/LICENSE-2.0 + *=20 + * Unless required by applicable law or agreed to in writing, software=20 + * distributed under the License is distributed on an "AS IS" BASIS,=20 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= .=20 + * See the License for the specific language governing permissions and=20 + * limitations under the License. + */ + +/* + * File: JDOHandlerImpl.java + * Date: July 3, 2001 2:16 PM + * + * @author michael + * @version generated by FFJ XML module + */ +package org.apache.jdo.impl.model.jdo.xml; + +import java.util.*; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.jdo.impl.model.jdo.JDOClassImplDynamic; +import org.apache.jdo.model.ModelException; +import org.apache.jdo.model.jdo.JDOArray; +import org.apache.jdo.model.jdo.JDOClass; +import org.apache.jdo.model.jdo.JDOCollection; +import org.apache.jdo.model.jdo.JDOElement; +import org.apache.jdo.model.jdo.JDOExtension; +import org.apache.jdo.model.jdo.JDOField; +import org.apache.jdo.model.jdo.JDOIdentityType; +import org.apache.jdo.model.jdo.JDOMap; +import org.apache.jdo.model.jdo.JDOModel; +import org.apache.jdo.model.jdo.JDOPackage; +import org.apache.jdo.model.jdo.NullValueTreatment; +import org.apache.jdo.model.jdo.PersistenceModifier; +import org.apache.jdo.util.I18NHelper; +import org.xml.sax.*; + +/** + *=20 + * TBD: + *
    + *
  • Reading persistence capable superclass entry: check already existi= ng=20 + * superclass entry for consistency + *
  • Only populate requested class info, not the entire .jdo file + */ +public class JDOHandlerImpl=20 + implements JDOHandler=20 +{ + /** */ + private final JDOModel model; + =20 + /** */ + private final Stack context; + =20 + /**=20 + * Flag indicating that the current entries should no be loaded, + * because JDO metadata has been loaded before for the current + * persistence capable class. + */ + private boolean skipXMLElements; + + /** */ + private final Collection handledJDOClasses; + + /** I18N support. */ + private static final I18NHelper msg =3D I18NHelper.getInstance( + "org.apache.jdo.impl.model.jdo.Bundle",=20 + JDOHandlerImpl.class.getClassLoader()); //NOI18N + + /** Logger */ + private static Log logger =3D LogFactory.getFactory().getInstance( + "org.apache.jdo.impl.model.jdo.xml"); // NOI18N + =20 + /** + *=20 + */ + public JDOHandlerImpl (JDOModel model)=20 + { + this.model =3D model; + this.context =3D new Stack(); + this.skipXMLElements =3D false; + this.handledJDOClasses =3D new HashSet(); + } + =20 + /** + *=20 + */ + public void start_jdo(final Attributes meta)=20 + { + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // push current JDOModel on context stack + context.push(model); + } + =20 + /** + *=20 + */ + public void end_jdo()=20 + { + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOModel fom context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_package(final Attributes meta)=20 + throws SAXException=20 + { + boolean trace =3D logger.isTraceEnabled(); + if (trace)=20 + logger.trace(" "); //NOI18N + JDOPackage jdoPackage =3D null; + try { + // get JDOModel from context stack + JDOModel model =3D (JDOModel)context.peek(); + String packageName =3D meta.getValue("", "name"); //NOI18N + if ((packageName =3D=3D null) || packageName.length() =3D=3D 0) + packageName =3D ""; //NOI18N + if (trace) + logger.trace(" name =3D " + packageName); //NOI18N + jdoPackage =3D model.createJDOPackage(packageName); + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_package:", e); //NOI18N + throw e; + } + =20 + // push current JDOPackage on context stack + context.push(jdoPackage); + } + =20 + /** + *=20 + */ + public void end_package()=20 + { + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOPackage fom context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_class(final Attributes meta) =20 + throws SAXException=20 + { + boolean trace =3D logger.isTraceEnabled(); + if (trace) + logger.trace(" "); //NOI18N + JDOClass jdoClass =3D null; + try { + // get JDOPackage from context stack + //String packageName =3D (String)context.peek(); + JDOPackage jdoPackage =3D (JDOPackage)context.peek(); + String packageName =3D jdoPackage.getName(); + String className =3D meta.getValue("", "name"); //NOI18N + if ((packageName !=3D null) && (packageName.length() > 0)) + className =3D packageName + "." + className; //NOI18N + jdoClass =3D model.createJDOClass(className, false); + skipXMLElements =3D isXMLProcessed(jdoClass); + if (skipXMLElements) { + if (trace) + logger.trace( + " JDO metadata already loaded for class " + //NOI= 18N + className + ", skipping class element"); //NOI18N + return; + } + for ( int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("name".equals(name)) { //NOI18N + // name is already set during create =3D> do nothing=20 + } + else if ("identity-type".equals(name)) { //NOI18N + jdoClass.setIdentityType( + JDOIdentityType.toJDOIdentityType(value)); + } + else if ("objectid-class".equals(name)) { //NOI18N + jdoClass.setDeclaredObjectIdClassName(value); + } + else if ("requires-extent".equals(name)) { //NOI18N + jdoClass.setRequiresExtent( + Boolean.valueOf(value).booleanValue()); + } + else if ("persistence-capable-superclass".equals(name)) { = //NOI18N + // Do not overwrite existing entry + // TBD check old and new entry for consistency + if (jdoClass.getPersistenceCapableSuperclassName() =3D= =3D null) { + jdoClass.setPersistenceCapableSuperclassName(value= ); + } + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //NOI18N + name, value));=20 + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_class:", e); //= NOI18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_class:", e); //NOI18N + throw e; + } + // store current jdoClass in handledJDOClasses + handledJDOClasses.add(jdoClass); + + // push current JDOClass object on context stack + context.push(jdoClass); + } + =20 + /** + *=20 + */ + public void end_class() =20 + { + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + if (skipXMLElements) { + // set flag to false to allow next class entry to be populated + skipXMLElements =3D false; + } + else { + // remove JDOClass fom context stack + JDOClass jdoClass =3D (JDOClass)context.pop(); + // set jdoClass' xmlProcessed flag + setXMLProcessed(jdoClass); + } + } + =20 + /** + *=20 + */ + public void start_field(final Attributes meta)=20 + throws SAXException=20 + { + if (skipXMLElements)=20 + return; + boolean trace =3D logger.isTraceEnabled(); + if (trace) + logger.trace(" "); //NOI18N + JDOField jdoField =3D null; + try { + // get the current JDOClass from context stack + JDOClass jdoClass =3D (JDOClass)context.peek(); + String fieldName =3D meta.getValue("", "name"); //NOI18N + jdoField =3D jdoClass.createJDOField(fieldName); + for (int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("name".equals(name)) { //NOI18N + // name is already set during create =3D> do nothing=20 + } + else if ("persistence-modifier".equals(name)) { //NOI18N + int modifier =3D=20 + PersistenceModifier.toPersistenceModifier(value); + jdoField.setPersistenceModifier(modifier); + } + else if ("primary-key".equals(name)) { //NOI18N + jdoField.setPrimaryKey( + Boolean.valueOf(value).booleanValue()); + } + else if ("null-value".equals(name)) { //NOI18N + jdoField.setNullValueTreatment( + NullValueTreatment.toNullValueTreatment(value)); + } + else if ("default-fetch-group".equals(name)) { //NOI18N + jdoField.setDefaultFetchGroup( + Boolean.valueOf(value).booleanValue()); + } + else if ("embedded".equals(name)) { //NOI18N + jdoField.setEmbedded( + Boolean.valueOf(value).booleanValue()); + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //NOI18N + name, value));=20 + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_field:", e); //= NOI18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_field:", e); //NOI18N + throw e; + } + =20 + // push current JDOField on context stack + context.push(jdoField); + } + =20 + /** + *=20 + */ + public void end_field() =20 + { + if (skipXMLElements) + return; + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOField from context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_collection(final Attributes meta) =20 + throws SAXException=20 + { + if (skipXMLElements) + return; + =20 + boolean trace =3D logger.isTraceEnabled(); + if (trace) + logger.trace(" "); //NOI18N + JDOCollection jdoCollection =3D null; + try { + // get the current JDOField from context stack + JDOField jdoField =3D (JDOField)context.peek(); + jdoCollection =3D jdoField.createJDOCollection(); + for (int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("element-type".equals(name)) { //NOI18N + jdoCollection.setElementTypeName(value); + } + else if ("embedded-element".equals(name)) { //NOI18N + jdoCollection.setEmbeddedElement( + Boolean.valueOf(value).booleanValue()); + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //= NOI18N + name, value));=20 + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_collection:", e= ); //NOI18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_collection:", e); //NOI= 18N + throw e; + } + =20 + // push current JDOCollection on context stack + context.push(jdoCollection); + } + =20 + /** + *=20 + */ + public void end_collection() =20 + { + if (skipXMLElements)=20 + return; + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOCollection from context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_array(final Attributes meta)=20 + throws SAXException=20 + { + if (skipXMLElements) + return; + + boolean trace =3D logger.isTraceEnabled(); + if (trace) + logger.trace(" "); //NOI18N + JDOArray jdoArray =3D null; + try { + // get the current JDOField from context stack + JDOField jdoField =3D (JDOField)context.peek(); + jdoArray =3D jdoField.createJDOArray(); + for (int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("embedded-element".equals(name)) { //NOI18N + jdoArray.setEmbeddedElement( + Boolean.valueOf(value).booleanValue()); + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //NOI18N + name, value));=20 + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_array:", e); //= NOI18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_array:", e); //NOI18N + throw e; + } + =20 + // push current JDOArray on context stack + context.push(jdoArray); + } + =20 + /** + *=20 + */ + public void end_array()=20 + { + if (skipXMLElements) + return; + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOArray from context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_map(final Attributes meta)=20 + throws SAXException=20 + { + if (skipXMLElements) + return; + boolean trace =3D logger.isTraceEnabled(); + if (trace) + logger.trace(" "); //NOI18N + JDOMap jdoMap =3D null; + try { + // get the current JDOField from context stack + JDOField jdoField =3D (JDOField)context.peek(); + jdoMap =3D jdoField.createJDOMap(); + for (int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("key-type".equals(name)) { //NOI18N + jdoMap.setKeyTypeName(value); + } + else if ("embedded-key".equals(name)) { //NOI18N + jdoMap.setEmbeddedKey( + Boolean.valueOf(value).booleanValue()); + } + else if ("value-type".equals(name)) { //NOI18N + jdoMap.setValueTypeName(value); + } + else if ("embedded-value".equals(name)) { //NOI18N + jdoMap.setEmbeddedValue( + Boolean.valueOf(value).booleanValue()); + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //NOI18N + name, value));=20 + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_map:", e); //NO= I18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_map:", e); //NOI18N + throw e; + } + =20 + // push current JDOMap on context stack + context.push(jdoMap); + } + =20 + /** + *=20 + */ + public void end_map() =20 + { + if (skipXMLElements) + return; + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // remove JDOMap from context stack + context.pop(); + } + =20 + /** + *=20 + */ + public void start_extension(final Attributes meta)=20 + throws SAXException=20 + { + if (skipXMLElements) + return; + boolean trace =3D logger.isTraceEnabled(); + + if (trace) + logger.trace(" "); //NOI18N + JDOExtension jdoExtension =3D null; + try { + // get the current JDOElement from context stack + JDOElement jdoElement =3D (JDOElement)context.peek(); + jdoExtension =3D jdoElement.createJDOExtension(); + for ( int i =3D 0; i < meta.getLength(); i++ ) { + String name =3D meta.getLocalName(i); + String value =3D meta.getValue(i); + =20 + if (trace) + logger.trace(" " + name + " =3D " + value); //NOI18N + if ("vendor-name".equals(name)) { //NOI18N + jdoExtension.setVendorName(value); + } + else if ("key".equals(name)) { //NOI18N + jdoExtension.setKey(value); + } + else if ("value".equals(name)) { //NOI18N + jdoExtension.setValue(value); + } + else { + SAXException e =3D new SAXException( + msg.msg("EXC_UnknownAttribute", "", //N= OI18N + name, value)); + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_extension:", e)= ; //NOI18N + throw e; + } + } + } + catch (ModelException ex) { + SAXException e =3D=20 + new SAXException(msg.msg("EXC_ModelException"), ex); //NOI= 18N + if (trace) + logger.trace("Throwing exception in " + //NOI18N + "JDOHandlerImpl.start_extension:", e); //NOI1= 8N + throw e; + } + } + =20 + /** + *=20 + */ + public void end_extension() =20 + { + if (skipXMLElements) + return; + if (logger.isTraceEnabled())=20 + logger.trace(" "); //NOI18N + // start did not push anything =3D> do nothing + } + =20 + /** + * + */ + public Collection handledJDOClasses() + { + return handledJDOClasses; + } + + /** */ + private boolean isXMLProcessed(JDOClass jdoClass) { + if (jdoClass instanceof JDOClassImplDynamic) + return ((JDOClassImplDynamic)jdoClass).isXMLProcessed(); + return false; + } + + /** */ + private void setXMLProcessed(JDOClass jdoClass) { + if (jdoClass instanceof JDOClassImplDynamic) + ((JDOClassImplDynamic)jdoClass).setXMLProcessed(); + } + =20 +} Added: incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/= JDOParser.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/src/java/org/ap= ache/jdo/impl/model/jdo/xml/JDOParser.java?view=3Dauto&rev=3D158176 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/JDO= Parser.java (added) +++ incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/JDO= Parser.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,315 @@ +/* + * Copyright 2005 The Apache Software Foundation. + *=20 + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at=20 + *=20 + * http://www.apache.org/licenses/LICENSE-2.0 + *=20 + * Unless required by applicable law or agreed to in writing, software=20 + * distributed under the License is distributed on an "AS IS" BASIS,=20 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= .=20 + * See the License for the specific language governing permissions and=20 + * limitations under the License. + */ + +/* + * File: JDOParser.java + * Date: July 3, 2001 2:16 PM + * + * @author michael + * @version generated by FFJ XML module + */ +package org.apache.jdo.impl.model.jdo.xml; + +import java.io.*; +import java.security.AccessController; +import java.security.PrivilegedAction; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.jdo.model.jdo.JDOModel; +import org.apache.jdo.util.I18NHelper; +import org.xml.sax.*; +import org.xml.sax.helpers.*; + +import javax.jdo.JDOFatalInternalException; + + +/** + * The class reads XML documents according to specified DTD and + * translates all related events into JDOHandler events. + *

    Usage sample: + *

    + *    JDOParser parser =3D new JDOParser(...);
    + *    parser.parse(new InputSource("..."));
    + * 
    + *

    Warning: the class is machine generated. DO NOT MODIFY

    + */ +public class JDOParser=20 + implements ContentHandler { + =20 + /** I18N support. */ + private static final I18NHelper msg =3D I18NHelper.getInstance( + "org.apache.jdo.impl.model.jdo.Bundle", JDOParser.class.getClassLo= ader()); //NOI18N + + private StringBuffer buffer; + =20 + private JDOHandler handler; + =20 + private java.util.Stack context; + =20 + public JDOParser(final JDOHandler handler)=20 + { + this.handler =3D handler; + buffer =3D new StringBuffer(111); + context =3D new java.util.Stack(); + } + =20 + public void setDocumentLocator(Locator locator)=20 + { + } + =20 + public void startDocument() throws SAXException=20 + { + } + =20 + public void endDocument() throws SAXException=20 + { + } + =20 + public void startElement(String ns, String name, String qname, Attribu= tes attrs)=20 + throws SAXException=20 + { + dispatch(true); + context.push(new Object[] {qname, new org.xml.sax.helpers.Attribut= esImpl(attrs)}); + =20 + if ("package".equals(name)) { //NOI18N + handler.start_package(attrs); + } else if ("jdo".equals(name)) { //NOI18N + handler.start_jdo(attrs); + } else if ("class".equals(name)) { //NOI18N + handler.start_class(attrs); + } else if ("map".equals(name)) { //NOI18N + handler.start_map(attrs); + } else if ("field".equals(name)) { //NOI18N + handler.start_field(attrs); + } else if ("collection".equals(name)) { //NOI18N + handler.start_collection(attrs); + } else if ("extension".equals(name)) { //NOI18N + handler.start_extension(attrs); + } else if ("array".equals(name)) { //NOI18N + handler.start_array(attrs); + } + } + =20 + public void endElement(String ns, String name, String qname)=20 + throws SAXException=20 + { + dispatch(false); + context.pop(); + if ("package".equals(name)) { //NOI18N + handler.end_package(); + } else if ("jdo".equals(name)) { //NOI18N + handler.end_jdo(); + } else if ("class".equals(name)) { //NOI18N + handler.end_class(); + } else if ("map".equals(name)) { //NOI18N + handler.end_map(); + } else if ("field".equals(name)) { //NOI18N + handler.end_field(); + } else if ("collection".equals(name)) { //NOI18N + handler.end_collection(); + } else if ("extension".equals(name)) { //NOI18N + handler.end_extension(); + } else if ("array".equals(name)) { //NOI18N + handler.end_array(); + } + } + =20 + public void characters(char[] chars, int start, int len)=20 + throws SAXException=20 + { + buffer.append(chars, start, len); + } + =20 + public void ignorableWhitespace(char[] chars, int start, int len)=20 + throws SAXException=20 + { + } + =20 + public void processingInstruction(String target, String data)=20 + throws SAXException=20 + { + } + =20 + public void startPrefixMapping(final String prefix, final String uri)=20 + throws SAXException=20 + { + } + =20 + public void endPrefixMapping(final String prefix)=20 + throws SAXException=20 + { + } + =20 + public void skippedEntity(String name)=20 + throws SAXException=20 + { + } + =20 + private void dispatch(final boolean fireOnlyIfMixed)=20 + throws SAXException=20 + { + if (fireOnlyIfMixed && buffer.length() =3D=3D 0) + return; //skip it + =20 + Object[] ctx =3D (Object[]) context.peek(); + String here =3D (String) ctx[0]; + Attributes attrs =3D (Attributes) ctx[1]; + buffer.delete(0, buffer.length()); + } + =20 + /** + * The recognizer entry method taking an InputSource. + * @param input InputSource to be parsed. + * @throws java.io.IOException on I/O error. + * @throws SAXException propagated exception thrown by a DocumentHandl= er. + * @throws javax.xml.parsers.ParserConfigurationException a parser=20 + * satisfining requested configuration can not be created. + * @throws javax.xml.parsers.FactoryConfigurationError if the implemen= tation=20 + * can not be instantiated. + */ + public void parse(final InputSource input)=20 + throws SAXException, ParserConfigurationException, IOException=20 + { + parse(input, this); + } + =20 + /** + * The recognizer entry method taking a URL. + * @param url URL source to be parsed. + * @throws java.io.IOException on I/O error. + * @throws SAXException propagated exception thrown by a DocumentHandl= er. + * @throws javax.xml.parsers.ParserConfigurationException a parser=20 + * satisfining requested configuration can not be created. + * @throws javax.xml.parsers.FactoryConfigurationError if the implemen= tation=20 + * can not be instantiated. + */ + public void parse(final java.net.URL url)=20 + throws SAXException, ParserConfigurationException, IOException=20 + { + parse(new InputSource(url.toExternalForm()), this); + } + =20 + /** + * The recognizer entry method taking an Inputsource. + * @param input InputSource to be parsed. + * @throws java.io.IOException on I/O error. + * @throws SAXException propagated exception thrown by a DocumentHandl= er. + * @throws javax.xml.parsers.ParserConfigurationException a parser=20 + * satisfining requested configuration can not be created. + * @throws javax.xml.parsers.FactoryConfigurationError if the implemen= tation=20 + * can not be instantiated. + */ + public static void parse(final InputSource input, final JDOHandler han= dler)=20 + throws SAXException, ParserConfigurationException, IOException=20 + { + parse(input, new JDOParser(handler)); + } + =20 + /** + * The recognizer entry method taking a URL. + * @param url URL source to be parsed. + * @throws java.io.IOException on I/O error. + * @throws SAXException propagated exception thrown by a DocumentHandl= er. + * @throws javax.xml.parsers.ParserConfigurationException a parser=20 + * satisfining requested configuration can not be created. + * @throws javax.xml.parsers.FactoryConfigurationError if the implemen= tation=20 + * can not be instantiated. + */ + public static void parse(final java.net.URL url, final JDOHandler hand= ler)=20 + throws SAXException, ParserConfigurationException, IOException=20 + { + parse(new InputSource(url.toExternalForm()), handler); + } + =20 + private static void parse(final InputSource input, final JDOParser rec= ognizer)=20 + throws SAXException, ParserConfigurationException, IOException=20 + { + SAXParserFactory factory =3D SAXParserFactory.newInstance(); + factory.setValidating(true); + factory.setNamespaceAware(true); + XMLReader parser =3D factory.newSAXParser().getXMLReader(); + parser.setEntityResolver(new JDOEntityResolver()); + parser.setContentHandler(recognizer); + parser.setErrorHandler(recognizer.getDefaultErrorHandler()); + parser.parse(input); + } + =20 + private ErrorHandler getDefaultErrorHandler()=20 + { + return new ErrorHandler() { + public void error(SAXParseException ex)=20 + throws SAXException { + if (context.isEmpty())=20 + System.err.println("Missing DOCTYPE."); //NOI18N + throw ex; + } + =20 + public void fatalError(SAXParseException ex)=20 + throws SAXException { + throw ex; + } + =20 + public void warning(SAXParseException ex)=20 + throws SAXException { + // ignore + } + }; + } + =20 + /** + * Implementation of EntityResolver interface to check the jdo.dtd loc= ation + **/ + private static class JDOEntityResolver=20 + implements EntityResolver=20 + { + private static final String RECOGNIZED_PUBLIC_ID =3D=20 + "-//Sun Microsystems, Inc.//DTD Java Data Objects Metadata 1.0= //EN"; + private static final String RECOGNIZED_SYSTEM_ID =3D=20 + "file:/javax/jdo/jdo.dtd"; + + public InputSource resolveEntity(String publicId, String systemId) + throws SAXException, IOException=20 + { + // check for recognized ids + if (((publicId !=3D null) && RECOGNIZED_PUBLIC_ID.equals(publi= cId)) || + ((publicId =3D=3D null) && (systemId !=3D null) &&=20 + RECOGNIZED_SYSTEM_ID.equals(systemId))) { + // Substitute the dtd with the one from javax.jdo.jdo.dtd, + // but only if the publicId is equal to RECOGNIZED_PUBLIC_= ID + // or there is no publicID and the systemID is equal to + // RECOGNIZED_SYSTEM_ID.=20 + InputStream stream =3D (InputStream) AccessController.= doPrivileged ( + new PrivilegedAction () { + public Object run () { + return getClass().getClassLoader(). + getResourceAsStream("javax/jdo/jdo.dtd"); = //NOI18N + } + } + ); + if (stream =3D=3D null) { + throw new JDOFatalInternalException( + msg.msg("EXC_MissingJDODTD", //NOI18N + publicId, systemId));=20 + } + return new InputSource(new InputStreamReader(stream)); + } + return null; + } + } +} + + Added: incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/= XMLExists.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/src/java/org/ap= ache/jdo/impl/model/jdo/xml/XMLExists.java?view=3Dauto&rev=3D158176 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/XML= Exists.java (added) +++ incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/model/jdo/xml/XML= Exists.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,290 @@ +/* + * Copyright 2005 The Apache Software Foundation. + *=20 + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at=20 + *=20 + * http://www.apache.org/licenses/LICENSE-2.0 + *=20 + * Unless required by applicable law or agreed to in writing, software=20 + * distributed under the License is distributed on an "AS IS" BASIS,=20 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= .=20 + * See the License for the specific language governing permissions and=20 + * limitations under the License. + */ + +package org.apache.jdo.impl.model.jdo.xml; + +import java.util.*; + +import org.apache.jdo.impl.model.java.AbstractJavaModelFactory; +import org.apache.jdo.impl.model.java.runtime.RuntimeJavaModel; +import org.apache.jdo.impl.model.jdo.caching.JDOModelFactoryImplCaching; +import org.apache.jdo.impl.model.jdo.util.PrintSupport; +import org.apache.jdo.model.ModelException; +import org.apache.jdo.model.java.JavaModel; +import org.apache.jdo.model.jdo.JDOClass; +import org.apache.jdo.model.jdo.JDOModel; +import org.apache.jdo.model.jdo.JDOModelFactory; + +/** + * This class allows to check whether there is JDO metadata for a class wi= th=20 + * a given class name. There must be a class file (enhanced or not enhance= d) + * available in the classpath of the caller. + *

    + * Usage: XMLExists <options> <arguments>... + *
    + * Options: + *
    + *   -h       + * print usage message + *
    + *   -v       + * print verbose messages and JDO metadata + *
    + *   -q       + * do not print any output; just set the exit code + *
    + *   -xml     + * expected to find JDO XML metadata for the specified class(es) + *
    + *   -noxml   + * expected to find no JDO XML metadata for the specified class(es) + *
    + * Arguments: + *
    + *   <classname>  + * the fully qualified name of a class to be checked + *

    + * The following sample call checks whether there is JDO XML metadata for = the=20 + * classes Emplyoe and Department from the com.xyz.hr package and dumps th= e=20 + * JDOClass instances: + *
    + *   java org.apache.jdo.impl.model.jdo.util.XMLExists -v=20 + * com.xyz.hr.Employee com.xyz.hr.Department + *

    + * Method main will exit the JVM with an exit code 1 if the test fails for=20 + * at least one class. Please note, the class dumps the JDOClass if the=20 + * outputLevel is set to VERBOSE (e.g. by setting the -v option). This JDO= Class=20 + * info does NOT include runtime metadata, even if the class file is enhan= ced. + *=20 + * @author Michael Bouschen + */ +public class XMLExists +{ + /**=20 + * Flag indicating whether the classes to be checked is expected to ha= ve=20 + * JDO XML metadata or not. + */ + private boolean xmlExpected; + =20 + /** Print verbose messages. */ + public static final int VERBOSE =3D 1; + + /** Normal output. */ + public static final int NORMAL =3D 0; + + /** No messages, just set the exit code. */ + public static final int QUIET =3D -1; + =20 + /** Output level.*/ + private int outputLevel =3D NORMAL; + + /**=20 + * The main method checks all classes specified as argument. + * It will exit the JVM with an exit code 1 if the test fails for=20 + * at least one class.=20 + * @param args arguments which are options followed by class names. + */ + public static void main(String[] args) + { + final XMLExists test =3D new XMLExists(); + final List classNames =3D test.processArgs(args); + if (!test.run(classNames)) + System.exit(1); + } + + /**=20 + * No arg constructor. The flags default to + *

      + *
    • xmlExpected =3D=3D true + *
    • outputLevel =3D=3D NORMAL + *
    + */ + public XMLExists() + { + this(true, NORMAL); + } + + /** Constructor taking checkXMLExists and outputLevel. */ + public XMLExists(boolean xmlExpected, int outputLevel) + { + this.xmlExpected =3D xmlExpected; + this.outputLevel =3D outputLevel; + } + + /** + * This method checks all classes from the specified list of class nam= es. + * It uses the current classLoader to load the classes. The method ret= urns=20 + * false if there is at least one class that fails on che= cking. + * @param classNames list of classes to be checked + * @return true if all classes are ok; + * false otherwise. + */ + public boolean run(List classNames) + { + ClassLoader classLoader =3D getClass().getClassLoader(); + XMLExistsJDOModelFactory factory =3D new XMLExistsJDOModelFactory(= ); + JavaModel javaModel =3D factory.getJavaModel(classLoader); + JDOModel jdoModel =3D javaModel.getJDOModel(); + boolean ok =3D true; + for (Iterator i =3D classNames.iterator(); i.hasNext(); ) { + final String className =3D (String)i.next(); + try { + checkClass(className, classLoader, jdoModel, xmlExpected); + if ((outputLevel =3D=3D NORMAL) && xmlExpected) + System.out.println( + "Found XML metadata for class " + className); //NO= I18N + =20 + else if ((outputLevel =3D=3D NORMAL) && !xmlExpected) + System.out.println( + "No MXL metadata for class " + className); //NOI18N + } + catch (Exception ex) { + if (outputLevel > QUIET) { + System.err.println(ex); + ex.printStackTrace(); + } + ok =3D false; + } + } + return ok; + } + =20 + /**=20 + * The method checks the class with the specified class name. + * It first loads the class using the specified class loader. + * If the flag xmlExpected is true it expects to get a no= n-null + * JDOClass instance. If the flag xmlExpected is false it=20 + * expects to get a null JDOClass instance.=20 + *

    + * The method indicates any failure by throwing an exception.=20 + * It dumps the JDOClass if the output level is VERBOSE. + * @param className the name of the class to be checked + * @param classLoader the class loader to be used to load the class + * @param jdoModel JDOModel for type info + * @param xmlExpected flag whether the class to be checked is expected= to=20 + * have JDO XML metadata or not. + */ + public void checkClass(String className,=20 + ClassLoader classLoader, + JDOModel jdoModel,=20 + boolean xmlExpected) + throws Exception + { + Class clazz =3D Class.forName(className, true, classLoader); + if (outputLevel =3D=3D VERBOSE) + System.out.println("Found " + clazz); //NOI18N + JDOClass jdoClass =3D jdoModel.getJDOClass(className); + if (xmlExpected && (jdoClass =3D=3D null)) { + throw new Exception( + "Missing JDO XML metadata for class " + //NOI18N + className); + } + if (!xmlExpected && (jdoClass !=3D null)) { + throw new Exception( + "Found JDO XML metadata for class " + className); //NOI18N + } + if ((outputLevel =3D=3D VERBOSE) && (jdoClass !=3D null)) { + PrintSupport.printJDOClass(jdoClass); + } + } + =20 + // =3D=3D=3D=3D Comand line processing helper method =3D=3D=3D=3D=3D + =20 + /** + * Helper method to do command line argument processing. + * @param args the arguments passed to main. + * @return the list of classes to be checked. + */ + protected List processArgs(String[] args) + {=20 + List classNames =3D new ArrayList(); + for (int i =3D 0; i < args.length; i++) { + final String arg =3D args[i]; + if (arg.equals("-h")) { //NOI18N + usage(); + } + else if (arg.equals("-v")) { //NOI18N + outputLevel =3D VERBOSE; + } + else if (arg.equals("-q")) { //NOI18N + outputLevel =3D QUIET; + } + else if (arg.equals("-xml")) { //NOI18N + xmlExpected =3D true; + } + else if (arg.equals("-noxml")) { //NOI18N + xmlExpected =3D false; + } + else if (arg.length() > 0 && arg.charAt(0) =3D=3D '-') { + System.err.println("Unrecognized option:" + arg); //NOI18N + usage(); + } + else if (arg.length() =3D=3D 0) { + System.err.println("Ignoring empty command line argument."= ); //NOI18N + } + else { + classNames.add(arg); + } + } + return classNames; + } + =20 + /** + * Print a usage message to System.err. + */ + public void usage()=20 + { + System.err.println("Usage: main ..."); //NOI1= 8N + System.err.println("Options:"); //NOI18N + System.err.println(" -h print usage message"); //NOI18N + System.err.println(" -v print verbose messages and JDO metad= ata"); //NOI18N + System.err.println(" -q do not print any messages; just set = the exit code"); //NOI18N + System.err.println(" -xml expected to find JDO XML metadata fo= r the specified class(es)"); //NOI18N + System.err.println(" -noxml expected to find no JDO XML metadata= for the specified class(es)"); //NOI18N + System.err.println("Arguments:"); //NOI18N + System.err.println(" the fully qualified name of a = class to be checked"); //NOI18N + } + =20 + /** + * JavaModelFactory implementation.=20 + * We cannot use the RuntimeJavaModelFactory, because it registers + * a JDOImplHelper event listener to populate enhancer generated + * metadata into the model. Since XMLExists checks whether JDO + * metadata is present from a .jdo we do not want to the enhancer + * generated metadata. + */ + private static class XMLExistsJDOModelFactory=20 + extends AbstractJavaModelFactory { + + /** */ + protected XMLExistsJDOModelFactory() {} + + /** */ + public JavaModel createJavaModel(Object key) throws ModelException= { + if ((key =3D=3D null) || (!(key instanceof ClassLoader))) + throw new ModelException("Invalid key " + key +=20 + " expected ClassLoader"); + ClassLoader classLoader =3D (ClassLoader)key; + return new RuntimeJavaModel(classLoader);=20 + } + =20 + /** */ + protected JDOModelFactory getJDOModelFactory() { + return JDOModelFactoryImplCaching.getInstance(); + } + } + =20 +} Added: incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/Bundle.prop= erties URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/src/java/org/ap= ache/jdo/impl/pm/Bundle.properties?view=3Dauto&rev=3D158176 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/Bundle.propert= ies (added) +++ incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/Bundle.propert= ies Fri Mar 18 17:02:29 2005 @@ -0,0 +1,102 @@ +# +# Copyright 2005 The Apache Software Foundation. +#=20 +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at=20 +#=20 +# http://www.apache.org/licenses/LICENSE-2.0 +#=20 +# Unless required by applicable law or agreed to in writing, software=20 +# distributed under the License is distributed on an "AS IS" BASIS,=20 +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.=20 +# See the License for the specific language governing permissions and=20 +# limitations under the License. + +# This file should conform to netbeans standards +# (http://www.netbeans.org/i18n) + +# resource bundle for the messages +# key consists of: +# - any valid prefix like MSG_, EXC_, etc. +# - short description started with the upper case letter and= used +# upper case to represent each next word. + +# XXX TBD: this message is not used: +notsupported=3DOperation is not supported in this release. + + +# +# CacheManagerImpl +# +EXC_MetaDataNotAvailable=3DMetadata for the owning Class is not available. +EXC_NonTransactional=3DInstance is not transactional. +EXC_ObjectExistsInCache=3DObject exists. Instance with the same primary ke= y is already in the PersistenceManager cache. +EXC_NotOID=3DGiven object is not a valid OID. +# NOI18N +EXC_ObjectIdExistsInCache=3DObjectId {0} already exists in this Persistenc= eManager cache. +# NOI18N +EXC_ObjectIdNotExistsInCache=3DObjectId {0} does not exist in this Persist= enceManager cache. + +# +# PersistenceManagerFactoryImpl +# +EXC_NotConfigurable=3DThis instance of PersistenceManagerFactory is not co= nfigurable. +EXC_IntegerInInvalidFormat=3DInteger found in invalid format: should not h= appen! +EXC_IncompleteConfiguration=3DOne of ConnectionURL, ConnectionFactory, or = ConnectionFactoryName must be set before using this PersistenceManagerFacto= ry. +EXC_WrongUsernamePassword=3DCannot use multiple combinations of username/p= assword in the same transaction. +# NOI18N +EXC_WrongJTATransaction=3DThis instance of javax.transaction.Transaction i= s registered with another PersistenceManager. +EXC_PersistenceManagerFactoryClosed=3DThis operation cannot be performed b= ecause this PersistenceManagerFactory is closed. +EXC_ActivePersistenceManager=3DThis PersistenceManagerFactory cannot be cl= osed while a PersistenceManager has an active transaction. +EXC_CannotAddShutdownHook=3DA SecurityException was thrown when trying \ +to add a JVM shudown hook. In order to register a shutdown hook, \ +you must grant java.lang.RuntimePermission("shutdownHooks") to the \ +codeBases containing the JDO Reference Implementation (jdo-ri.jar). + +# +# PersistenceManagerImpl +# +EXC_CannotGetRuntimeJavaModelFactory=3DA SecurityException was thrown when= trying \ +to get the singleton RuntimeJavaModelFactory instance. In order to get run= time \ +metadata, you must grant javax.jdo.spi.JDOPermission("getMetadata") to the= \ +codeBases containing the JDO Reference Implementation (jdo.jar and jdo-ri.= jar). +EXC_ActiveTransaction=3DCannot close PersistenceManager while transaction = is still active. +EXC_WrongSCOType=3DTracked SCO instances of type {0} are not supported. +EXC_CannotConstructSCO=3DException during construction of type {0}. +EXC_IllegalArguments=3DWrong arguments for construction of type {0}. +EXC_PersistenceManagerClosed=3DPersistenceManager was closed. +EXC_TransactionNotActive=3DTransaction is not active. +EXC_NotPersistenceCapable=3DClass {0} not PersistenceCapable. The class of= the instance does not implement PersistenceCapable. Check to see that the = class has been enhanced and that the class path is correct (the unenhanced = version of the class should not be in the class path). +EXC_CollectionType=3DParameter is of a Collection type; use method {0}All(= Collection). +EXC_ArrayType=3DParameter is of an array type; use method {0}All(Object[]). +EXC_TransientInstance=3DInstance of class {0} is not persistent. +EXC_AnotherPersistenceManager=3DObject owned by another PersistenceManager. +EXC_ClassNotPersistenceCapable=3DClass given to getExtent, {0}, does not = implement javax.jdo.spi.PersistenceCapable +EXC_FailedToProcessAll=3DFailed to process all objects. +EXC_CannotFindSM=3DCould not find a StateManager for the given Persistence= Capable of class {0}. +# NOI18N +EXC_NotNullJTATransaction=3DAttempt to replace not null javax.transaction.= Transaction. +EXC_UnsupportedQueryLanguage=3DUnsupported query language ''{0}'' +EXC_CannotFindPCClassForObjectIdClass=3DCannot find persistence-capable cl= ass for ObjectId class ''{0}'' + +# +# TransactionImpl +# +EXC_CannotChangeType=3DCannot change transaction type during an active tra= nsaction. +EXC_CannotSetFlag=3DCannot change flag value during commit or rollback pro= cessing. +EXC_CannotSetFlagIfActive=3DCannot change flag value if transaction is act= ive. +EXC_SynchronizationNotNull=3DA Synchronization object has already been set= for this transaction. +EXC_ErrorBegin=3DTransaction has already begun. +EXC_TransactionRolledback=3DTransaction already rolled back or rollback in= progress. +EXC_TransactionCommitting=3DTransaction has already started to commit. +EXC_MarkedRolledback=3DThis transaction was marked rollback-only. +EXC_WrongStateCommit=3DTransaction in wrong state to commit. +EXC_WrongStateRollback=3DTransaction in wrong state to rollback. +EXC_InvalidStatus=3DInvalid Transaction.{0}(). This transaction status is = not {1} (status =3D {2}). +EXC_WrongMgdOperation=3DOperation {0} is not allowed in managed environmen= t=2E +EXC_WrongNonMgdOperation=3DOperation {0} is not allowed in non-managed env= ironment. +EXC_NontransactionalRead=3DThis operation requires that a transaction be a= ctive or the NontransactionalRead flag be true. +# NOI18N +EXC_ErrorRegister=3DCannot register this instance with JTA Synchronization. + Added: incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/CacheManage= rImpl.java URL: http://svn.apache.org/viewcvs/incubator/jdo/trunk/ri11/src/java/org/ap= ache/jdo/impl/pm/CacheManagerImpl.java?view=3Dauto&rev=3D158176 =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D --- incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/CacheManagerIm= pl.java (added) +++ incubator/jdo/trunk/ri11/src/java/org/apache/jdo/impl/pm/CacheManagerIm= pl.java Fri Mar 18 17:02:29 2005 @@ -0,0 +1,630 @@ +/* + * Copyright 2005 The Apache Software Foundation. + *=20 + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at=20 + *=20 + * http://www.apache.org/licenses/LICENSE-2.0 + *=20 + * Unless required by applicable law or agreed to in writing, software=20 + * distributed under the License is distributed on an "AS IS" BASIS,=20 + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied= .=20 + * See the License for the specific language governing permissions and=20 + * limitations under the License. + */ + +/* + * CacheManagerImpl.java + * + * Created on December 1, 2000 + */ + +package org.apache.jdo.impl.pm; + +import java.util.*; +import java.lang.reflect.Field; +import java.lang.reflect.Constructor; +import java.lang.ref.WeakReference; + +import javax.jdo.*; +import javax.jdo.spi.*; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.apache.jdo.impl.state.StateManagerFactory; +import org.apache.jdo.pm.PersistenceManagerInternal; +import org.apache.jdo.state.StateManagerInternal; +import org.apache.jdo.store.StoreManager; +import org.apache.jdo.util.I18NHelper; +import org.apache.jdo.util.WeakValueHashMap; + +/* + * This is the cache manager that is responsible for operation of + * all types of caches (weak, transactional, flushed, transient) + * associated with the referenced instance of a PersistenceManager. + * + * @author Marina Vatkina + */ +class CacheManagerImpl { + + // Reference to the corresponding PersistenceManagerImpl. + PersistenceManagerImpl pm =3D null; + + /** + * Collection of Persistent instances created and/or updated + * in this Transaction + */ + private Collection _txCache =3D Collections.synchronizedSet(new HashSe= t()); + + /** + * Collection of Transient-transactional instances registered + * with this Transaction + */ + private Collection _transientCache =3D new Vector(); + + /** + * Collection of Persistent instances that will require state + * change at the transaction completion + */ + private ArrayList _flushedCache =3D new ArrayList(); + + /** + * Collection of StateManager instances that represent Persistent + * instances that had been made newly persistent in the current + * transaction. + */ + private ArrayList _newInstances =3D new ArrayList(); + + /**=20 + * Weak Hashtable of Persistent instances accessed by this Persistence= Manager + */ + private WeakValueHashMap _weakCache =3D new WeakValueHashMap(); + + /** + * Logger instance + */ + private static final Log logger =3D LogFactory.getFactory().getInstanc= e( + "org.apache.jdo.impl.pm"); // NOI18N + + /** + * I18N message handler + */ + private final static I18NHelper msg =3D=20 + I18NHelper.getInstance(CacheManagerImpl.class); + + /** + * Constructs new instnstance of CacheManagerImpl + *=20 + * @param pm calling instance of PersistenceManagerImpl + */ + CacheManagerImpl(PersistenceManagerImpl pm) { + this.pm =3D pm; + } + + /** + * close the CacheManagerImpl + */ + protected void close() { + // RELEASE THE CACHE... + // Nothing should be in _txCache and/or _flushedCache because + // PersistenceManager verified that transaction is not + // active. _transientCache can have transient transactional + // instances, but it is OK to clear them.=20 + _weakCache.clear(); + _txCache.clear(); + _flushedCache.clear(); + _transientCache.clear(); + } + + =20 + + /** This method locates a persistent instance in the cache of instances + * managed by this PersistenceManager. + * =20 + *

    If the validate flag is true: This method verifies that there + * is an instance in the data store with the same oid, constructs an + * instance, and returns it. If there is no transaction active, then + * a hollow instance or persistent non-transactional instance is retur= ned. + * If there is a transaction active, then + * a persistent clean instance is returned. + *

    If the validate flag is false: If there is not already an instan= ce + * in the cache with the same oid, then an instance is constructed and + * returned. If the instance does not exist + * in the data store, then this method will + * not fail. However, a request to access fields of the instance will + * throw an exception. + * @return the PersistenceCapable instance with the specified + * ObjectId + * @param oid an ObjectId + * @param validate if the existence of the instance is to be validated + */ + protected Object getObjectById (Object oid, boolean validate) { + if (debugging()) + debug ("getObjectById"); // NOI18N + + StateManagerInternal sm =3D this.getStateManager(oid, validate); + return ((StateManagerInternal)sm).getObject(); + } + + /** + * Returns StateManager instance associated with this instance of Obje= ctId + * Creates a Hollow instance of a PersistenceCapable object, if it can= not be=20 + * found in the cache + * @param oid an ObjectId + * @param pcClass Class of a Hollow instance to be created. + * @return the StateManagerInternal=20 + */ + protected StateManagerInternal getStateManager (Object oid, Class pcCl= ass) { + if (debugging()) + debug ("getStateManager " + oid + " for: " + pcClass.getName()= ); // NOI18N + + StateManagerInternal sm =3D null; + // Check weak cache to find SM: + synchronized (_weakCache) { + // Need to keep a reference to the value in the cache as it is= a weak + // cache and the value might be removed otherwise. + Object o =3D _weakCache.get(oid); + if (o =3D=3D null) { + // Nothing found + sm =3D createNewSM(null, oid, pcClass); + } else { + // Prepare Hollow instance if its class type was not + // known before.=20 + sm =3D (StateManagerInternal)o; + sm.setPCClass(pcClass); + } + } + + if (debugging()) + debug ("return from getStateManager: " + sm); // NOI18N + + return sm; + } + + /** + * The ObjectId returned by this method represents the JDO identity of + * the instance. The ObjectId is a copy (clone) of the internal state + * of the instance, and changing it does not affect the JDO identity of + * the instance. + * Delegates actual execution to the internal method. + * @param pc the PersistenceCapable instance + * @param transactional true if transactional Id is requested + * @return the ObjectId of the instance + */ + protected Object getExternalObjectId (PersistenceCapable pc, + boolean transactional) { + StateManagerInternal sm =3D pm.findStateManager(pc); + + Object oid =3D null; + if (_weakCache.containsValue(sm)) { + if (transactional) + oid =3D sm.getTransactionalObjectId(pc); + else + oid =3D sm.getExternalObjectId(); + } + + return oid; + } + + /** Make the transient instance persistent in this PersistenceManager. + * This method must be called in an active transaction. + * The PersistenceManager assigns an ObjectId to the instance and + * transitions it to persistent-new. + * The instance will be managed in the Extent associated with its Clas= s=2E + * The instance will be put into the data store at commit. + * @param pc a transient instance of a Class that implements + * PersistenceCapable + */ + protected void makePersistent (PersistenceCapable pc) { + + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm =3D=3D null) { + sm =3D StateManagerFactory.newInstance(pc, pm); + } + + sm.makePersistent(); + } + + /** Make the transient or persistent instance transactional in + * this PersistenceManager. + * @see javax.jdo.PersistenceManager#makeTransactional(Object pc) + */ + protected void makeTransactional(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm =3D=3D null) { + sm =3D StateManagerFactory.newInstance(pc, pm); + } + sm.makeTransactional(); + } + + + /** Make the transient or persistent instance transactional in + * this PersistenceManager. + * @see javax.jdo.PersistenceManager#makeNontransactional(Object pc) + */ + protected void makeNontransactional(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm =3D=3D null) { + throw new JDOUserException(msg.msg( + "EXC_NonTransactional")); // NOI18N + } + sm.makeNontransactional(); + } + + + /** Make the persistent instance transient in this PersistenceManager. + * @see javax.jdo.PersistenceManager#makeTransient(Object pc) + */ + protected void makeTransient(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm !=3D null) { + sm.makeTransient(); + } + } + + /** Make persistent instance hollow in this PersistenceManager. + * @see javax.jdo.PersistenceManager#evict(Object pc) + */ + protected void evict(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm !=3D null) { + sm.evictInstance(); + } + } + + /** Make all non-dirty persistent instances in the cache hollow in=20 + * this PersistenceManager. + * @see javax.jdo.PersistenceManager#evictAll() + */ + protected void evictAll() { + StateManagerInternal sm =3D null; + + Iterator it =3D _weakCache.entrySet().iterator(); + while (it.hasNext()) { + sm =3D (StateManagerInternal) ((Map.Entry)it.next()).getValue(= ); + sm.evictInstance(); + } + } + + /** Retrieve Hollow persistent instance in this PersistenceManager. + * @see javax.jdo.PersistenceManager#retrieve(Object pc) + */ + protected void retrieve(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm !=3D null) { + sm.retrieve(); + } + } + + /** Refresh dirty persistent instance in this PersistenceManager. + * @see javax.jdo.PersistenceManager#refresh(Object pc) + */ + protected void refresh(PersistenceCapable pc) { + StateManagerInternal sm =3D pm.findStateManager(pc); + if (sm !=3D null) { + sm.refreshInstance(); + } + } + + /** Refresh dirty persistent instances in the transactional cache=20 + * of this PersistenceManager. Called in an active transaction. + * @see javax.jdo.PersistenceManager#refreshAll() + */ + protected void refreshAllTransactional() { + StateManagerInternal sm =3D null; + + Iterator it =3D _txCache.iterator(); + while(it.hasNext()) { + sm =3D (StateManagerInternal)it.next(); + sm.refreshInstance(); + } + } + + /** Refresh nontransactional instances in the weak cache + * of this PersistenceManager. Called outside an active transaction. + * @see javax.jdo.PersistenceManager#refreshAll() + */ + protected void refreshAllNontransactional() { + StateManagerInternal sm =3D null; + + Iterator it =3D _weakCache.entrySet().iterator(); + while (it.hasNext()) { + sm =3D (StateManagerInternal) ((Map.Entry)it.next()).getValue(= ); + sm.refreshInstance(); + } + } + + /** + * Register transient instance in the transient cache + */ + protected void registerTransient(StateManagerInternal sm) { + Iterator it =3D _transientCache.iterator(); + while(it.hasNext()) { + Object o =3D ((WeakReference)it.next()).get(); + if ((StateManagerInternal)o =3D=3D sm) { + // The same SM is found - nothing to do. + return; + } + } + _transientCache.add(new WeakReference(sm)); + } + + /** + * Register persistent instance in the transactional cache + */ + protected void register(StateManagerInternal sm, Object oid,=20 + boolean transactional, boolean throwDuplicateException) { + if (oid =3D=3D null) { + oid =3D sm.getInternalObjectId(); + } + + //register in both caches for transactional instances only + + if (! _weakCache.containsKey(oid)) { + deregisterTransient(sm); + _weakCache.put(oid, sm); =20 + + } else if (throwDuplicateException) { + throw new JDOUserException(msg.msg( + "EXC_ObjectExistsInCache")); // NOI18N + } + + if (pm.currentTransaction().isActive() && transactional) { + // Register in both caches for convenience. + if (! _flushedCache.contains(sm)) { + _flushedCache.add(sm);=20 + } + if (! _txCache.contains(sm)) { + _txCache.add(sm);=20 + if (sm.isNew())=20 + _newInstances.add(sm.getObject()); + } + } + + if (!transactional) { + // Remove from transactional caches if instance became + // nontransactional + _txCache.remove(sm);=20 + _flushedCache.remove(sm); + } + } + + /** + * Remove transient instance from the transient cache + */ + protected void deregisterTransient(Object sm) { + Iterator it =3D _transientCache.iterator(); + while(it.hasNext()) { + WeakReference wr =3D (WeakReference)it.next(); + if ((StateManagerInternal)wr.get() =3D=3D sm) { + _transientCache.remove(wr); + break; + } + } + } + + /** + * Remove persistent instance from all caches + */ + protected void deregister(Object oid) { + if (oid !=3D null) { + //deregister the instance from all the caches + Object o =3D _weakCache.remove(oid); + + // No need to do anything outside an active transaction. + if (pm.currentTransaction().isActive()) { + _txCache.remove(o); + _flushedCache.remove(o); + } + } + } + + /** =20 + * @see PersistenceManagerInternal#replaceObjectId(Object oldId, + * Object newId) + */ =20 + protected void replaceObjectId(Object oldId, Object newId) { + if (debugging()) + debug ("replaceObjectId"); // NOI18N + + synchronized(_weakCache) { + if (_weakCache.containsKey(newId)) { + throw new JDOFatalInternalException(msg.msg( + "EXC_ObjectIdExistsInCache", newId)); // NOI18N + } + Object o =3D _weakCache.remove(oldId); + if (o =3D=3D null) { + throw new JDOFatalInternalException(msg.msg( + "EXC_ObjectIdNotExistsInCache", newId)); // NOI18N + } + _weakCache.put(newId, o); + } + } + + /** =20 + * @see PersistenceManagerInternal#markAsFlushed(StateManagerInternal = sm) + */ =20 + protected void markAsFlushed(StateManagerInternal sm) {=20 + _txCache.remove(sm); + } + + /** + * Called by Transaction#commit(), Transaction#beforeCompletion(), or + * Transaction#internalFlush(). + * Processes instances for the reachability algorithm, then calls + * StoreManager to iterate over transactional cache and to call flush(= )=20 + * for each StateManager in it. + */ + protected void flushInstances() { + StateManagerInternal sm =3D null; + + Object[] e =3D _txCache.toArray(); + boolean commit =3D pm.insideCommit(); + + for (int i =3D 0; i < e.length; i++) { + sm =3D (StateManagerInternal)e[i]; + + // + // NOTE: handleRelationships has the side-effect of adding + // more objects to the transaction cache. + // + sm.handleReachability(commit); + } + + StoreManager srm =3D pm.getStoreManager(); + Iterator it =3D _txCache.iterator(); + + srm.flush(it, pm); + + _txCache.clear(); + } + + /** + * Called by Transaction commit() or rollback() + * cleans up transactional cache + * @param abort=20 + */ + protected void afterCompletion(boolean abort) { + boolean retainValues =3D pm.currentTransaction().getRetainValues(); + boolean restoreValues =3D pm.currentTransaction().getRestoreValues= (); + + // Need to process transient instances also + Iterator it =3D _transientCache.iterator(); + while(it.hasNext()) { + Object o =3D ((WeakReference)it.next()).get(); + + if (o =3D=3D null) {=20 + // It has been GC'd and should be removed from _transientC= ache.=20 + it.remove();=20 + } else { + _flushedCache.add(o); + } + } + + int len =3D _flushedCache.size(); + for ( int i =3D 0; i < len; i++) { + StateManagerInternal sm =3D (StateManagerInternal)_flushedCach= e=2Eget(i); + sm.afterCompletion(abort, retainValues, restoreValues); + } + + // Now clean the flushed cache + _flushedCache.clear(); + _newInstances.clear(); + + // Just in case beforeCompletion failed or it was a rollback + _txCache.clear(); + } + + /** + * Returns a Collection of instances that has been made persistent + * or become persistent through persistence-by-reachability + * algorithm in this transaction. Called by the Extent.iterator. + * @see PersistenceManagerInternal#getInsertedInstances + * @return Collection of Persistent-New instances. + */ + protected Collection getInsertedInstances() { + if (debugging()) + debug("getInsertedInstances"); // NOI18N + + return _newInstances; + } + + /** --------------Private Methods-------------- */ + + /** + * Returns StateManager instance associated with this instance of Obje= ctId + * @see #getObjectById(Object oid, boolean validate) + * @param oid an ObjectId + * @param validate if the existence of the instance is to be validated + */ + private StateManagerInternal getStateManager (Object oid, boolean vali= date) { + + Object o =3D null; + StoreManager srm =3D pm.getStoreManager(); + Class candidateClassType =3D srm.getPCClassForOid(oid, pm); + if (candidateClassType =3D=3D null) { + // not found, report an error + throw new JDOUserException(msg.msg( + "EXC_NotOID"),// NOI18N + oid); + } + + Object internalOid =3D srm.getInternalObjectId(oid, pm); + if (debugging()) + debug ("getStateManager internal oid: " + internalOid); // NOI= 18N + + StateManagerInternal sm =3D null; + + // Check weak cache to find SM: + synchronized (_weakCache) { + if((o =3D _weakCache.get(internalOid)) =3D=3D null) { + // Nothing found + if (debugging()) + debug ("getStateManager oid not found."); // NOI18N + + sm =3D createNewSM(oid, internalOid, candidateClassType); + // Always reload from the DB to resolve actual classType + if (validate || !srm.hasActualPCClass(internalOid)) + sm.reload(); + return sm; + + } else if (validate && !_flushedCache.contains(o)) { + // Found but NOT in the transactional cache. Reload. + if (debugging()) + debug ("getStateManager oid found - reload."); // NOI1= 8N + + sm =3D (StateManagerInternal)o; + sm.reload(); + return sm; + } + } + return (StateManagerInternal)o; + } + + /** + * Creates new StateManager instance associated with this instance + * of ObjectId. + * @see #getObjectById(Object oid, boolean validate) + * @param UserOid a user provided ObjectId + * @param internalOid an internal ObjectId + * @param candidateClassType super class of a Hollow instance to be cr= eated. + */ + private StateManagerInternal createNewSM(Object UserOid, Object intern= alOid, + Class candidateClass= Type) { + try { + return StateManagerFactory.newInstance(UserOid, internalOid,=20 + pm, candidateClassType); + + } catch (JDOUserException e) { + throw e; + // XXX Possible jikes bug + // + // The following catch phrase causes jikes to complain (Cautio= n: + // This try block cannot throw a "checked exception" (JLS sect= ion + // 14.7) that can be caught here. You may have intended to cat= ch + // a RuntimeException instead of an Exception.) But this try + // block is *not* here throwing any checked exceptions! That's + // why I think it's a jikes bug (Sun's javac does not complain= .) + } catch (Exception e) { + throw new JDOUserException(msg.msg("EXC_NotOID"), e, UserOid);= // NOI18N + } + } + + /** + * Tracing method + * @param msg String to display + */ =20 + private void debug(String msg) { + logger.debug("In CacheManagerImpl " + msg); // NOI18N + } + /** + * Verifies if debugging is enabled. + * @return true if debugging is enabled. + */ + private boolean debugging() { + return logger.isDebugEnabled(); + } + +}