diff --git a/x4o-core/src/main/java/org/x4o/xml/X4ODriver.java b/x4o-core/src/main/java/org/x4o/xml/X4ODriver.java new file mode 100644 index 0000000..ec3e6b0 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/X4ODriver.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml; + +import java.util.Collection; + +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.core.phase.X4OPhaseException; +import org.x4o.xml.core.phase.X4OPhaseType; +import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.io.DefaultX4OReader; +import org.x4o.xml.io.DefaultX4OSchemaWriter; +import org.x4o.xml.io.DefaultX4OWriter; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.io.X4OSchemaWriter; +import org.x4o.xml.io.X4OWriter; + +/** + * This is the starting point of the XML X4O Language Driver. + * + * @author Willem Cazander + * @version 1.0 Aug 11, 2005 + */ +public abstract class X4ODriver { + + /** Defines the default version if none is defined. */ + public final static String DEFAULT_LANGUAGE_VERSION = "1.0"; + + /** + * Force public constructor and register the driver. + */ + public X4ODriver() { + X4ODriverManager.registerX4ODriver(this); + } + + abstract public String getLanguageName(); + + abstract public String[] getLanguageVersions(); + + abstract public X4OLanguage buildLanguage(String version); + + public X4OLanguage createLanguage(String version) { + X4OLanguage result = null; + if (result==null) { + result = buildLanguage(version); + } + return result; + } + + public ElementLanguage createLanguageContext() { + return createLanguageContext(getLanguageVersionDefault()); + } + + public ElementLanguage createLanguageContext(String version) { + X4OLanguage language = createLanguage(version); + ElementLanguage result = language.getLanguageConfiguration().createElementLanguage(this); + + try { + result.getLanguage().getPhaseManager().runPhases(result, X4OPhaseType.INIT); + } catch (X4OPhaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return result; + } + + public X4OSchemaWriter createSchemaWriter() { + return createSchemaWriter(getLanguageVersionDefault()); + } + + public X4OSchemaWriter createSchemaWriter(String version) { + return new DefaultX4OSchemaWriter(createLanguageContext(version)); + } + + public X4OReader createReader() { + return createReader(getLanguageVersionDefault()); + } + + public X4OReader createReader(String version) { + return new DefaultX4OReader(createLanguageContext(version)); + } + + public X4OWriter createWriter() { + return createWriter(getLanguageVersionDefault()); + } + + public X4OWriter createWriter(String version) { + return new DefaultX4OWriter(createLanguageContext(version)); + } + + public String getLanguageVersionDefault() { + String[] lang = getLanguageVersions(); + if (lang==null || lang.length==0) { + return DEFAULT_LANGUAGE_VERSION; + } + String langVersion = lang[lang.length-1]; + return langVersion; + } + + /** + * @return Returns the property keys which can be set. + */ + public String[] getGlobalPropertyKeySet() { + return X4OLanguagePropertyKeys.DEFAULT_X4O_GLOBAL_KEYS; + } + + /** + * @return Returns the property keys which are set. + */ + final public Collection getGlobalPropertyKeys() { + return X4ODriverManager.getGlobalPropertyKeys(this); + } + + final public Object getGlobalProperty(String key) { + return X4ODriverManager.getGlobalProperty(this, key); + } + + final public void setGlobalProperty(String key,Object value) { + X4ODriverManager.setGlobalProperty(this, key, value); + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/X4ODriverManager.java b/x4o-core/src/main/java/org/x4o/xml/X4ODriverManager.java new file mode 100644 index 0000000..1c3c63e --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/X4ODriverManager.java @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import org.x4o.xml.core.config.X4OLanguageClassLoader; +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.ext.DefaultHandler2; +import org.xml.sax.helpers.XMLReaderFactory; + +public final class X4ODriverManager { + + public final static String X4O_DRIVERS_RESOURCE = "META-INF/x4o-drivers.xml"; + private final static X4ODriverManager instance; + private Logger logger = null; + private volatile boolean reloadDrivers = true; + private Map classdrivers = null; + private Map defaultDrivers = null; + private Map> drivers = null; + private Map> globalProperties = null; + + private X4ODriverManager() { + logger = Logger.getLogger(X4ODriverManager.class.getName()); + classdrivers = new HashMap(10); + defaultDrivers = new HashMap(10); + drivers = new HashMap>(10); + globalProperties = new HashMap>(20); + } + + static { + instance = new X4ODriverManager(); + } + + static public Collection getGlobalPropertyKeys(X4ODriver driver) { + Map driverProperties = instance.globalProperties.get(driver.getLanguageName()); + if (driverProperties==null) { + return Collections.emptySet(); + } + return driverProperties.keySet(); + } + + static public Object getGlobalProperty(X4ODriver driver,String key) { + Map driverProperties = instance.globalProperties.get(driver.getLanguageName()); + if (driverProperties==null) { + return null; + } + return driverProperties.get(key); + } + + static public void setGlobalProperty(X4ODriver driver,String key,Object value) { + Map driverProperties = instance.globalProperties.get(driver.getLanguageName()); + if (driverProperties==null) { + driverProperties = new HashMap(20); + instance.globalProperties.put(driver.getLanguageName(), driverProperties); + } + String keyLimits[] = driver.getGlobalPropertyKeySet(); + for (int i=0;i driver) { + instance.drivers.put(driver.getLanguageName(), driver); + } + + static public void deregisterX4ODriver(X4ODriver driver) { + instance.drivers.remove(driver.getLanguageName()); + } + + static public X4ODriver getX4ODriver(String language) { + if (language==null) { + throw new NullPointerException("Can't provider driver for null language."); + } + if (language.isEmpty()) { + throw new IllegalArgumentException("Can't provider driver for empty language."); + } + try { + instance.lazyInit(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + X4ODriver result = null; + try { + result = instance.createX4ODriver(language); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + if (result==null) { + throw new IllegalArgumentException("Can't find driver for language: "+language); + } + return result; + } + + static public List getX4OLanguages() { + try { + instance.lazyInit(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + List result = new ArrayList(10); + result.addAll(instance.classdrivers.keySet()); + result.addAll(instance.defaultDrivers.keySet()); + Collections.sort(result); + return result; + } + + private void lazyInit() throws IOException, SAXException { + if (reloadDrivers==false) { + return; + } + instance.loadLanguageDrivers(); + reloadDrivers = false; + } + + private X4ODriver createX4ODriver(String language) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + if (classdrivers.containsKey(language)) { + String driverClassName = classdrivers.get(language); + Class driverClass = X4OLanguageClassLoader.loadClass(driverClassName); + X4ODriver driver = (X4ODriver)driverClass.newInstance(); + return driver; + } + if (defaultDrivers.containsKey(language)) { + String driverClassName = defaultDrivers.get(language); + Class driverClass = X4OLanguageClassLoader.loadClass(driverClassName); + X4ODriver driver = (X4ODriver)driverClass.newInstance(); + return driver; + } + return null; + } + + /** + * Loads all defined language drivers in classpath. + */ + private void loadLanguageDrivers() throws IOException, SAXException { + + logger.finer("loading x4o drivers from: "+X4O_DRIVERS_RESOURCE); + Enumeration e = Thread.currentThread().getContextClassLoader().getResources(X4O_DRIVERS_RESOURCE); + while(e.hasMoreElements()) { + URL u = e.nextElement(); + loadDriversXml(u.openStream()); + } + + e = Thread.currentThread().getContextClassLoader().getResources("/"+X4O_DRIVERS_RESOURCE); + while(e.hasMoreElements()) { + URL u = e.nextElement(); + loadDriversXml(u.openStream()); + } + } + + /** + * Parser xml inputstream and add into drivers and defaultDrivers lists. + * @param in The inputstream to parser. + * @throws IOException + * @throws SAXException + */ + private void loadDriversXml(InputStream in) throws IOException, SAXException { + if (in==null) { + throw new NullPointerException("Can't parse null input stream"); + } + DriversTagHandler xth = new DriversTagHandler(); + XMLReader saxParser = XMLReaderFactory.createXMLReader(); + saxParser.setContentHandler(xth); + saxParser.setProperty("http://xml.org/sax/properties/lexical-handler", xth); + saxParser.setProperty("http://xml.org/sax/properties/declaration-handler",xth); + try { + saxParser.parse(new InputSource(in)); + } finally { + in.close(); + } + } + + private class DriversTagHandler extends DefaultHandler2 { + @Override + public void startElement(String namespaceUri, String tag, String qName,Attributes attr) throws SAXException { + if ("drivers".equals(tag)) { + String version = attr.getValue("version"); + logger.finest("Version attribute: "+version); + } else if ("driver".equals(tag)) { + String language = attr.getValue("language"); + String className = attr.getValue("className"); + logger.finest("Driver className: "+className+" for language: "+language); + if (classdrivers.containsKey(className)==false) { + classdrivers.put(language,className); + } + } else if ("defaultDriver".equals("tab")) { + String language = attr.getValue("language"); + logger.finest("DefaultDriver language: "+language); + if (defaultDrivers.containsKey(language)==false) { + defaultDrivers.put(language,language); + } + } + } + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4ODebugWriter.java b/x4o-core/src/main/java/org/x4o/xml/core/X4ODebugWriter.java index 183fd51..3fccf5f 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4ODebugWriter.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/X4ODebugWriter.java @@ -31,6 +31,9 @@ import java.util.Map; import org.x4o.xml.conv.ObjectConverter; import org.x4o.xml.core.config.X4OLanguageConfiguration; import org.x4o.xml.core.config.X4OLanguageProperty; +import org.x4o.xml.core.phase.X4OPhaseException; +import org.x4o.xml.core.phase.X4OPhase; +import org.x4o.xml.core.phase.X4OPhaseListener; import org.x4o.xml.element.Element; import org.x4o.xml.element.ElementAttributeHandler; import org.x4o.xml.element.ElementBindingHandler; @@ -65,8 +68,8 @@ public class X4ODebugWriter { public X4ODebugWriter(DefaultHandler2 debugWriter) { this.debugWriter=debugWriter; } - - protected DefaultHandler2 getDebugWriter() { + + public DefaultHandler2 getDebugWriter() { return debugWriter; } @@ -80,14 +83,14 @@ public class X4ODebugWriter { /** * @throws X4OPhaseException - * @see org.x4o.xml.core.X4OPhaseListener#preRunPhase(org.x4o.xml.element.ElementLanguage) + * @see org.x4o.xml.core.phase.X4OPhaseListener#preRunPhase(org.x4o.xml.element.ElementLanguage) */ - public void preRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { + public void preRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException { startTime = System.currentTimeMillis(); try { AttributesImpl atts = new AttributesImpl(); if (elementLanguage!=null) { - atts.addAttribute("", "language","","", elementLanguage.getLanguageConfiguration().getLanguage()); + atts.addAttribute("", "language","","", elementLanguage.getLanguage().getLanguageName()); } debugWriter.startElement (DEBUG_URI, "executePhase", "", atts); } catch (SAXException e) { @@ -96,11 +99,11 @@ public class X4ODebugWriter { debugPhase(phase); } - public void endRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { + public void endRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException { long stopTime = System.currentTimeMillis(); try { AttributesImpl atts = new AttributesImpl(); - atts.addAttribute ("", "name", "", "", phase.getX4OPhase().name()); + atts.addAttribute ("", "id", "", "", phase.getId()); atts.addAttribute ("", "speed", "", "", (stopTime-startTime)+" ms"); debugWriter.startElement (DEBUG_URI, "executePhaseDone", "", atts); debugWriter.endElement (DEBUG_URI, "executePhaseDone" , ""); @@ -117,7 +120,7 @@ public class X4ODebugWriter { AttributesImpl atts = new AttributesImpl(); debugWriter.startElement (DEBUG_URI, "X4OLanguageProperties", "", atts); for (X4OLanguageProperty p:X4OLanguageProperty.values()) { - Object value = ec.getLanguageConfiguration().getLanguageProperty(p); + Object value = ec.getLanguageProperty(p); if (value==null) { continue; } @@ -137,7 +140,7 @@ public class X4ODebugWriter { try { AttributesImpl atts = new AttributesImpl(); debugWriter.startElement (DEBUG_URI, "X4OLanguageDefaultClasses", "", atts); - X4OLanguageConfiguration conf = ec.getLanguageConfiguration(); + X4OLanguageConfiguration conf = ec.getLanguage().getLanguageConfiguration(); debugLanguageDefaultClass("getDefaultElementNamespaceContext",conf.getDefaultElementNamespaceContext()); debugLanguageDefaultClass("getDefaultElementInterface",conf.getDefaultElementInterface()); @@ -167,12 +170,12 @@ public class X4ODebugWriter { debugWriter.endElement(DEBUG_URI, "X4OLanguageDefaultClass", ""); } - public void debugPhaseOrder(List phases) throws X4OPhaseException { - X4OPhaseHandler phase = null; + public void debugPhaseOrder(List phases) throws X4OPhaseException { + X4OPhase phase = null; try { AttributesImpl atts = new AttributesImpl(); debugWriter.startElement (DEBUG_URI, "phaseOrder", "", atts); - for (X4OPhaseHandler phase2:phases) { + for (X4OPhase phase2:phases) { phase = phase2; debugPhase(phase2); } @@ -189,11 +192,11 @@ public class X4ODebugWriter { } } - private void debugPhase(X4OPhaseHandler phase) throws X4OPhaseException { + private void debugPhase(X4OPhase phase) throws X4OPhaseException { try { AttributesImpl atts = new AttributesImpl(); - atts.addAttribute ("", "name", "", "", phase.getX4OPhase().name()); - atts.addAttribute ("", "runOnce", "", "", phase.getX4OPhase().isRunOnce()+""); + atts.addAttribute ("", "id", "", "", phase.getId()); + atts.addAttribute ("", "runOnce", "", "", phase.isRunOnce()+""); atts.addAttribute ("", "listenersSize", "", "", phase.getPhaseListeners().size()+""); debugWriter.startElement (DEBUG_URI, "phase", "", atts); @@ -214,7 +217,7 @@ public class X4ODebugWriter { AttributesImpl attsEmpty = new AttributesImpl(); debugWriter.startElement (DEBUG_URI, "ElementLanguageModules", "", attsEmpty); - for (ElementLanguageModule module:elementLanguage.getElementLanguageModules()) { + for (ElementLanguageModule module:elementLanguage.getLanguage().getElementLanguageModules()) { AttributesImpl atts = new AttributesImpl(); atts.addAttribute ("", "className", "", "", module.getClass().getName()); atts.addAttribute ("", "name", "", "", module.getName()); @@ -422,10 +425,10 @@ public class X4ODebugWriter { public void debugElementLanguage(ElementLanguage elementLanguage) throws SAXException { AttributesImpl atts = new AttributesImpl(); //atts.addAttribute ("", key, "", "", value); - atts.addAttribute ("", "language", "", "", elementLanguage.getLanguageConfiguration().getLanguage()); - atts.addAttribute ("", "languageVersion", "", "", elementLanguage.getLanguageConfiguration().getLanguageVersion()); + atts.addAttribute ("", "language", "", "", elementLanguage.getLanguage().getLanguageName()); + atts.addAttribute ("", "languageVersion", "", "", elementLanguage.getLanguage().getLanguageVersion()); atts.addAttribute ("", "className", "", "", elementLanguage.getClass().getName()+""); - atts.addAttribute ("", "currentX4OPhase", "", "", elementLanguage.getCurrentX4OPhase().name()); + atts.addAttribute ("", "currentX4OPhase", "", "", elementLanguage.getCurrentX4OPhase().getId()); debugWriter.startElement (DEBUG_URI, "printElementLanguage", "", atts); debugWriter.endElement(DEBUG_URI, "printElementLanguage", ""); } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4ODriver.java b/x4o-core/src/main/java/org/x4o/xml/core/X4ODriver.java deleted file mode 100644 index 848da3d..0000000 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4ODriver.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright (c) 2004-2012, Willem Cazander - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.x4o.xml.core; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.logging.Logger; - -import javax.xml.parsers.ParserConfigurationException; - -import org.x4o.xml.core.config.X4OLanguageConfiguration; -import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.sax.XMLWriter; - -import org.xml.sax.SAXException; -import org.xml.sax.ext.DefaultHandler2; -import org.xml.sax.helpers.AttributesImpl; - -/** - * X4ODriver can load language and parse files - * - * @author Willem Cazander - * @version 1.0 Aug 9, 2012 - */ -public class X4ODriver implements X4OParserSupport { - - /** The logger to log to. */ - private Logger logger = null; - - /** The ElementLanguage which hold all language config. */ - protected ElementLanguage elementLanguage = null; - - /** Keep is here for if we want to reuse the parser instance. */ - private X4OPhaseManager phaseManager = null; - - //private X4OPhaseHandler configOptionalPhase = null; - - /** Defines the default version if none is defined. */ - public final static String DEFAULT_LANGUAGE_VERSION = "1.0"; - - /** - * Creates an X4ODriver for this config - * - * @param languageConfig The X4O languageConfig to create this parser for.. - */ - public X4ODriver(X4OLanguageConfiguration languageConfig) { - if (languageConfig==null) { - throw new NullPointerException("Can't start with null X4OLanguageConfiguration"); - } - elementLanguage = languageConfig.createElementLanguage(); // store also language config - logger = Logger.getLogger(X4OParser.class.getName()); - logger.fine("Creating X4O driver for language: "+languageConfig.getLanguage()); - } - - /** - * Returns the ElementLanguage - * @return returns the ElementLanguage. - */ - public ElementLanguage getElementLanguage() { - return elementLanguage; - } - - /** - * Creates and configs an X4OPhaseManager to parse a language. - * - * @return An configured X4OPhaseManager - * @throws X4OPhaseException - */ - protected X4OPhaseManager createX4OPhaseManager() throws X4OPhaseException { - - X4OPhaseHandlerFactory factory = new X4OPhaseHandlerFactory(elementLanguage); - X4OPhaseManager manager = new X4OPhaseManager(elementLanguage); - - // main startup - //manager.addX4OPhaseHandler(factory.createContextsPhase()); - manager.addX4OPhaseHandler(factory.startupX4OPhase()); - manager.addX4OPhaseHandler(factory.createLanguagePhase()); - manager.addX4OPhaseHandler(factory.createLanguageSiblingsPhase()); - manager.addX4OPhaseHandler(factory.parseSAXStreamPhase()); - - // inject and opt phase - manager.addX4OPhaseHandler(factory.configGlobalElBeansPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - /* - if (configOptionalPhase!=null) { - if (X4OPhase.configOptionalPhase.equals(configOptionalPhase.getX4OPhase())==false) { - throw new X4OPhaseException(configOptionalPhase,new IllegalStateException("createConfigOptionalPhase() did not return an X4OPhase.configOptionalPhase x4o phase.")); - } - manager.addX4OPhaseHandler(configOptionalPhase); - } - */ - - // meta start point - manager.addX4OPhaseHandler(factory.startX4OPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - // config - manager.addX4OPhaseHandler(factory.configElementPhase()); - manager.addX4OPhaseHandler(factory.configElementInterfacePhase()); - manager.addX4OPhaseHandler(factory.configGlobalElementPhase()); - manager.addX4OPhaseHandler(factory.configGlobalAttributePhase()); - - // run all attribute events - manager.addX4OPhaseHandler(factory.runAttributesPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - // templating - manager.addX4OPhaseHandler(factory.fillTemplatingPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - // transforming - manager.addX4OPhaseHandler(factory.transformPhase()); - manager.addX4OPhaseHandler(factory.runDirtyElementPhase(manager)); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - // binding elements - manager.addX4OPhaseHandler(factory.bindElementPhase()); - - // runing and releasing - manager.addX4OPhaseHandler(factory.runPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - manager.addX4OPhaseHandler(factory.runDirtyElementLastPhase(manager)); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - // after release phase Element Tree is not avible anymore - manager.addX4OPhaseHandler(factory.releasePhase()); - - // Add debug phase listener to all phases - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { - for (X4OPhaseHandler h:manager.getPhases()) { - h.addPhaseListener(elementLanguage.getLanguageConfiguration().getX4ODebugWriter().createDebugX4OPhaseListener()); - } - } - - // We are done we the manager - return manager; - } - - protected X4OPhaseManager createX4OPhaseManagerSupport() throws X4OPhaseException { - X4OPhaseHandlerFactory factory = new X4OPhaseHandlerFactory(elementLanguage); - X4OPhaseManager manager = new X4OPhaseManager(elementLanguage); - manager.addX4OPhaseHandler(factory.createLanguagePhase()); - manager.addX4OPhaseHandler(factory.createLanguageSiblingsPhase()); - - manager.addX4OPhaseHandler(factory.configGlobalElBeansPhase()); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} - - return manager; - } - - /** - * Parses the input stream as a X4O document. - */ - public void parseInput() throws ParserConfigurationException,SAXException,IOException { - if (elementLanguage.getLanguageConfiguration().getLanguage()==null) { - throw new ParserConfigurationException("parserConfig is broken getLanguage() returns null."); - } - - // init debugWriter if enabled - boolean startedDebugWriter = false; - Object debugOutputHandler = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.DEBUG_OUTPUT_HANDLER); - Object debugOutputStream = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.DEBUG_OUTPUT_STREAM); - if (elementLanguage.getLanguageConfiguration().getX4ODebugWriter()==null) { - DefaultHandler2 xmlDebugWriter = null; - if (debugOutputHandler instanceof DefaultHandler2) { - xmlDebugWriter = (DefaultHandler2)debugOutputHandler; - } else if (debugOutputStream instanceof OutputStream) { - xmlDebugWriter = new XMLWriter((OutputStream)debugOutputStream); - } - if (xmlDebugWriter!=null) { - xmlDebugWriter.startDocument(); - xmlDebugWriter.startPrefixMapping("debug", X4ODebugWriter.DEBUG_URI); - X4ODebugWriter debugWriter = new X4ODebugWriter(xmlDebugWriter); - elementLanguage.getLanguageConfiguration().setX4ODebugWriter(debugWriter); - startedDebugWriter = true; - } - } - - // debug language - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { - AttributesImpl atts = new AttributesImpl(); - atts.addAttribute ("", "language", "", "", elementLanguage.getLanguageConfiguration().getLanguage()); - atts.addAttribute ("", "currentTimeMillis", "", "", System.currentTimeMillis()+""); - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().startElement(X4ODebugWriter.DEBUG_URI, "X4ODriver", "", atts); - } - - // start parsing language - try { - if (phaseManager==null) { - phaseManager = createX4OPhaseManager(); - } - phaseManager.runPhases(); - } catch (Exception e) { - - // also debug exceptions - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { - try { - AttributesImpl atts = new AttributesImpl(); - atts.addAttribute ("", "message", "", "", e.getMessage()); - if (e instanceof X4OPhaseException) { - atts.addAttribute ("", "phase", "", "", ((X4OPhaseException)e).getX4OPhaseHandler().getX4OPhase().name()); - } - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().startElement(X4ODebugWriter.DEBUG_URI, "exceptionStackTrace", "", atts); - StringWriter writer = new StringWriter(); - PrintWriter printer = new PrintWriter(writer); - printer.append('\n'); - if (e.getCause()==null) { - e.printStackTrace(printer); - } else { - e.getCause().printStackTrace(printer); - } - char[] stack = writer.getBuffer().toString().toCharArray(); - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().characters(stack, 0, stack.length); - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "exceptionStackTrace", ""); - } catch (Exception ee) { - ee.printStackTrace(); - } - } - - // unwrap exception - if (e.getCause() instanceof ParserConfigurationException) { - throw (ParserConfigurationException)e.getCause(); - } - if (e.getCause() instanceof SAXException) { - throw (SAXException)e.getCause(); - } - if (e.getCause() instanceof IOException) { - throw (IOException)e.getCause(); - } - if (e.getCause()==null) { - throw new SAXException(e); - } else { - throw new SAXException((Exception)e.getCause()); - } - } finally { - // close all our resources. - //if (inputStream!=null) { - // inputStream.close(); - //} - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "X4ODriver", ""); - } - if (startedDebugWriter && elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().endPrefixMapping("debug"); - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().getDebugWriter().endDocument(); - if (debugOutputStream instanceof OutputStream) { - OutputStream outputStream = (OutputStream)debugOutputStream; - outputStream.flush(); - outputStream.close(); // need this here ? - } - } - } - } - - - - /** - * Loads the language and returns the ElementLanguage. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() - */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - try { - X4OPhaseManager loadLanguageManager = createX4OPhaseManagerSupport(); - loadLanguageManager.runPhases(); - return elementLanguage; - } catch (Exception e) { - throw new X4OParserSupportException(e); - } - } - - /** - * Run a manual release phase to clean the parsing object tree. - * - * @throws X4OPhaseException - */ - public void doReleasePhaseManual() throws X4OPhaseException { - if (phaseManager==null) { - throw new IllegalStateException("Can't release with null phaseManager."); - } - phaseManager.doReleasePhaseManual(); - } - - /** - * Sets an X4O Language property. - * @param key The key of the property to set. - * @param value The vlue of the property to set. - */ - public void setProperty(String key,Object value) { - if (phaseManager!=null) { - throw new IllegalStateException("Can't set property after phaseManager is created."); - } - elementLanguage.getLanguageConfiguration().setLanguageProperty(X4OLanguageProperty.valueByUri(key), value); - } - - /** - * Returns the value an X4O Language property. - * @param key The key of the property to get the value for. - * @return Returns null or the value of the property. - */ - public Object getProperty(String key) { - return elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.valueByUri(key)); - } -} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OEntityResolver.java b/x4o-core/src/main/java/org/x4o/xml/core/X4OEntityResolver.java index 6076879..6139230 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OEntityResolver.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/X4OEntityResolver.java @@ -56,24 +56,24 @@ public class X4OEntityResolver implements EntityResolver { private Logger logger = null; private URL basePath = null; - private ElementLanguage elementLanguage = null; + private ElementLanguage elementContext = null; private Map schemaResources = null; private Map schemaPathResources = null; /** * Creates an X4OEntityResolver for a language. - * @param elementLanguage The x4o language to resolve entities for. + * @param elementContext The x4o language to resolve entities for. */ - protected X4OEntityResolver(ElementLanguage elementLanguage) { - if (elementLanguage==null) { - throw new NullPointerException("Can't provide entities with null ElementLanguage."); + public X4OEntityResolver(ElementLanguage elementContext) { + if (elementContext==null) { + throw new NullPointerException("Can't provide entities with null elementContext."); } this.logger=Logger.getLogger(X4OEntityResolver.class.getName()); - this.elementLanguage=elementLanguage; - this.basePath=(URL)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_BASE_PATH); + this.elementContext=elementContext; + this.basePath=(URL)elementContext.getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_BASE_PATH); this.schemaResources=new HashMap(20); this.schemaPathResources=new HashMap(20); - for (ElementLanguageModule mod:elementLanguage.getElementLanguageModules()) { + for (ElementLanguageModule mod:elementContext.getLanguage().getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { if (ns.getSchemaUri()==null) { continue; @@ -82,15 +82,15 @@ public class X4OEntityResolver implements EntityResolver { continue; } StringBuffer buf = new StringBuffer(30); - buf.append(elementLanguage.getLanguageConfiguration().getLanguageResourcePathPrefix()); + buf.append(elementContext.getLanguage().getLanguageConfiguration().getLanguageResourcePathPrefix()); buf.append('/'); - buf.append(elementLanguage.getLanguageConfiguration().getLanguage()); + buf.append(elementContext.getLanguage().getLanguageName()); buf.append('/'); buf.append(ns.getSchemaResource()); schemaResources.put( ns.getSchemaUri(), buf.toString() ); buf = new StringBuffer(30); - buf.append(elementLanguage.getLanguageConfiguration().getLanguage()); + buf.append(elementContext.getLanguage().getLanguageName()); buf.append(File.separatorChar); buf.append(ns.getSchemaResource()); schemaPathResources.put( ns.getSchemaUri(), buf.toString() ); @@ -110,7 +110,7 @@ public class X4OEntityResolver implements EntityResolver { logger.finer("Fetch sysId: "+systemId+" pubId: "+publicId); // Check if other resolver has resource - EntityResolver resolver = (EntityResolver)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER); + EntityResolver resolver = (EntityResolver)elementContext.getLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER); if (resolver!=null) { InputSource result = resolver.resolveEntity(publicId, systemId); if (result!=null) { @@ -120,7 +120,7 @@ public class X4OEntityResolver implements EntityResolver { // Check if we have it on user defined schema base path if (schemaPathResources.containsKey(systemId)) { - File schemaBasePath = (File)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.VALIDATION_SCHEMA_PATH); + File schemaBasePath = (File)elementContext.getLanguageProperty(X4OLanguageProperty.VALIDATION_SCHEMA_PATH); if (schemaBasePath!=null && schemaBasePath.exists()) { String schemeResource = schemaResources.get(systemId); File schemaFile = new File(schemaBasePath.getAbsolutePath()+File.separatorChar+schemeResource); diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OErrorHandler.java b/x4o-core/src/main/java/org/x4o/xml/core/X4OErrorHandler.java index 6b48511..55b83dc 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OErrorHandler.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/X4OErrorHandler.java @@ -24,8 +24,8 @@ package org.x4o.xml.core; import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementException; +import org.x4o.xml.element.ElementLanguage; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; @@ -38,31 +38,31 @@ import org.xml.sax.SAXParseException; */ public class X4OErrorHandler implements ErrorHandler { - private ElementLanguage elementLanguage = null; + private ElementLanguage elementContext = null; private ErrorHandler errorHandler = null; /** * Construct a new SAXErrorPrinter - * @param elementLanguage The elementLanguage to get errors to. + * @param language The language to get errors to. */ - public X4OErrorHandler(ElementLanguage elementLanguage) { - if (elementLanguage==null) { - throw new NullPointerException("Can't debug and proxy errors with null elementLanguage."); + public X4OErrorHandler(ElementLanguage elementContext) { + if (elementContext==null) { + throw new NullPointerException("Can't debug and proxy errors with null elementContext."); } - this.elementLanguage=elementLanguage; - this.errorHandler=(ErrorHandler)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.CONFIG_ERROR_HANDLER); + this.elementContext=elementContext; + this.errorHandler=(ErrorHandler)elementContext.getLanguageProperty(X4OLanguageProperty.CONFIG_ERROR_HANDLER); } /** * Prints the error message to debug output. */ private void printError(boolean isError, SAXParseException exception) throws SAXException { - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()==false) { + if (elementContext.hasX4ODebugWriter()==false) { return; } String message = printErrorString(isError,exception); try { - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().debugPhaseMessage(message, X4OErrorHandler.class); + elementContext.getX4ODebugWriter().debugPhaseMessage(message, X4OErrorHandler.class); } catch (ElementException e) { throw new SAXException(e); } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OParser.java b/x4o-core/src/main/java/org/x4o/xml/core/X4OParser.java deleted file mode 100644 index ed02e62..0000000 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OParser.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 2004-2012, Willem Cazander - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.x4o.xml.core; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.parsers.ParserConfigurationException; - -import org.x4o.xml.core.config.X4OLanguageConfiguration; -import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.impl.config.DefaultX4OLanguageConfiguration; -import org.x4o.xml.sax.AbstractXMLParser; -import org.xml.sax.SAXException; - -/** - * This is the starting point of the XML X4O parsing. - * - * @author Willem Cazander - * @version 1.0 Aug 11, 2005 - */ -public class X4OParser extends AbstractXMLParser implements X4OParserSupport { - - private X4ODriver driver = null; - - /** - * Creates an X4OParser object. - * - * @param language The X4O language to create this parser for.. - */ - public X4OParser(String language) { - this(language,X4ODriver.DEFAULT_LANGUAGE_VERSION); - } - - public X4OParser(String language,String languageVersion) { - this(new DefaultX4OLanguageConfiguration(language,languageVersion)); - } - - protected X4OParser(X4OLanguageConfiguration config) { - this(new X4ODriver(config)); - } - - protected X4OParser(X4ODriver driver) { - if (driver==null) { - throw new NullPointerException("Can't start X4OParser with null X4ODriver."); - } - this.driver = driver; - } - - protected X4ODriver getDriver() { - return driver; - } - - /** - * @see org.x4o.xml.sax.AbstractXMLParser#parse(java.io.InputStream,java.lang.String,java.net.URL) - */ - @Override - public void parse(InputStream input,String systemId,URL basePath) throws ParserConfigurationException,SAXException, IOException { - driver.setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_STREAM, input); - driver.setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_SYSTEM_ID, systemId); - driver.setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_BASE_PATH, basePath); - driver.parseInput(); - } - - /** - * Run a manual release phase to clean the parsing object tree. - * - * @throws X4OPhaseException - */ - public void doReleasePhaseManual() throws X4OPhaseException { - driver.doReleasePhaseManual(); - } - - /** - * Sets an X4O Language property. - * @param key The key of the property to set. - * @param value The vlue of the property to set. - */ - public void setProperty(String key,Object value) { - driver.setProperty(key, value); - } - - /** - * Returns the value an X4O Language property. - * @param key The key of the property to get the value for. - * @return Returns null or the value of the property. - */ - public Object getProperty(String key) { - return driver.getProperty(key); - } - - /** - * Loads the support ElementLanguage from the driver. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() - */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - return driver.loadElementLanguageSupport(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected void addELBeanInstance(String name,Object bean) { - if (name==null) { - throw new NullPointerException("Can't add null name."); - } - if (name.length()==0) { - throw new NullPointerException("Can't add empty name."); - } - if (bean==null) { - throw new NullPointerException("Can't add null bean."); - } - Map map = (Map)getProperty(X4OLanguagePropertyKeys.EL_BEAN_INSTANCE_MAP); - if (map==null) { - map = new HashMap(20); - setProperty(X4OLanguagePropertyKeys.EL_BEAN_INSTANCE_MAP, map); - } - map.put(name,bean); - } -} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhase.java b/x4o-core/src/main/java/org/x4o/xml/core/X4OPhase.java deleted file mode 100644 index f941ae5..0000000 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhase.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2004-2012, Willem Cazander - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.x4o.xml.core; - -/** - * Defines the different phases of the x4o xml parser. - * - * @author Willem Cazander - * @version 1.0 Sep 1, 2008 - */ -public enum X4OPhase { - - /** Defines this meta startup phase. */ - startupX4OPhase(true), - - /** Load all meta info of the language we are creating. */ - createLanguagePhase(true), - - /** Load all siblings languages. */ - createLanguageSiblingsPhase(true), - - /** Parse the xml from sax events. */ - parseSAXStreamPhase(true), - - /** Optional extra config phase for injecting bean instances into the EL context. */ - configGlobalElBeansPhase(true), - - /** emty meta phase to refer to that sax is ready and element s are waiting for processing. */ - startX4OPhase(true), - - /** re runnable phases which config xml to beans and binds them together. */ - configElementPhase, - configElementInterfacePhase, - configGlobalElementPhase, - configGlobalAttributePhase, - - /** Fill the bean attributes from the Element xml attributes. */ - runAttributesPhase, - - /** Fill in the x4o templating objects. */ - fillTemplatingPhase, - - /** transform phase , modifies the Element Tree. */ - transformPhase, - - /** Run the phases which needs to be runned again from a phase. */ - runDirtyElementPhase(true), - - /** Binds objects together */ - bindElementPhase, - - /** Run action stuff, we are ready with it. */ - runPhase(true), - - /** Rerun all needed phases for all element that requested it. */ - runDirtyElementLastPhase, - - /** Releases all Elements, which clears attributes and childeren etc. */ - releasePhase(true), - - /** write all phases and stuff to debug sax stream. */ - debugPhase; - - /** Defines which phase we start, when context is created. */ - public static final X4OPhase FIRST_PHASE = startupX4OPhase; - - /** The order in which the phases are executed */ - static final X4OPhase[] PHASE_ORDER = { startupX4OPhase, - createLanguagePhase,createLanguageSiblingsPhase, - parseSAXStreamPhase,configGlobalElBeansPhase, - startX4OPhase, - configElementPhase,configElementInterfacePhase,configGlobalElementPhase, - configGlobalAttributePhase,runAttributesPhase,fillTemplatingPhase, - transformPhase,runDirtyElementPhase,bindElementPhase, - runPhase,runDirtyElementLastPhase, - releasePhase - }; - - /** Boolean indicating that this phase only may be run'ed once. */ - private boolean runOnce = false; - - /** - * Creates an X4O Phase. - */ - private X4OPhase() { - } - - /** - * Creates an X4O Phase - * @param runOnce Flag indicating that this phase is runnable multiple times. - */ - private X4OPhase(boolean runOnce) { - this.runOnce=runOnce; - } - - /** - * Returns a flag indicating that this phase is runnable multiple times. - * @return True if phase is restricted to run once. - */ - public boolean isRunOnce() { - return runOnce; - } -} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OTagHandler.java b/x4o-core/src/main/java/org/x4o/xml/core/X4OTagHandler.java index e0deb86..c4298fb 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OTagHandler.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/X4OTagHandler.java @@ -30,7 +30,7 @@ import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementException; import org.x4o.xml.element.ElementNamespaceContext; import org.x4o.xml.element.ElementNamespaceInstanceProvider; -import org.x4o.xml.sax.AttributeMap; +import org.x4o.xml.io.sax.AttributeMap; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; @@ -103,9 +103,9 @@ public class X4OTagHandler extends DefaultHandler2 { if ("http://www.w3.org/2001/XInclude".equals(namespaceUri)) { return; // skip xinclude ns. } - ElementNamespaceContext enc = elementLanguage.findElementNamespaceContext(namespaceUri); + ElementNamespaceContext enc = elementLanguage.getLanguage().findElementNamespaceContext(namespaceUri); if (enc==null) { - throw new SAXException("Can't find namespace uri: "+namespaceUri+" in language: "+elementLanguage.getLanguageConfiguration().getLanguage()); + throw new SAXException("Can't find namespace uri: "+namespaceUri+" in language: "+elementLanguage.getLanguage().getLanguageName()); } enc.setPrefixMapping(prefix); } @@ -122,13 +122,13 @@ public class X4OTagHandler extends DefaultHandler2 { overrideSaxHandler.startElement(namespaceUri, tag, qName, attributes); return; } - ElementNamespaceContext enc = elementLanguage.findElementNamespaceContext(namespaceUri); + ElementNamespaceContext enc = elementLanguage.getLanguage().findElementNamespaceContext(namespaceUri); if (enc==null) { if ("".equals(namespaceUri)) { - String configEmptryUri = (String)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_EMPTY_NAMESPACE_URI); + String configEmptryUri = (String)elementLanguage.getLanguageProperty(X4OLanguageProperty.INPUT_EMPTY_NAMESPACE_URI); if (configEmptryUri!=null) { namespaceUri = configEmptryUri; - enc = elementLanguage.findElementNamespaceContext(namespaceUri); + enc = elementLanguage.getLanguage().findElementNamespaceContext(namespaceUri); } if (enc==null) { throw new SAXParseException("No ElementNamespaceContext found for empty namespace.",locator); @@ -143,7 +143,7 @@ public class X4OTagHandler extends DefaultHandler2 { ElementNamespaceInstanceProvider eip = enc.getElementNamespaceInstanceProvider(); Element element = null; try { - element = eip.createElementInstance(tag); + element = eip.createElementInstance(elementLanguage,tag); } catch (Exception e) { throw new SAXParseException("Error while creating element: "+e.getMessage(),locator,e); } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguage.java b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguage.java new file mode 100644 index 0000000..7b992d7 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguage.java @@ -0,0 +1,167 @@ +package org.x4o.xml.core.config; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Logger; + +import org.x4o.xml.core.phase.X4OPhaseManager; +import org.x4o.xml.element.ElementBindingHandler; +import org.x4o.xml.element.ElementInterface; +import org.x4o.xml.element.ElementLanguageModule; +import org.x4o.xml.element.ElementNamespaceContext; + +public class DefaultX4OLanguage implements X4OLanguageLocal { + + private Logger logger = null; + private X4OLanguageConfiguration languageConfiguration = null; + private List elementLanguageModules = null; + private String languageName = null; + private String languageVersion = null; + private X4OPhaseManager phaseManager = null; + + public DefaultX4OLanguage(X4OLanguageConfiguration languageConfiguration,X4OPhaseManager phaseManager,String languageName,String languageVersion) { + logger = Logger.getLogger(DefaultX4OLanguage.class.getName()); + elementLanguageModules = new ArrayList(20); + this.languageConfiguration=languageConfiguration; + this.languageName=languageName; + this.languageVersion=languageVersion; + this.phaseManager=phaseManager; + } + + /** + * @see org.x4o.xml.core.config.X4OLanguage#getLanguageName() + */ + public String getLanguageName() { + return languageName; + } + + /** + * @see org.x4o.xml.core.config.X4OLanguage#getLanguageVersion() + */ + public String getLanguageVersion() { + return languageVersion; + } + + /** + * @see org.x4o.xml.core.config.X4OLanguage#getPhaseManager() + */ + public X4OPhaseManager getPhaseManager() { + return phaseManager; + } + + /** + * @return the languageConfiguration + */ + public X4OLanguageConfiguration getLanguageConfiguration() { + return languageConfiguration; + } + + /* + * @param languageConfiguration the languageConfiguration to set + + public void setLanguageConfiguration() { + this.languageConfiguration = languageConfiguration; + }*/ + + /** + * @see org.x4o.xml.element.ElementLanguage#addElementLanguageModule(org.x4o.xml.element.ElementLanguageModule) + */ + public void addElementLanguageModule(ElementLanguageModule elementLanguageModule) { + if (elementLanguageModule.getId()==null) { + throw new NullPointerException("Can't add module without id."); + } + elementLanguageModules.add(elementLanguageModule); + } + + /** + * @see org.x4o.xml.element.ElementLanguage#getElementLanguageModules() + */ + public List getElementLanguageModules() { + return elementLanguageModules; + } + + + /** + * @see org.x4o.xml.element.ElementLanguage#findElementBindingHandlers(java.lang.Object,java.lang.Object) + */ + public List findElementBindingHandlers(Object parent,Object child) { + List result = new ArrayList(50); + for (int i=0;i result,List checkList) { + for (ElementBindingHandler binding:checkList) { + boolean parentBind = false; + if (parent instanceof Class) { + parentBind = binding.getBindParentClass().isAssignableFrom((Class)parent); + } else { + parentBind = binding.getBindParentClass().isInstance(parent); + } + if (parentBind==false) { + continue; + } + boolean childBind = false; + for (Class childClass:binding.getBindChildClasses()) { + if (child instanceof Class && childClass.isAssignableFrom((Class)child)) { + childBind=true; + break; + } else if (childClass.isInstance(child)) { + childBind=true; + break; + } + } + if (parentBind & childBind) { + result.add(binding); + } + } + } + + /** + * @see org.x4o.xml.element.ElementLanguage#findElementInterfaces(java.lang.Object) + */ + public List findElementInterfaces(Object elementObject) { + if (elementObject==null) { + throw new NullPointerException("Can't search for null object."); + } + List result = new ArrayList(50); + for (int i=0;i eClass = ei.getInterfaceClass(); + logger.finest("Checking interface handler: "+ei+" for class: "+eClass); + if (elementObject instanceof Class && eClass.isAssignableFrom((Class)elementObject)) { + logger.finer("Found interface match from class; "+elementObject); + result.add(ei); + } else if (eClass.isInstance(elementObject)) { + logger.finer("Found interface match from object; "+elementObject); + result.add(ei); + } + } + } + return result; + } + + /** + * @see org.x4o.xml.element.ElementLanguage#findElementNamespaceContext(java.lang.String) + */ + public ElementNamespaceContext findElementNamespaceContext(String namespaceUri) { + + // TODO: refactor so no search for every tag !! + ElementNamespaceContext result = null; + for (int i=0;i languageProperties; - - public DefaultX4OLanguageConfiguration(String language,String languageVersion) { - if (language==null) { - throw new NullPointerException("language may not be null"); - } - if (language.length()==0) { - throw new IllegalArgumentException("language may not be empty"); - } - if (languageVersion==null) { - throw new NullPointerException("languageVersion may not be null"); - } - if (languageVersion.length()==0) { - throw new IllegalArgumentException("languageVersion may not be empty"); - } - languageProperties = new HashMap(20); - languageProperties.put(X4OLanguageProperty.LANGUAGE_NAME, language); - languageProperties.put(X4OLanguageProperty.LANGUAGE_VERSION, languageVersion); - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguage() - */ - public String getLanguage() { - return (String)languageProperties.get(X4OLanguageProperty.LANGUAGE_NAME); - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguageVersion() - */ - public String getLanguageVersion() { - return (String)languageProperties.get(X4OLanguageProperty.LANGUAGE_VERSION); + public DefaultX4OLanguageConfiguration() { } /** @@ -112,45 +77,6 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration public String getLanguageResourceModulesFileName() { return X4OLanguageConfiguration.DEFAULT_LANG_MODULES_FILE; } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguageProperty(org.x4o.xml.core.config.X4OLanguageProperty) - */ - public Object getLanguageProperty(X4OLanguageProperty property) { - return languageProperties.get(property); - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#setLanguageProperty(org.x4o.xml.core.config.X4OLanguageProperty, java.lang.Object) - */ - public void setLanguageProperty(X4OLanguageProperty property, Object value) { - if (property.isValueValid(value)==false) { - throw new IllegalArgumentException("Now allowed to set value: "+value+" in property: "+property.name()); - } - languageProperties.put(property, value); - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguagePropertyBoolean(org.x4o.xml.core.config.X4OLanguageProperty) - */ - public boolean getLanguagePropertyBoolean(X4OLanguageProperty property) { - Object value = getLanguageProperty(property); - if (value instanceof Boolean) { - return (Boolean)value; - } - return (Boolean)property.getDefaultValue(); - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguagePropertyInteger(org.x4o.xml.core.config.X4OLanguageProperty) - */ - public int getLanguagePropertyInteger(X4OLanguageProperty property) { - Object value = getLanguageProperty(property); - if (value instanceof Integer) { - return (Integer)value; - } - return (Integer)property.getDefaultValue(); - } /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getDefaultElementNamespaceContext() @@ -260,19 +186,24 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#createElementLanguage() */ - public ElementLanguage createElementLanguage() { - return configElementLanguage(new DefaultElementLanguage()); + public ElementLanguage createElementLanguage(X4ODriver driver) { + String v = driver.DEFAULT_LANGUAGE_VERSION; // TODO:fixme + return configElementLanguage(new DefaultElementLanguage(driver.createLanguage(v),v),driver); } - protected ElementLanguage configElementLanguage(ElementLanguage elementLanguage) { + protected ElementLanguage configElementLanguage(ElementLanguage elementLanguage,X4ODriver driver) { if ((elementLanguage instanceof ElementLanguageLocal)==false) { throw new RuntimeException("Can't init ElementLanguage which has not ElementLanguageLocal interface obj: "+elementLanguage); } ElementLanguageLocal contextInit = (ElementLanguageLocal)elementLanguage; - contextInit.setLanguageConfiguration(this); + //contextInit.setLanguageConfiguration(this); + for (String key:driver.getGlobalPropertyKeys()) { + Object value = driver.getGlobalProperty(key); + contextInit.setLanguageProperty(key, value); + } if (contextInit.getExpressionFactory()==null) { - contextInit.setExpressionFactory(configExpressionFactory()); + contextInit.setExpressionFactory(configExpressionFactory(contextInit)); } if (contextInit.getELContext()==null) { contextInit.setELContext(new X4OELContext()); @@ -290,8 +221,8 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration return elementLanguage; } - protected ExpressionFactory configExpressionFactory() { - ExpressionFactory factory = (ExpressionFactory)getLanguageProperty(X4OLanguageProperty.EL_FACTORY_INSTANCE); + protected ExpressionFactory configExpressionFactory(ElementLanguage elementContext) { + ExpressionFactory factory = (ExpressionFactory)elementContext.getLanguageProperty(X4OLanguageProperty.EL_FACTORY_INSTANCE); if (factory!=null) { return factory; } @@ -313,7 +244,7 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getSAXParserProperties() */ - public Map getSAXParserProperties() { + public Map getSAXParserProperties(ElementLanguage elementContext) { Map saxParserProperties = new HashMap(1); return saxParserProperties; } @@ -321,16 +252,16 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getSAXParserPropertiesOptional() */ - public Map getSAXParserPropertiesOptional() { + public Map getSAXParserPropertiesOptional(ElementLanguage elementContext) { Map saxParserProperties = new HashMap(1); - saxParserProperties.put("http://apache.org/xml/properties/input-buffer-size",getLanguagePropertyInteger(X4OLanguageProperty.INPUT_BUFFER_SIZE)); // Increase buffer to 8KB + saxParserProperties.put("http://apache.org/xml/properties/input-buffer-size",elementContext.getLanguagePropertyInteger(X4OLanguageProperty.INPUT_BUFFER_SIZE)); // Increase buffer to 8KB return saxParserProperties; } /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getSAXParserFeatures() */ - public Map getSAXParserFeatures() { + public Map getSAXParserFeatures(ElementLanguage elementContext) { // see example: http://xerces.apache.org/xerces2-j/features.html Map saxParserFeatures = new HashMap(20); @@ -352,12 +283,12 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration boolean validation = false; boolean validationXsd = false; - if (EldParser.ELD_LANGUAGE.equals(getLanguage())) { - validation = getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_ELD); - validationXsd = getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_ELD_XSD); + if (EldDriver.LANGUAGE_NAME.equals(elementContext.getLanguage().getLanguageName())) { + validation = elementContext.getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_ELD); + validationXsd = elementContext.getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_ELD_XSD); } else { - validation = getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_INPUT); - validationXsd = getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_INPUT_XSD); + validation = elementContext.getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_INPUT); + validationXsd = elementContext.getLanguagePropertyBoolean(X4OLanguageProperty.VALIDATION_INPUT_XSD); } if (validation) { saxParserFeatures.put("http://xml.org/sax/features/validation", true); // Validate the document and report validity errors. @@ -379,7 +310,7 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getSAXParserFeaturesOptional() */ - public Map getSAXParserFeaturesOptional() { + public Map getSAXParserFeaturesOptional(ElementLanguage elementContext) { Map saxParserFeatures = new HashMap(20); // Make Sax Impl more strict. @@ -403,7 +334,7 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration /** * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getSAXParserFeaturesRequired() */ - public List getSAXParserFeaturesRequired() { + public List getSAXParserFeaturesRequired(ElementLanguage elementContext) { List result = new ArrayList(5); result.add("http://xml.org/sax/features/use-attributes2"); // Attributes objects passed by the parser are ext.Attributes2 interface. result.add("http://xml.org/sax/features/use-locator2"); // Locator objects passed by the parser are org.xml.sax.ext.Locator2 interface. @@ -411,24 +342,4 @@ public class DefaultX4OLanguageConfiguration implements X4OLanguageConfiguration return result; } - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getX4ODebugWriter() - */ - public X4ODebugWriter getX4ODebugWriter() { - return debugWriter; - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#hasX4ODebugWriter() - */ - public boolean hasX4ODebugWriter() { - return debugWriter!=null; - } - - /** - * @see org.x4o.xml.core.config.X4OLanguageConfiguration#setX4ODebugWriter(org.x4o.xml.core.X4ODebugWriter) - */ - public void setX4ODebugWriter(X4ODebugWriter debugWriter) { - this.debugWriter=debugWriter; - } } diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageLoader.java b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageLoader.java similarity index 79% rename from x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageLoader.java rename to x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageLoader.java index 1d270ed..897a3eb 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageLoader.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageLoader.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.config; +package org.x4o.xml.core.config; import java.io.IOException; import java.io.InputStream; @@ -33,14 +33,8 @@ import java.util.List; import java.util.Map; import java.util.logging.Logger; -import org.x4o.xml.core.config.X4OLanguageClassLoader; -import org.x4o.xml.core.config.X4OLanguageLoader; -import org.x4o.xml.core.config.X4OLanguageLoaderException; -import org.x4o.xml.core.config.X4OLanguageVersionFilter; -import org.x4o.xml.eld.EldParser; +import org.x4o.xml.eld.EldDriver; import org.x4o.xml.eld.EldModuleLoader; -import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.element.ElementException; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementLanguageModuleLoader; import org.x4o.xml.element.ElementLanguageModuleLoaderSibling; @@ -75,26 +69,28 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { * @param elementLanguage The elementLanguage we are loading. * @param message The message to log to the debug output. */ - private void logMessage(ElementLanguage elementLanguage,String message) { + private void logMessage(X4OLanguage language,String message) { logger.finest(message); - if (elementLanguage.getLanguageConfiguration().hasX4ODebugWriter()) { + /* + if (language.getLanguageConfiguration().hasX4ODebugWriter()) { try { - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().debugPhaseMessage(message, this.getClass()); + language.getLanguageConfiguration().getX4ODebugWriter().debugPhaseMessage(message, this.getClass()); } catch (ElementException e) { throw new RuntimeException(e); } } + */ } /** * @see org.x4o.xml.core.config.X4OLanguageLoader#loadLanguage(org.x4o.xml.element.ElementLanguage, java.lang.String, java.lang.String) */ - public void loadLanguage(ElementLanguage elementLanguage, String language,String languageVersion) throws X4OLanguageLoaderException { + public void loadLanguage(X4OLanguageLocal languageLocal, String language,String languageVersion) throws X4OLanguageLoaderException { try { logger.finer("Loading all modules for language: "+language); - loadLanguageModules(elementLanguage,language); + loadLanguageModules(languageLocal,language); - X4OLanguageVersionFilter lvf = (X4OLanguageVersionFilter)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultX4OLanguageVersionFilter()); + X4OLanguageVersionFilter lvf = (X4OLanguageVersionFilter)X4OLanguageClassLoader.newInstance(languageLocal.getLanguageConfiguration().getDefaultX4OLanguageVersionFilter()); for (Map> map:modulesAll) { List versions = new ArrayList(map.keySet()); @@ -110,10 +106,10 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { for (String key:modules.keySet()) { String value = modules.get(key); - ElementLanguageModule module = (ElementLanguageModule)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementLanguageModule()); + ElementLanguageModule module = (ElementLanguageModule)X4OLanguageClassLoader.newInstance(languageLocal.getLanguageConfiguration().getDefaultElementLanguageModule()); module.setSourceResource(value); - logMessage(elementLanguage,"Parsing language config key: "+key+" value: "+value); + logMessage(languageLocal,"Parsing language config key: "+key+" value: "+value); if ("module-loader".equals(key)) { try { @@ -123,12 +119,12 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { } } else if ("eld-resource".equals(key)) { - String languagePrefix = elementLanguage.getLanguageConfiguration().getLanguageResourcePathPrefix(); + String languagePrefix = languageLocal.getLanguageConfiguration().getLanguageResourcePathPrefix(); String resource = languagePrefix+"/"+language+"/"+value; - if (language.equals(EldParser.ELD_LANGUAGE)) { - module.setElementLanguageModuleLoader(new EldModuleLoader(resource,true)); + if (language.equals(EldDriver.LANGUAGE_NAME)) { + module.setElementLanguageModuleLoader(new EldModuleLoader(resource,true)); // load cel } else { - module.setElementLanguageModuleLoader(new EldModuleLoader(resource,false)); + module.setElementLanguageModuleLoader(new EldModuleLoader(resource,false)); // load eld } module.setSourceResource(resource); } else if ("elb-resource".equals(key)) { @@ -150,10 +146,10 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { } // mmm start in order ? - logMessage(elementLanguage,"Starting modules: "+module+" for language: "+language); - module.getElementLanguageModuleLoader().loadLanguageModule(elementLanguage, module); + logMessage(languageLocal,"Starting modules: "+module+" for language: "+language); + module.getElementLanguageModuleLoader().loadLanguageModule(languageLocal, module); - elementLanguage.addElementLanguageModule(module); + languageLocal.addElementLanguageModule(module); } } } catch (Exception e1) { @@ -166,28 +162,28 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { * @param elementLanguage The ElementLanguage to load for. * @param language The language to load. */ - protected void loadLanguageModules(ElementLanguage elementLanguage,String language) throws IOException, SAXException { + protected void loadLanguageModules(X4OLanguageLocal languageLocal,String language) throws IOException, SAXException { StringBuilder buf = new StringBuilder(150); - buf.append(elementLanguage.getLanguageConfiguration().getLanguageResourcePathPrefix()); + buf.append(languageLocal.getLanguageConfiguration().getLanguageResourcePathPrefix()); buf.append('/'); buf.append(language); buf.append('/'); buf.append(language); - buf.append(elementLanguage.getLanguageConfiguration().getLanguageResourceModulesFileName()); + buf.append(languageLocal.getLanguageConfiguration().getLanguageResourceModulesFileName()); logger.finer("loading X4O language: "+language); Enumeration e = Thread.currentThread().getContextClassLoader().getResources(buf.toString()); while(e.hasMoreElements()) { URL u = e.nextElement(); - logMessage(elementLanguage,"Loading relative modules: "+u+" for: "+language); - loadModuleXml(u.openStream()); + logMessage(languageLocal,"Loading relative modules: "+u+" for: "+language); + loadModulesXml(u.openStream()); } e = Thread.currentThread().getContextClassLoader().getResources("/"+buf.toString()); while(e.hasMoreElements()) { URL u = e.nextElement(); - logMessage(elementLanguage,"Loading root modules: "+u+" for: "+language); - loadModuleXml(u.openStream()); + logMessage(languageLocal,"Loading root modules: "+u+" for: "+language); + loadModulesXml(u.openStream()); } } @@ -197,7 +193,7 @@ public class DefaultX4OLanguageLoader implements X4OLanguageLoader { * @throws IOException * @throws SAXException */ - private void loadModuleXml(InputStream in) throws IOException, SAXException { + private void loadModulesXml(InputStream in) throws IOException, SAXException { if (in==null) { throw new NullPointerException("Can't parse null input stream"); } diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageVersionFilter.java b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageVersionFilter.java similarity index 96% rename from x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageVersionFilter.java rename to x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageVersionFilter.java index 7952331..d688981 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/config/DefaultX4OLanguageVersionFilter.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/DefaultX4OLanguageVersionFilter.java @@ -21,11 +21,10 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.config; +package org.x4o.xml.core.config; import java.util.List; -import org.x4o.xml.core.config.X4OLanguageVersionFilter; /** * DefaultX4OLanguageVersionFilter makes best filter match attempt. diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguage.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguage.java new file mode 100644 index 0000000..a79f31b --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguage.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.core.config; + +import java.util.List; + +import org.x4o.xml.core.phase.X4OPhaseManager; +import org.x4o.xml.element.ElementBindingHandler; +import org.x4o.xml.element.ElementInterface; +import org.x4o.xml.element.ElementLanguageModule; +import org.x4o.xml.element.ElementNamespaceContext; + +/** + * X4OLanguage hold the defined language. + * + * @author Willem Cazander + * @version 1.0 30 apr 2013 + */ +public interface X4OLanguage { + + /** + * Returns the language for which this ElementLanguage is created. + * @return Returns the language. + */ + String getLanguageName(); + + /** + * @return Returns the languageVersion of the parsing of this language. + */ + String getLanguageVersion(); + + /** + * @return the X4OPhaseManager. + */ + X4OPhaseManager getPhaseManager(); + + /** + * @return the languageConfiguration. + */ + X4OLanguageConfiguration getLanguageConfiguration(); + + /** + * Gets all ElementBindingHandlers. + * @param parent The parent element object or class to search for. + * @param child The parent element object or class to search for. + * @return Returns an List with all ElementBindingHandler for the search pair. + */ + List findElementBindingHandlers(Object parent,Object child); + + /** + * Returns list of ElementInterfaces for an element. + * @param object The element object or class to search for. + * @return The list of elementInterfaces. + */ + List findElementInterfaces(Object object); + + /** + * Returns the namespace context for an namespace uri. + * @param namespaceUri the namespace uri. + * @return The ElementNamespaceContext. + */ + ElementNamespaceContext findElementNamespaceContext(String namespaceUri); + + /** + * @return Returns a list of element language modules in this defined and loaded language. + */ + List getElementLanguageModules(); +} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageConfiguration.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageConfiguration.java index f0c6a49..6fed77a 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageConfiguration.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageConfiguration.java @@ -26,7 +26,7 @@ package org.x4o.xml.core.config; import java.util.List; import java.util.Map; -import org.x4o.xml.core.X4ODebugWriter; +import org.x4o.xml.X4ODriver; import org.x4o.xml.element.ElementLanguage; @@ -44,17 +44,6 @@ public interface X4OLanguageConfiguration { /** The modules file to startup the language definition process. */ public static final String DEFAULT_LANG_MODULES_FILE = "-modules.xml"; - /** - * Returns the language for which this ElementLanguage is created. - * @return Returns the language. - */ - String getLanguage(); - - /** - * @return Returns the languageVersion of the parsing of this language. - */ - String getLanguageVersion(); - /** * @return Returns the path prefix for loading language resources. */ @@ -65,13 +54,6 @@ public interface X4OLanguageConfiguration { */ String getLanguageResourceModulesFileName(); - - Object getLanguageProperty(X4OLanguageProperty property); - void setLanguageProperty(X4OLanguageProperty property,Object object); - boolean getLanguagePropertyBoolean(X4OLanguageProperty property); - int getLanguagePropertyInteger(X4OLanguageProperty property); - - // Core interfaces are also in class for text reference without instance Class getDefaultElementNamespaceContext(); Class getDefaultElementInterface(); @@ -103,45 +85,30 @@ public interface X4OLanguageConfiguration { * Creates and filles the inital element language used to store the language. * @return The newly created ElementLanguage. */ - ElementLanguage createElementLanguage(); + ElementLanguage createElementLanguage(X4ODriver driver); /** * @return Returns Map of SAX properties which are set. */ - Map getSAXParserProperties(); + Map getSAXParserProperties(ElementLanguage elementContext); /** * @return Returns Map of SAX properties which are optional set. */ - Map getSAXParserPropertiesOptional(); + Map getSAXParserPropertiesOptional(ElementLanguage elementContext); /** * @return Returns Map of SAX features which are set on the xml parser. */ - Map getSAXParserFeatures(); + Map getSAXParserFeatures(ElementLanguage elementContext); /** * @return Returns Map of SAX features which are optional set. */ - Map getSAXParserFeaturesOptional(); + Map getSAXParserFeaturesOptional(ElementLanguage elementContext); /** * @return Returns List of SAX features which are required for xml parsing. */ - List getSAXParserFeaturesRequired(); - - /** - * @return Returns null or an X4ODebugWriter to write parsing steps and debug data to. - */ - X4ODebugWriter getX4ODebugWriter(); - - /** - * @return Returns true if this config has a debug writer. - */ - boolean hasX4ODebugWriter(); - - /** - * @param debugWriter The debug writer to set - */ - void setX4ODebugWriter(X4ODebugWriter debugWriter); + List getSAXParserFeaturesRequired(ElementLanguage elementContext); } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLoader.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLoader.java index 40bc590..dac788e 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLoader.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLoader.java @@ -23,8 +23,6 @@ package org.x4o.xml.core.config; -import org.x4o.xml.element.ElementLanguage; - /** * Loads the language into the contexts. * @@ -40,5 +38,5 @@ public interface X4OLanguageLoader { * @param languageVersion The language version to load. * @throws X4OLanguageLoaderException When there is an error. */ - void loadLanguage(ElementLanguage elementLanguage,String language,String languageVersion) throws X4OLanguageLoaderException; + void loadLanguage(X4OLanguageLocal languageLocal,String language,String languageVersion) throws X4OLanguageLoaderException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLocal.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLocal.java new file mode 100644 index 0000000..b127eb6 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageLocal.java @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.core.config; + +import org.x4o.xml.element.ElementLanguageModule; + +/** + * X4OLanguageLocal exposes the add method to load the language. + * + * @author Willem Cazander + * @version 1.0 30 apr 2013 + */ +public interface X4OLanguageLocal extends X4OLanguage { + + /* + * @param parserConfiguration The parserConfiguration to set. + + void setLanguageConfiguration(X4OLanguageConfiguration parserConfiguration); + */ + + /** + * Adds an ElementLanguageModule to this language. + * @param elementLanguageModule The element language module to add. + */ + void addElementLanguageModule(ElementLanguageModule elementLanguageModule); +} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageProperty.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageProperty.java index b0aff2d..919d672 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageProperty.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguageProperty.java @@ -27,6 +27,8 @@ import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import javax.el.ExpressionFactory; @@ -44,55 +46,57 @@ import org.xml.sax.ext.DefaultHandler2; */ public enum X4OLanguageProperty { + + /** Read-Only property returning the language we are working with. */ - LANGUAGE_NAME("language/name"), + LANGUAGE_NAME(IO.GLOBAL,"language/name"), /** Read-Only property returning the version of the language. */ - LANGUAGE_VERSION("language/version"), + LANGUAGE_VERSION(IO.GLOBAL,"language/version"), /** When set to OutputStream xml debug is written to it. note: when output-handler is set this property is ignored. */ - DEBUG_OUTPUT_STREAM("debug/output-stream",OutputStream.class), + DEBUG_OUTPUT_STREAM(IO.GLOBAL,"debug/output-stream",OutputStream.class), /** When set to DefaultHandler2 xml debug events are fired to the object. */ - DEBUG_OUTPUT_HANDLER("debug/output-handler",DefaultHandler2.class), + DEBUG_OUTPUT_HANDLER(IO.GLOBAL,"debug/output-handler",DefaultHandler2.class), /** When set to true print also phases for parsing eld files. */ - DEBUG_OUTPUT_ELD_PARSER("debug/output-eld-parser",Boolean.class,false), + DEBUG_OUTPUT_ELD_PARSER(IO.GLOBAL,"debug/output-eld-parser",Boolean.class,false), /** When set to true print full element tree per phase. */ //DEBUG_OUTPUT_TREE_PER_PHASE("debug/output-tree-per-phase",Boolean.class), /** SAX parser input buffer size: 512-16k defaults to 8k. */ - INPUT_BUFFER_SIZE("input/buffer-size",Integer.class,4096*2), + INPUT_BUFFER_SIZE(IO.READER,"input/buffer-size",Integer.class,4096*2), /** When set it allows parsing of non-namespace aware documents. */ - INPUT_EMPTY_NAMESPACE_URI("input/empty-namespace-uri"), + INPUT_EMPTY_NAMESPACE_URI(IO.READER,"input/empty-namespace-uri"), /** The input stream to parse, note is skipped when object is set. */ - INPUT_SOURCE_STREAM("input/source/stream",InputStream.class), + INPUT_SOURCE_STREAM(IO.READER,"input/source/stream",InputStream.class), /** When set it overrides automatic encoding detection of sax parser. */ - INPUT_SOURCE_ENCODING("input/source/encoding"), + INPUT_SOURCE_ENCODING(IO.READER,"input/source/encoding"), /** When set use this InputSource instance for parsing. */ - INPUT_SOURCE_OBJECT("input/source/object",InputSource.class), + INPUT_SOURCE_OBJECT(IO.READER,"input/source/object",InputSource.class), /** Sets the system-id to the input source. */ - INPUT_SOURCE_SYSTEM_ID("input/source/system-id",String.class), + INPUT_SOURCE_SYSTEM_ID(IO.READER,"input/source/system-id",String.class), /** Sets the base path to resolve external input sources. */ - INPUT_SOURCE_BASE_PATH("input/source/base-path",URL.class), + INPUT_SOURCE_BASE_PATH(IO.READER,"input/source/base-path",URL.class), /** Set for custom handling of validation errors. */ - CONFIG_ERROR_HANDLER("config/error-handler",ErrorHandler.class), + CONFIG_ERROR_HANDLER(IO.GLOBAL,"config/error-handler",ErrorHandler.class), /** Resolve more entities from local sources. */ - CONFIG_ENTITY_RESOLVER("config/entity-resolver",EntityResolver.class), + CONFIG_ENTITY_RESOLVER(IO.GLOBAL,"config/entity-resolver",EntityResolver.class), //CONFIG_CACHE_HANDLER("config/cache-handler"), //CONFIG_MODULE_PROVIDER("config/module-provider"), @@ -100,61 +104,101 @@ public enum X4OLanguageProperty { /** The beans in this map are set into the EL context for reference. */ - EL_BEAN_INSTANCE_MAP("el/bean-instance-map",Map.class), + EL_BEAN_INSTANCE_MAP(IO.READER,"el/bean-instance-map",Map.class), //EL_CONTEXT_INSTANCE("el/context-instance"), /** When set this instance is used in ElementLanguage. */ - EL_FACTORY_INSTANCE("el/factory-instance",ExpressionFactory.class), + EL_FACTORY_INSTANCE(IO.READER,"el/factory-instance",ExpressionFactory.class), //EL_INSTANCE_FACTORY("phase/skip-elb-init",Boolean.class), /** When set to an X4OPhase then parsing stops after completing the set phase. */ - PHASE_STOP_AFTER("phase/stop-after",Boolean.class), + PHASE_STOP_AFTER(IO.READER,"phase/stop-after",String.class), /** When set to true skip the release phase. */ - PHASE_SKIP_RELEASE("phase/skip-release",Boolean.class,false), + PHASE_SKIP_RELEASE(IO.READER,"phase/skip-release",Boolean.class,false), /** When set to true skip the run phase. */ - PHASE_SKIP_RUN("phase/skip-run",Boolean.class,false), + PHASE_SKIP_RUN(IO.READER,"phase/skip-run",Boolean.class,false), /** When set to true skip the load siblings language phase. */ - PHASE_SKIP_SIBLINGS("phase/skip-siblings",Boolean.class,false), + PHASE_SKIP_SIBLINGS(IO.READER,"phase/skip-siblings",Boolean.class,false), /** When set this path is searched for xsd schema files in the language sub directory. */ - VALIDATION_SCHEMA_PATH("validation/schema-path",File.class), + VALIDATION_SCHEMA_PATH(IO.READER,"validation/schema-path",File.class), /** When set to true then input xml is validated. */ - VALIDATION_INPUT("validation/input",Boolean.class,false), + VALIDATION_INPUT(IO.READER,"validation/input",Boolean.class,false), /** When set to true then input xsd xml grammer is validated. */ - VALIDATION_INPUT_XSD("validation/input/xsd",Boolean.class,false), + VALIDATION_INPUT_XSD(IO.READER,"validation/input/xsd",Boolean.class,false), /** When set to true then eld xml is validated. */ - VALIDATION_ELD("validation/eld",Boolean.class,false), + VALIDATION_ELD(IO.READER,"validation/eld",Boolean.class,false), /** When set to true than eld xsd xml grammer is also validated. */ - VALIDATION_ELD_XSD("validation/eld/xsd",Boolean.class,false); + VALIDATION_ELD_XSD(IO.GLOBAL, "validation/eld/xsd",Boolean.class,false); + public final static X4OLanguageProperty[] DEFAULT_X4O_GLOBAL_KEYS; + public final static X4OLanguageProperty[] DEFAULT_X4O_READER_KEYS; + public final static X4OLanguageProperty[] DEFAULT_X4O_WRITER_KEYS; + public final static X4OLanguageProperty[] DEFAULT_X4O_SCHEMA_WRITER_KEYS; + + static { + List globalResultKeys = new ArrayList(); + List readerResultKeys = new ArrayList(); + List writerResultKeys = new ArrayList(); + List schemaWriterResultKeys = new ArrayList(); + X4OLanguageProperty[] keys = X4OLanguageProperty.values(); + for (int i=0;i[] classTypes; private final Object defaultValue; + private final X4OLanguageProperty.IO type; - private X4OLanguageProperty(String uriName) { - this(uriName,String.class); + private X4OLanguageProperty(X4OLanguageProperty.IO type,String uriName) { + this(type,uriName,String.class); } - private X4OLanguageProperty(String uriName,Class classType) { - this(uriName,new Class[]{classType},null); + private X4OLanguageProperty(X4OLanguageProperty.IO type,String uriName,Class classType) { + this(type,uriName,new Class[]{classType},null); } - private X4OLanguageProperty(String uriName,Class classType,Object defaultValue) { - this(uriName,new Class[]{classType},defaultValue); + private X4OLanguageProperty(X4OLanguageProperty.IO type,String uriName,Class classType,Object defaultValue) { + this(type,uriName,new Class[]{classType},defaultValue); } - private X4OLanguageProperty(String uriName,Class[] classTypes,Object defaultValue) { + private X4OLanguageProperty(X4OLanguageProperty.IO type,String uriName,Class[] classTypes,Object defaultValue) { + this.type=type; this.uriName=URI_PREFIX+uriName; this.classTypes=classTypes; this.defaultValue=defaultValue; diff --git a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguagePropertyKeys.java b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguagePropertyKeys.java index 00716fd..b25e4bf 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguagePropertyKeys.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/config/X4OLanguagePropertyKeys.java @@ -63,4 +63,39 @@ public class X4OLanguagePropertyKeys { public static final String VALIDATION_INPUT_XSD = X4OLanguageProperty.VALIDATION_INPUT_XSD.toUri(); public static final String VALIDATION_ELD = X4OLanguageProperty.VALIDATION_ELD.toUri(); public static final String VALIDATION_ELD_XSD = X4OLanguageProperty.VALIDATION_ELD_XSD.toUri(); + + public final static String[] DEFAULT_X4O_GLOBAL_KEYS; + public final static String[] DEFAULT_X4O_READER_KEYS; + public final static String[] DEFAULT_X4O_WRITER_KEYS; + public final static String[] DEFAULT_X4O_SCHEMA_WRITER_KEYS; + + static { + X4OLanguageProperty[] globalKeys = X4OLanguageProperty.DEFAULT_X4O_GLOBAL_KEYS; + String[] globalResultKeys = new String[globalKeys.length]; + for (int i=0;i phaseListeners = null; /** * Creates the AbstractX4OPhaseHandler. */ - public AbstractX4OPhaseHandler() { + public AbstractX4OPhase() { phaseListeners = new ArrayList(3); - setX4OPhase(); } /** - * Is called from constructor. + * defaults to false */ - abstract protected void setX4OPhase(); - - /** - * Gets the current phase. - * @return The current phase. - */ - public X4OPhase getX4OPhase() { - return phase; + public boolean isRunOnce() { + return false; } /** diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseManager.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/DefaultX4OPhaseManager.java similarity index 53% rename from x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseManager.java rename to x4o-core/src/main/java/org/x4o/xml/core/phase/DefaultX4OPhaseManager.java index 5226983..7dd1d7b 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseManager.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/DefaultX4OPhaseManager.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.core; +package org.x4o.xml.core.phase; import java.util.ArrayList; import java.util.Collections; @@ -40,21 +40,23 @@ import org.x4o.xml.element.ElementLanguage; * @author Willem Cazander * @version 1.0 Jan 6, 2008 */ -public class X4OPhaseManager { +public class DefaultX4OPhaseManager implements X4OPhaseManager { /** The X4OPhaseHandler */ - private List x4oPhases = null; - private ElementLanguage elementLanguage = null; - private X4OPhase stopPhase = null; - private boolean skipReleasePhase = false; - private boolean skipRunPhase = false; - private boolean skipSiblingsPhase = false; + private List x4oPhases = null; + //private ElementLanguage elementLanguage = null; + //private X4OPhase stopPhase = null; + //private boolean skipReleasePhase = false; + //private boolean skipRunPhase = false; + //private boolean skipSiblingsPhase = false; /** * Local package constructor. * @param elementLanguage The ElementLanguage to run the phases on. */ - public X4OPhaseManager(ElementLanguage elementLanguage) { + public DefaultX4OPhaseManager() { + x4oPhases = new ArrayList(25); + /* if (elementLanguage==null) { throw new NullPointerException("Can't manage phases with null elementLanguage in constuctor."); } @@ -62,29 +64,30 @@ public class X4OPhaseManager { this.elementLanguage = elementLanguage; // Manual - skipReleasePhase = elementLanguage.getLanguageConfiguration().getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RELEASE); - skipRunPhase = elementLanguage.getLanguageConfiguration().getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RUN); - skipSiblingsPhase = elementLanguage.getLanguageConfiguration().getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_SIBLINGS); + skipReleasePhase = elementLanguage.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RELEASE); + skipRunPhase = elementLanguage.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RUN); + skipSiblingsPhase = elementLanguage.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_SIBLINGS); // Check if we need to stop after a certain phase - Object stopPhaseObject = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.PHASE_STOP_AFTER); + Object stopPhaseObject = elementLanguage.getLanguageProperty(X4OLanguageProperty.PHASE_STOP_AFTER); if (stopPhaseObject instanceof X4OPhase) { stopPhase = (X4OPhase)stopPhaseObject; } + */ } /** * Adds an X4OPhaseHandler. * @param phase The X4OPhaseHandler to add. */ - public void addX4OPhaseHandler(X4OPhaseHandler phase) { + public void addX4OPhase(X4OPhase phase) { if (phase==null) { throw new NullPointerException("Can't add null phase handler."); } // context is created in first phase. - if (X4OPhase.FIRST_PHASE.equals(elementLanguage.getCurrentX4OPhase())==false) { - throw new IllegalStateException("Can't add new phases after first phase is completed."); - } + //if (X4OPhase.FIRST_PHASE.equals(elementLanguage.getCurrentX4OPhase())==false) { +// throw new IllegalStateException("Can't add new phases after first phase is completed."); + //} x4oPhases.add(phase); } @@ -92,17 +95,28 @@ public class X4OPhaseManager { * Returns all the X4OPhaseHandlers. * @return Returns all X4OPhaseHandlers. */ - protected List getPhases() { - return x4oPhases; + public List getAllPhases() { + return new ArrayList(x4oPhases); } /** * Returns all the X4OPhaseHandlers in ordered list. * @return Returns all X4OPhaseHandler is order. */ - protected List getOrderedPhases() { - List result = new ArrayList(x4oPhases); - Collections.sort(result,new X4OPhaseHandlerComparator()); + public List getOrderedPhases(X4OPhaseType type) { + List result = new ArrayList(x4oPhases.size()); + for (X4OPhase p:x4oPhases) { + if (p.getType().equals(type)) { + result.add(p); + } + if (X4OPhaseType.XML_READ.equals(type) && X4OPhaseType.XML_RW.equals(p.getType())) { + result.add(p); + } + if (X4OPhaseType.XML_WRITE.equals(type) && X4OPhaseType.XML_RW.equals(p.getType())) { + result.add(p); + } + } + Collections.sort(result,new X4OPhaseComparator()); return result; } @@ -110,52 +124,68 @@ public class X4OPhaseManager { * Runs all the phases in the right order. * @throws X4OPhaseException When a running handlers throws one. */ - public void runPhases() throws X4OPhaseException { + public void runPhases(ElementLanguage languageContext,X4OPhaseType type) throws X4OPhaseException { // sort for the order - List x4oPhasesOrder = getOrderedPhases(); + List x4oPhasesOrder = getOrderedPhases(type); + + /* + System.out.println("------ phases type: "+type+" for: "+languageContext.getLanguage().getLanguageName()); + for (X4OPhase p:x4oPhasesOrder) { + System.out.print("Exec phase; "+p.getId()+" deps: ["); + for (String dep:p.getPhaseDependencies()) { + System.out.print(dep+","); + } + System.out.println("]"); + } + */ // debug output - if (elementLanguage.getLanguageConfiguration().getX4ODebugWriter()!=null) { - elementLanguage.getLanguageConfiguration().getX4ODebugWriter().debugPhaseOrder(x4oPhases); + if (languageContext.getX4ODebugWriter()!=null) { + languageContext.getX4ODebugWriter().debugPhaseOrder(x4oPhases); } + boolean skipReleasePhase = languageContext.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RELEASE); + boolean skipRunPhase = languageContext.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RUN); + boolean skipSiblingsPhase = languageContext.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_SIBLINGS); + String stopPhase = languageContext.getLanguagePropertyString(X4OLanguageProperty.PHASE_STOP_AFTER); + // run the phases in ordered order - for (X4OPhaseHandler phaseHandler:x4oPhasesOrder) { + for (X4OPhase phase:x4oPhasesOrder) { - if (skipReleasePhase && X4OPhase.releasePhase.equals(phaseHandler.getX4OPhase())) { + if (skipReleasePhase && phase.getId().equals("X4O_RELEASE")) { continue; // skip always release phase when requested by property } - if (skipRunPhase && X4OPhase.runPhase.equals(phaseHandler.getX4OPhase())) { + if (skipRunPhase && phase.getId().equals("READ_RUN")) { continue; // skip run phase on request } - if (skipSiblingsPhase && X4OPhase.createLanguageSiblingsPhase.equals(phaseHandler.getX4OPhase())) { + if (skipSiblingsPhase && phase.getId().equals("INIT_LANG_SIB")) { continue; // skip loading sibling languages } // debug output - elementLanguage.setCurrentX4OPhase(phaseHandler.getX4OPhase()); + languageContext.setCurrentX4OPhase(phase); // run listeners - for (X4OPhaseListener l:phaseHandler.getPhaseListeners()) { - l.preRunPhase(phaseHandler, elementLanguage); + for (X4OPhaseListener l:phase.getPhaseListeners()) { + l.preRunPhase(phase, languageContext); } // always run endRunPhase for valid debug xml try { // do the run interface - phaseHandler.runPhase(elementLanguage); + phase.runPhase(languageContext); // run the element phase if possible - executePhaseElement(phaseHandler); + executePhaseRoot(languageContext,phase); } finally { // run the listeners again - for (X4OPhaseListener l:phaseHandler.getPhaseListeners()) { - l.endRunPhase(phaseHandler, elementLanguage); + for (X4OPhaseListener l:phase.getPhaseListeners()) { + l.endRunPhase(phase, languageContext); } } - if (stopPhase!=null && stopPhase.equals(phaseHandler.getX4OPhase())) { + if (stopPhase!=null && stopPhase.equals(phase.getId())) { return; // we are done } } @@ -167,31 +197,35 @@ public class X4OPhaseManager { * @param p The phase to run. * @throws X4OPhaseException When a running handlers throws one. */ - public void runPhasesForElement(Element e,X4OPhase p) throws X4OPhaseException { + public void runPhasesForElement(Element e,X4OPhaseType type,X4OPhase p) throws X4OPhaseException { + ElementLanguage languageContext = e.getElementLanguage(); + boolean skipRunPhase = languageContext.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RUN); + String stopPhase = languageContext.getLanguagePropertyString(X4OLanguageProperty.PHASE_STOP_AFTER); + // sort for the order - List x4oPhasesOrder = getOrderedPhases(); - for (X4OPhaseHandler phaseHandler:x4oPhasesOrder) { - if (phaseHandler.getX4OPhase().equals(p)==false) { + List x4oPhasesOrder = getOrderedPhases(type); + for (X4OPhase phase:x4oPhasesOrder) { + if (phase.getId().equals(p.getId())==false) { continue; // we start running all phases from specified phase } - if (X4OPhase.releasePhase.equals(phaseHandler.getX4OPhase())) { + if (phase.getId().equals("RELEASE")) { continue; // skip always release phase in dirty extra runs. } - if (skipRunPhase && X4OPhase.runPhase.equals(phaseHandler.getX4OPhase())) { + if (skipRunPhase && phase.getId().equals("READ_RUN")) { continue; // skip run phase on request } // set phase - elementLanguage.setCurrentX4OPhase(phaseHandler.getX4OPhase()); + languageContext.setCurrentX4OPhase(phase); // do the run interface - phaseHandler.runPhase(elementLanguage); + phase.runPhase(languageContext); // run the element phase if possible - executePhaseElement(phaseHandler); + executePhaseRoot(languageContext,phase); - if (stopPhase!=null && stopPhase.equals(phaseHandler.getX4OPhase())) { + if (stopPhase!=null && stopPhase.equals(phase.getId())) { return; // we are done } } @@ -201,20 +235,21 @@ public class X4OPhaseManager { * Run release phase manual if auto release is disabled by config. * @throws X4OPhaseException When a running handlers throws one. */ - public void doReleasePhaseManual() throws X4OPhaseException { + public void doReleasePhaseManual(ElementLanguage languageContext) throws X4OPhaseException { + boolean skipReleasePhase = languageContext.getLanguagePropertyBoolean(X4OLanguageProperty.PHASE_SKIP_RELEASE); if (skipReleasePhase==false) { throw new IllegalStateException("No manual release requested."); } - if (elementLanguage.getRootElement()==null) { + if (languageContext.getRootElement()==null) { return; // no root element , empty xml document ? } - if (elementLanguage.getRootElement().getElementClass()==null) { + if (languageContext.getRootElement().getElementClass()==null) { throw new IllegalStateException("Release phase has already been runned."); } - X4OPhaseHandler h = null; - for (X4OPhaseHandler phase:x4oPhases) { - if (phase.getX4OPhase().equals(X4OPhase.releasePhase)) { + X4OPhase h = null; + for (X4OPhase phase:x4oPhases) { + if (phase.getId().equals("X4O_RELEASE")) { h = phase; break; } @@ -224,24 +259,33 @@ public class X4OPhaseManager { } // set phase - elementLanguage.setCurrentX4OPhase(h.getX4OPhase()); + languageContext.setCurrentX4OPhase(h); // do the run interface - h.runPhase(elementLanguage); + h.runPhase(languageContext); // run the element phase if possible - executePhaseElement(h); + executePhaseRoot(languageContext,h); } - class X4OPhaseHandlerComparator implements Comparator { + class X4OPhaseComparator implements Comparator { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ - public int compare(X4OPhaseHandler e1, X4OPhaseHandler e2) { + public int compare(X4OPhase e1, X4OPhase e2) { - X4OPhase p1 = e1.getX4OPhase(); - X4OPhase p2 = e2.getX4OPhase(); + String pid = e1.getId(); + String[] dpids = e2.getPhaseDependencies(); + for (int i=0;i runConf = null; - public X4OPhaseHandlerFactory(ElementLanguage elementLanguage) { - if (elementLanguage==null) { - throw new NullPointerException("Can't start factory with null elementLanguage."); - } - this.elementLanguage=elementLanguage; - logger = Logger.getLogger(X4OPhaseHandlerFactory.class.getName()); - runConf = new ArrayList(10); + public X4OPhaseFactory() { + logger = Logger.getLogger(X4OPhaseFactory.class.getName()); } - class RunConfigurator { - Element element; - ElementConfigurator elementConfigurator; - RunConfigurator(Element element,ElementConfigurator elementConfigurator) { - this.element=element; - this.elementConfigurator=elementConfigurator; - } - } - - private void runElementConfigurator(ElementConfigurator ec,Element e,X4OPhaseHandler phase) throws X4OPhaseException { - //int size = ecs.size(); - //for (int i=0;i siblingLoaders = new ArrayList(3); - for (ElementLanguageModule module:elementLanguage.getElementLanguageModules()) { + for (ElementLanguageModule module:elementLanguage.getLanguage().getElementLanguageModules()) { if (module.getElementLanguageModuleLoader() instanceof ElementLanguageModuleLoaderSibling) { siblingLoaders.add((ElementLanguageModuleLoaderSibling)module.getElementLanguageModuleLoader()); } } if (siblingLoaders.isEmpty()==false) { - X4OLanguageLoader loader = (X4OLanguageLoader)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultX4OLanguageLoader()); + X4OLanguageLoader loader = (X4OLanguageLoader)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguage().getLanguageConfiguration().getDefaultX4OLanguageLoader()); for (ElementLanguageModuleLoaderSibling siblingLoader:siblingLoaders) { - debugPhaseMessage("Loading sibling langauge loader: "+siblingLoader,this); - siblingLoader.loadLanguageSibling(elementLanguage, loader); + debugPhaseMessage("Loading sibling langauge loader: "+siblingLoader,this,elementLanguage); + siblingLoader.loadLanguageSibling((X4OLanguageLocal)elementLanguage.getLanguage(), loader); } - if (hasX4ODebugWriter()) { - getX4ODebugWriter().debugElementLanguageModules(elementLanguage); + if (elementLanguage.hasX4ODebugWriter()) { + elementLanguage.getX4ODebugWriter().debugElementLanguageModules(elementLanguage); } } } catch (Exception e) { @@ -233,25 +200,69 @@ public class X4OPhaseHandlerFactory { } } }; - X4OPhaseHandler result = new CreateLanguageSiblingsPhase(); + X4OPhase result = new CreateLanguageSiblingsPhase(); return result; } + /** + * Creates the startX4OPhase which is a empty meta phase. + * @return The X4OPhaseHandler for this phase. + */ + public X4OPhase readStartX4OPhase() { + class ReadStartX4OPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_START"; + } + public String[] getPhaseDependencies() { + return new String[]{}; + } + public boolean isElementPhase() { + return false; + } + public void runElementPhase(Element element) throws X4OPhaseException { + // not used. + } + public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + // print the properties and classes for this language/config + if (elementLanguage.hasX4ODebugWriter()) { + try { + elementLanguage.getX4ODebugWriter().debugLanguageProperties(elementLanguage); + elementLanguage.getX4ODebugWriter().debugLanguageDefaultClasses(elementLanguage); + } catch (ElementException e) { + throw new X4OPhaseException(this,e); + } + } + } + }; + X4OPhase result = new ReadStartX4OPhase(); + return result; + } + + /** * Parses the xml resource(s) and creates an Element tree. * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler parseSAXStreamPhase() { - class CreateSAXStreamPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.parseSAXStreamPhase; + public X4OPhase readSAXStreamPhase() { + class CreateSAXStreamPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_XML"; + } + public String[] getPhaseDependencies() { + return new String[]{"READ_START"}; } public boolean isElementPhase() { return false; } public void runElementPhase(Element element) throws X4OPhaseException { } - public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { try { //XMLParserConfiguration config = new XIncludeAwareParserConfiguration(); //config.setProperty("http://apache.org/xml/properties/internal/grammar-pool",myFullGrammarPool); @@ -267,69 +278,69 @@ public class X4OPhaseHandlerFactory { saxParser.setProperty("http://xml.org/sax/properties/declaration-handler",xth); // Set properties and optional - Map saxParserProperties = elementLanguage.getLanguageConfiguration().getSAXParserProperties(); + Map saxParserProperties = elementLanguage.getLanguage().getLanguageConfiguration().getSAXParserProperties(elementLanguage); for (Map.Entry entry:saxParserProperties.entrySet()) { String name = entry.getKey(); Object value= entry.getValue(); saxParser.setProperty(name, value); - debugPhaseMessage("Set SAX property: "+name+" to: "+value,this); + debugPhaseMessage("Set SAX property: "+name+" to: "+value,this,elementLanguage); } - Map saxParserPropertiesOptional = elementLanguage.getLanguageConfiguration().getSAXParserPropertiesOptional(); + Map saxParserPropertiesOptional = elementLanguage.getLanguage().getLanguageConfiguration().getSAXParserPropertiesOptional(elementLanguage); for (Map.Entry entry:saxParserPropertiesOptional.entrySet()) { String name = entry.getKey(); Object value= entry.getValue(); try { saxParser.setProperty(name, value); - debugPhaseMessage("Set SAX optional property: "+name+" to: "+value,this); + debugPhaseMessage("Set SAX optional property: "+name+" to: "+value,this,elementLanguage); } catch (SAXException e) { - debugPhaseMessage("Could not set optional SAX property: "+name+" to: "+value+" error: "+e.getMessage(),this); + debugPhaseMessage("Could not set optional SAX property: "+name+" to: "+value+" error: "+e.getMessage(),this,elementLanguage); } } // Set sax features and optional - Map features = elementLanguage.getLanguageConfiguration().getSAXParserFeatures(); + Map features = elementLanguage.getLanguage().getLanguageConfiguration().getSAXParserFeatures(elementLanguage); for (String key:features.keySet()) { Boolean value=features.get(key); saxParser.setFeature(key, value); - debugPhaseMessage("Set SAX feature: "+key+" to: "+value,this); + debugPhaseMessage("Set SAX feature: "+key+" to: "+value,this,elementLanguage); } - Map featuresOptional = elementLanguage.getLanguageConfiguration().getSAXParserFeaturesOptional(); + Map featuresOptional = elementLanguage.getLanguage().getLanguageConfiguration().getSAXParserFeaturesOptional(elementLanguage); for (String key:featuresOptional.keySet()) { Boolean value=featuresOptional.get(key); try { saxParser.setFeature(key, value); - debugPhaseMessage("Set SAX optional feature: "+key+" to: "+value,this); + debugPhaseMessage("Set SAX optional feature: "+key+" to: "+value,this,elementLanguage); } catch (SAXException e) { - debugPhaseMessage("Could not set optional SAX feature: "+key+" to: "+value+" error: "+e.getMessage(),this); + debugPhaseMessage("Could not set optional SAX feature: "+key+" to: "+value+" error: "+e.getMessage(),this,elementLanguage); } } // check for required features - List requiredFeatures = elementLanguage.getLanguageConfiguration().getSAXParserFeaturesRequired(); + List requiredFeatures = elementLanguage.getLanguage().getLanguageConfiguration().getSAXParserFeaturesRequired(elementLanguage); for (String requiredFeature:requiredFeatures) { - debugPhaseMessage("Checking required SAX feature: "+requiredFeature,this); + debugPhaseMessage("Checking required SAX feature: "+requiredFeature,this,elementLanguage); if (saxParser.getFeature(requiredFeature)==false) { - Exception e = new IllegalStateException("Missing required feature: "+requiredFeature); + Exception e = new IllegalStateException("Missing required feature: "+requiredFeature); throw new X4OPhaseException(this,e); } } // Finally start parsing the xml input stream - Object requestInputSource = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_OBJECT); + Object requestInputSource = elementLanguage.getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_OBJECT); InputSource input = null; InputStream inputStream = null; if (requestInputSource instanceof InputSource) { input = (InputSource)requestInputSource; } else { - inputStream = (InputStream)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_STREAM); + inputStream = (InputStream)elementLanguage.getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_STREAM); input = new InputSource(inputStream); } - Object requestInputEncoding = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_ENCODING); + Object requestInputEncoding = elementLanguage.getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_ENCODING); if (requestInputEncoding!=null && requestInputEncoding instanceof String) { input.setEncoding(requestInputEncoding.toString()); } - Object requestSystemId = elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_SYSTEM_ID); + Object requestSystemId = elementLanguage.getLanguageProperty(X4OLanguageProperty.INPUT_SOURCE_SYSTEM_ID); if (requestSystemId!=null && requestSystemId instanceof String) { input.setSystemId(requestSystemId.toString()); } @@ -346,30 +357,7 @@ public class X4OPhaseHandlerFactory { } } }; - X4OPhaseHandler result = new CreateSAXStreamPhase(); - return result; - } - - /** - * Creates the startX4OPhase which is a empty meta phase. - * @return The X4OPhaseHandler for this phase. - */ - public X4OPhaseHandler startX4OPhase() { - class CreateStartX4OPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.startX4OPhase; - } - public boolean isElementPhase() { - return false; - } - public void runElementPhase(Element element) throws X4OPhaseException { - // not used. - } - public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { - // empty because this is a meta phase. - } - }; - X4OPhaseHandler result = new CreateStartX4OPhase(); + X4OPhase result = new CreateSAXStreamPhase(); return result; } @@ -377,10 +365,16 @@ public class X4OPhaseHandlerFactory { * Creates the configGlobalElBeansPhase which adds beans to the el context. * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler configGlobalElBeansPhase() { - class ConfigGlobalElBeansPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.configGlobalElBeansPhase; + public X4OPhase configGlobalElBeansPhase() { + class ConfigGlobalElBeansPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_RW; + } + public String getId() { + return "X4O_CONFIG_GLOBAL_EL"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_XML"}; } public boolean isElementPhase() { return false; @@ -389,9 +383,9 @@ public class X4OPhaseHandlerFactory { // not used. } @SuppressWarnings("rawtypes") - public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { try { - Map beanMap = (Map)elementLanguage.getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); + Map beanMap = (Map)elementLanguage.getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); if (beanMap==null) { return; } @@ -399,14 +393,14 @@ public class X4OPhaseHandlerFactory { Object o = beanMap.get(elName); ValueExpression ve = elementLanguage.getExpressionFactory().createValueExpression(elementLanguage.getELContext(),"${"+elName+"}", o.getClass()); ve.setValue(elementLanguage.getELContext(), o); - debugPhaseMessage("Setting el bean: ${"+elName+"} to: "+o.getClass().getName(),this); + debugPhaseMessage("Setting el bean: ${"+elName+"} to: "+o.getClass().getName(),this,elementLanguage); } } catch (Exception e) { throw new X4OPhaseException(this,e); } } }; - X4OPhaseHandler result = new ConfigGlobalElBeansPhase(); + X4OPhase result = new ConfigGlobalElBeansPhase(); return result; } @@ -414,12 +408,18 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler configElementPhase() { - class ConfigElementPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.configElementPhase; + public X4OPhase configElementPhase(final X4OPhaseReadRunConfigurator runConf) { + class ConfigElementPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_CONFIG_ELEMENT"; + } + public String[] getPhaseDependencies() { + return new String[] {"X4O_CONFIG_GLOBAL_EL"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { // First phase is to rename attributes, maybe move so sax phase for (ElementClassAttribute eca:element.getElementClass().getElementClassAttributes()) { @@ -438,11 +438,11 @@ public class X4OPhaseHandlerFactory { logger.finest("Do ElementClass Config Configurators: "+element.getElementClass().getElementConfigurators().size()); for (ElementConfigurator ec:element.getElementClass().getElementConfigurators()) { - runElementConfigurator(ec,element,this); + runConf.runElementConfigurator(ec,element,this); } } }; - X4OPhaseHandler result = new ConfigElementPhase(); + X4OPhase result = new ConfigElementPhase(); return result; } @@ -450,25 +450,31 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler configElementInterfacePhase() { - class ConfigElementInterfacePhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.configElementInterfacePhase; + public X4OPhase configElementInterfacePhase(final X4OPhaseReadRunConfigurator runConf) { + class ConfigElementInterfacePhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_CONFIG_ELEMENT_INTERFACE"; + } + public String[] getPhaseDependencies() { + return new String[] {"X4O_CONFIG_GLOBAL_EL"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { if (element.getElementObject()==null) { logger.finest("Null elementObject skipping, interfaces"); return; } - for (ElementInterface ei:element.getElementLanguage().findElementInterfaces(element.getElementObject())) { + for (ElementInterface ei:element.getElementLanguage().getLanguage().findElementInterfaces(element.getElementObject())) { logger.finest("Do ElementInterface Config Configurators: "+ei.getElementConfigurators().size()); for (ElementConfigurator ec:ei.getElementConfigurators()) { - runElementConfigurator(ec,element,this); + runConf.runElementConfigurator(ec,element,this); } } } }; - X4OPhaseHandler result = new ConfigElementInterfacePhase(); + X4OPhase result = new ConfigElementInterfacePhase(); return result; } @@ -477,21 +483,27 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler configGlobalElementPhase() { - class ConfigGlobalElementPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.configGlobalElementPhase; + public X4OPhase configGlobalElementPhase(final X4OPhaseReadRunConfigurator runConf) { + class ConfigGlobalElementPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { - for (ElementLanguageModule mod:element.getElementLanguage().getElementLanguageModules()) { + public String getId() { + return "READ_CONFIG_GLOBAL_ELEMENT"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_CONFIG_ELEMENT","READ_CONFIG_ELEMENT_INTERFACE"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { + for (ElementLanguageModule mod:element.getElementLanguage().getLanguage().getElementLanguageModules()) { logger.finest("Do Element Config Global Configurators: "+mod.getElementConfiguratorGlobals().size()); for (ElementConfiguratorGlobal ec:mod.getElementConfiguratorGlobals()) { - runElementConfigurator(ec,element,this); + runConf.runElementConfigurator(ec,element,this); } } } }; - X4OPhaseHandler result = new ConfigGlobalElementPhase(); + X4OPhase result = new ConfigGlobalElementPhase(); return result; } @@ -499,17 +511,23 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler configGlobalAttributePhase() { - class ConfigGlobalAttributePhase extends AbstractX4OPhaseHandler { + public X4OPhase configGlobalAttributePhase(final X4OPhaseReadRunConfigurator runConf) { + class ConfigGlobalAttributePhase extends AbstractX4OPhase { Comparator elementAttributeHandlerComparator = null; - protected void setX4OPhase() { - phase = X4OPhase.configGlobalAttributePhase; + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_CONFIG_GLOBAL_ATTRIBUTE"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_CONFIG_GLOBAL_ELEMENT"}; } @SuppressWarnings("unchecked") - public void runElementPhase(Element element) throws X4OPhaseException { + public void runElementPhase(Element element) throws X4OPhaseException { if (elementAttributeHandlerComparator==null) { try { - elementAttributeHandlerComparator = (Comparator)X4OLanguageClassLoader.newInstance(element.getElementLanguage().getLanguageConfiguration().getDefaultElementAttributeHandlerComparator()); + elementAttributeHandlerComparator = (Comparator)X4OLanguageClassLoader.newInstance(element.getElementLanguage().getLanguage().getLanguageConfiguration().getDefaultElementAttributeHandlerComparator()); } catch (Exception e) { throw new X4OPhaseException(this,e); } @@ -518,7 +536,7 @@ public class X4OPhaseHandlerFactory { // do global parameters logger.finest("Do Element Global AttributeHandlers."); List handlers = new ArrayList(); - for (ElementLanguageModule mod:element.getElementLanguage().getElementLanguageModules()) { + for (ElementLanguageModule mod:element.getElementLanguage().getLanguage().getElementLanguageModules()) { for (ElementAttributeHandler global:mod.getElementAttributeHandlers()) { String attribute = element.getAttributes().get(global.getAttributeName()); @@ -531,11 +549,11 @@ public class X4OPhaseHandlerFactory { List handlers2 = new ArrayList(handlers.size()); handlers2.addAll(handlers); for (ElementConfigurator ec:handlers) { - runElementConfigurator(ec,element,this); + runConf.runElementConfigurator(ec,element,this); } } }; - X4OPhaseHandler result = new ConfigGlobalAttributePhase(); + X4OPhase result = new ConfigGlobalAttributePhase(); return result; } @@ -543,17 +561,27 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler runAttributesPhase() { - class RunAttributesPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.runAttributesPhase; + public X4OPhase runAttributesPhase() { + class RunAttributesPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_RUN_ATTRIBUTE"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_CONFIG_GLOBAL_ATTRIBUTE"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { // we only can config ElementObjects if (element.getElementObject()==null) { return; } + if (element.getElementLanguage().getLanguage().getLanguageName().equals("test")) { + System.out.println("do element; "+element.getElementClass().getTag()+" attr; "+element.getAttributes()); + } + // do config Map attr = element.getAttributes(); ElementAttributeValueParser attrParser = element.getElementLanguage().getElementAttributeValueParser(); @@ -610,7 +638,7 @@ public class X4OPhaseHandlerFactory { } } }; - X4OPhaseHandler result = new RunAttributesPhase(); + X4OPhase result = new RunAttributesPhase(); return result; } @@ -618,10 +646,16 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler fillTemplatingPhase() { - X4OPhaseHandler result = new AbstractX4OPhaseHandler() { - protected void setX4OPhase() { - phase = X4OPhase.fillTemplatingPhase; + public X4OPhase fillTemplatingPhase() { + X4OPhase result = new AbstractX4OPhase() { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_FILL_TEMPLATE"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_RUN_ATTRIBUTE"}; } public void runElementPhase(Element element) throws X4OPhaseException { } @@ -633,18 +667,24 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler transformPhase() { - X4OPhaseHandler result = new AbstractX4OPhaseHandler() { - protected void setX4OPhase() { - phase = X4OPhase.transformPhase; + public X4OPhase transformPhase() { + X4OPhase result = new AbstractX4OPhase() { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_TRANSFORM"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_FILL_TEMPLATE"}; } public void runElementPhase(Element element) throws X4OPhaseException { if (element.isTransformingTree()==false) { return; } try { - if (hasX4ODebugWriter()) { - getX4ODebugWriter().debugElement(element); + if (element.getElementLanguage().hasX4ODebugWriter()) { + element.getElementLanguage().getX4ODebugWriter().debugElement(element); } element.doElementRun(); } catch (ElementException e) { @@ -660,25 +700,31 @@ public class X4OPhaseHandlerFactory { * @param manager The phasemanager. * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler runDirtyElementPhase(final X4OPhaseManager manager) { - class RunDirtyElementPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.runDirtyElementPhase; + public X4OPhase runDirtyElementPhase(final X4OPhaseManager manager) { + class RunDirtyElementPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_RUN_DIRTY"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_TRANSFORM"}; } public void runElementPhase(Element element) throws X4OPhaseException { Map dirtyElements = element.getElementLanguage().getDirtyElements(); if (dirtyElements.isEmpty()) { return; } - debugPhaseMessage("Dirty elements: "+dirtyElements.size(), this); + debugPhaseMessage("Dirty elements: "+dirtyElements.size(), this,element.getElementLanguage()); for (Element e:dirtyElements.keySet()) { X4OPhase p = dirtyElements.get(e); - manager.runPhasesForElement(e, p); + manager.runPhasesForElement(e,getType(), p); } element.getElementLanguage().getDirtyElements().clear(); } }; - X4OPhaseHandler result = new RunDirtyElementPhase(); + X4OPhase result = new RunDirtyElementPhase(); return result; } @@ -687,25 +733,31 @@ public class X4OPhaseHandlerFactory { * @param manager The phasemanager. * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler runDirtyElementLastPhase(final X4OPhaseManager manager) { - class RunDirtyElementLastPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.runDirtyElementLastPhase; + public X4OPhase runDirtyElementLastPhase(final X4OPhaseManager manager) { + class RunDirtyElementLastPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_RUN_DIRTY_LAST"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_RUN"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { Map dirtyElements = element.getElementLanguage().getDirtyElements(); if (dirtyElements.isEmpty()) { return; } - debugPhaseMessage("Dirty elements last: "+dirtyElements.size(), this); + debugPhaseMessage("Dirty elements last: "+dirtyElements.size(), this,element.getElementLanguage()); for (Element e:dirtyElements.keySet()) { X4OPhase p = dirtyElements.get(e); - manager.runPhasesForElement(e, p); + manager.runPhasesForElement(e,getType(), p); } element.getElementLanguage().getDirtyElements().clear(); } }; - X4OPhaseHandler result = new RunDirtyElementLastPhase(); + X4OPhase result = new RunDirtyElementLastPhase(); return result; } @@ -713,12 +765,18 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler bindElementPhase() { - class BindElementPhase extends AbstractX4OPhaseHandler { - protected void setX4OPhase() { - phase = X4OPhase.bindElementPhase; + public X4OPhase bindElementPhase() { + class BindElementPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_BIND_ELEMENT"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_RUN_DIRTY"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { Element parentElement = element.getParent(); if(parentElement==null) { logger.finest("No parent element, so no binding needed."); @@ -735,12 +793,12 @@ public class X4OPhaseHandlerFactory { return; } - List binds = element.getElementLanguage().findElementBindingHandlers(parentObject, childObject); + List binds = element.getElementLanguage().getLanguage().findElementBindingHandlers(parentObject, childObject); logger.finest("Calling bindings handlers; "+binds.size()); try { for (ElementBindingHandler binding:binds) { - if (hasX4ODebugWriter()) { - getX4ODebugWriter().debugElementBindingHandler(binding,element); + if (element.getElementLanguage().hasX4ODebugWriter()) { + element.getElementLanguage().getX4ODebugWriter().debugElementBindingHandler(binding,element); } binding.doBind(parentObject,childObject,element); } @@ -749,7 +807,7 @@ public class X4OPhaseHandlerFactory { } } }; - X4OPhaseHandler result = new BindElementPhase(); + X4OPhase result = new BindElementPhase(); return result; } @@ -757,12 +815,18 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler runPhase() { - X4OPhaseHandler result = new AbstractX4OPhaseHandler() { - protected void setX4OPhase() { - phase = X4OPhase.runPhase; + public X4OPhase runPhase() { + X4OPhase result = new AbstractX4OPhase() { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; } - public void runElementPhase(Element element) throws X4OPhaseException { + public String getId() { + return "READ_RUN"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_BIND_ELEMENT"}; + } + public void runElementPhase(Element element) throws X4OPhaseException { if (element.isTransformingTree()) { return; // has already runned. } @@ -776,31 +840,112 @@ public class X4OPhaseHandlerFactory { } } }; - - class RunConfiguratorPhaseListener implements X4OPhaseListener { - /** - * @see org.x4o.xml.core.X4OPhaseListener#preRunPhase(org.x4o.xml.core.X4OPhaseHandler, org.x4o.xml.element.ElementLanguage) - */ - public void preRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { - } - /** - * @see org.x4o.xml.core.X4OPhaseListener#endRunPhase(org.x4o.xml.core.X4OPhaseHandler, org.x4o.xml.element.ElementLanguage) - */ - public void endRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { - for (RunConfigurator conf:runConf) { - try { - if (hasX4ODebugWriter()) { - getX4ODebugWriter().debugElementConfigurator(conf.elementConfigurator,conf.element); - } - conf.elementConfigurator.doConfigElement(conf.element); - } catch (ElementException e) { - throw new X4OPhaseException(phase,e); + return result; + } + + public class X4OPhaseReadRunConfigurator extends AbstractX4OPhase { + private List runConf = null; + protected X4OPhaseReadRunConfigurator() { + runConf = new ArrayList(10); + } + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_RUN_CONFIGURATOR"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_RUN"}; + } + public boolean isElementPhase() { + return false; + } + public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + for (RunConfigurator conf:runConf) { + try { + if (elementLanguage.hasX4ODebugWriter()) { + elementLanguage.getX4ODebugWriter().debugElementConfigurator(conf.elementConfigurator,conf.element); } + conf.elementConfigurator.doConfigElement(conf.element); + } catch (ElementException e) { + throw new X4OPhaseException(this,e); } - } } - result.addPhaseListener(new RunConfiguratorPhaseListener()); + @Override + public void runElementPhase(Element element) throws X4OPhaseException { + } + class RunConfigurator { + Element element; + ElementConfigurator elementConfigurator; + RunConfigurator(Element element,ElementConfigurator elementConfigurator) { + this.element=element; + this.elementConfigurator=elementConfigurator; + } + } + public void runElementConfigurator(ElementConfigurator ec,Element e,X4OPhase phase) throws X4OPhaseException { + if (ec.isConfigAction()) { + runConf.add(new RunConfigurator(e,ec)); + return; + } + try { + if (e.getElementLanguage().hasX4ODebugWriter()) { + e.getElementLanguage().getX4ODebugWriter().debugElementConfigurator(ec,e); + } + ec.doConfigElement(e); + + // may request rerun of config + if (ec.isConfigAction()) { + runConf.add(new RunConfigurator(e,ec)); + } + } catch (ElementException ee) { + throw new X4OPhaseException(phase,ee); + } + } + } + + /** + * + * @return The X4OPhaseHandler for this phase. + */ + public X4OPhaseReadRunConfigurator readRunConfiguratorPhase() { + return new X4OPhaseReadRunConfigurator(); + } + + /** + * Ends the read phase + * @return The X4OPhaseHandler for this phase. + */ + public X4OPhase readEndX4OPhase() { + class ReadStartX4OPhase extends AbstractX4OPhase { + public X4OPhaseType getType() { + return X4OPhaseType.XML_READ; + } + public String getId() { + return "READ_END"; + } + public String[] getPhaseDependencies() { + return new String[]{"READ_RUN_CONFIGURATOR"}; + } + public boolean isElementPhase() { + return false; + } + public void runElementPhase(Element element) throws X4OPhaseException { + // not used. + } + public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + // print the properties and classes for this language/config + if (elementLanguage.hasX4ODebugWriter()) { + try { + elementLanguage.getX4ODebugWriter().debugLanguageProperties(elementLanguage); + elementLanguage.getX4ODebugWriter().debugLanguageDefaultClasses(elementLanguage); + } catch (ElementException e) { + throw new X4OPhaseException(this,e); + } + } + } + }; + X4OPhase result = new ReadStartX4OPhase(); return result; } @@ -808,29 +953,29 @@ public class X4OPhaseHandlerFactory { * * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler releasePhase() { + public X4OPhase releasePhase() { // for debug output class ReleasePhaseListener implements X4OPhaseListener { private int elementsReleased = 0; /** - * @see org.x4o.xml.core.X4OPhaseListener#preRunPhase(org.x4o.xml.core.X4OPhaseHandler, org.x4o.xml.element.ElementLanguage) + * @see org.x4o.xml.core.phase.X4OPhaseListener#preRunPhase(org.x4o.xml.core.phase.X4OPhase, org.x4o.xml.element.ElementLanguage) */ - public void preRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { + public void preRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException { elementsReleased=0; } /** - * @see org.x4o.xml.core.X4OPhaseListener#endRunPhase(org.x4o.xml.core.X4OPhaseHandler, org.x4o.xml.element.ElementLanguage) + * @see org.x4o.xml.core.phase.X4OPhaseListener#endRunPhase(org.x4o.xml.core.phase.X4OPhase, org.x4o.xml.element.ElementLanguage) */ - public void endRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException { - if (hasX4ODebugWriter()==false) { + public void endRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException { + if (elementLanguage.hasX4ODebugWriter()==false) { return; } try { AttributesImpl atts = new AttributesImpl(); atts.addAttribute ("", "elements", "", "", elementsReleased+""); - getX4ODebugWriter().getDebugWriter().startElement (X4ODebugWriter.DEBUG_URI, "executeReleases", "", atts); - getX4ODebugWriter().getDebugWriter().endElement (X4ODebugWriter.DEBUG_URI, "executeReleases" , ""); + elementLanguage.getX4ODebugWriter().getDebugWriter().startElement (X4ODebugWriter.DEBUG_URI, "executeReleases", "", atts); + elementLanguage.getX4ODebugWriter().getDebugWriter().endElement (X4ODebugWriter.DEBUG_URI, "executeReleases" , ""); } catch (SAXException e) { throw new X4OPhaseException(phase,e); } @@ -842,9 +987,15 @@ public class X4OPhaseHandlerFactory { } final ReleasePhaseListener releaseCounter = new ReleasePhaseListener(); - X4OPhaseHandler result = new AbstractX4OPhaseHandler() { - protected void setX4OPhase() { - phase = X4OPhase.releasePhase; + X4OPhase result = new AbstractX4OPhase() { + public X4OPhaseType getType() { + return X4OPhaseType.XML_RW; + } + public String getId() { + return "X4O_RELEASE"; + } + public String[] getPhaseDependencies() { + return new String[] {"READ_END"}; } public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { } @@ -866,15 +1017,16 @@ public class X4OPhaseHandlerFactory { * Creates an debug phase * @return The X4OPhaseHandler for this phase. */ - public X4OPhaseHandler debugPhase() { - X4OPhaseHandler result = new AbstractX4OPhaseHandler() { - protected void setX4OPhase() { - phase = X4OPhase.debugPhase; - - // safety check - if (hasX4ODebugWriter()==false) { - throw new NullPointerException("Use debugPhase only when X4OParser.debugWriter is filled."); - } + public X4OPhase debugPhase(final X4OPhase afterPhase) { + X4OPhase result = new AbstractX4OPhase() { + public X4OPhaseType getType() { + return X4OPhaseType.XML_RW; + } + public String getId() { + return "X4O_DEBUG_"+afterPhase.getId(); + } + public String[] getPhaseDependencies() { + return new String[] {afterPhase.getId()}; } public boolean isElementPhase() { return false; @@ -882,18 +1034,22 @@ public class X4OPhaseHandlerFactory { public void runElementPhase(Element element) throws X4OPhaseException { } public void runPhase(ElementLanguage elementLanguage) throws X4OPhaseException { + // safety check + if (elementLanguage.hasX4ODebugWriter()==false) { + throw new X4OPhaseException(this,"Use debugPhase only when X4OParser.debugWriter is filled."); + } try { AttributesImpl atts = new AttributesImpl(); //atts.addAttribute ("", key, "", "", value); //atts.addAttribute ("", "verbose", "", "", "true"); - getX4ODebugWriter().getDebugWriter().startElement (X4ODebugWriter.DEBUG_URI, "printElementTree", "", atts); + elementLanguage.getX4ODebugWriter().getDebugWriter().startElement (X4ODebugWriter.DEBUG_URI, "printElementTree", "", atts); startedPrefix.clear(); printXML(elementLanguage.getRootElement()); for (String prefix:startedPrefix) { - getX4ODebugWriter().getDebugWriter().endPrefixMapping(prefix); + elementLanguage.getX4ODebugWriter().getDebugWriter().endPrefixMapping(prefix); } - getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "printElementTree", ""); - getX4ODebugWriter().debugElementLanguage(elementLanguage); + elementLanguage.getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "printElementTree", ""); + elementLanguage.getX4ODebugWriter().debugElementLanguage(elementLanguage); } catch (SAXException e) { throw new X4OPhaseException(this,e); } @@ -902,7 +1058,7 @@ public class X4OPhaseHandlerFactory { // note: slow version private String getNamespaceForElement(Element e) { - for (ElementLanguageModule mod:e.getElementLanguage().getElementLanguageModules()) { + for (ElementLanguageModule mod:e.getElementLanguage().getLanguage().getElementLanguageModules()) { for (ElementNamespaceContext enc:mod.getElementNamespaceContexts()) { List l = enc.getElementClasses(); if (l.contains(e.getElementClass())) { @@ -917,7 +1073,7 @@ public class X4OPhaseHandlerFactory { if (element==null) { throw new SAXException("Can't print debug xml of null element."); } - DefaultHandler2 handler = getX4ODebugWriter().getDebugWriter(); + DefaultHandler2 handler = element.getElementLanguage().getX4ODebugWriter().getDebugWriter(); if (element.getElementType().equals(Element.ElementType.comment)) { char[] msg = ((String)element.getElementObject()).toCharArray(); handler.comment(msg,0,msg.length); @@ -940,7 +1096,7 @@ public class X4OPhaseHandlerFactory { } String nameSpace = getNamespaceForElement(element); - String prefix = element.getElementLanguage().findElementNamespaceContext(nameSpace).getPrefixMapping(); + String prefix = element.getElementLanguage().getLanguage().findElementNamespaceContext(nameSpace).getPrefixMapping(); if (startedPrefix.contains(prefix)==false) { handler.startPrefixMapping(prefix, nameSpace); diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseListener.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseListener.java similarity index 90% rename from x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseListener.java rename to x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseListener.java index 075dfe4..a27518b 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OPhaseListener.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseListener.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.core; +package org.x4o.xml.core.phase; import org.x4o.xml.element.ElementLanguage; @@ -41,7 +41,7 @@ public interface X4OPhaseListener { * @param elementLanguage The elementLanguage of the driver. * @throws X4OPhaseException Is throws when listeners has error. */ - void preRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException; + void preRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException; /** * Gets called after the X4OPhaseHandler is runned. @@ -49,5 +49,5 @@ public interface X4OPhaseListener { * @param elementLanguage The elementLanguage of the driver. * @throws X4OPhaseException Is throws when listeners has error. */ - void endRunPhase(X4OPhaseHandler phase,ElementLanguage elementLanguage) throws X4OPhaseException; + void endRunPhase(X4OPhase phase,ElementLanguage elementLanguage) throws X4OPhaseException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManager.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManager.java new file mode 100644 index 0000000..7f4ff0b --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManager.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.core.phase; + +import java.util.Collection; +import java.util.List; + +import org.x4o.xml.element.Element; +import org.x4o.xml.element.ElementLanguage; + + +/** + * X4OPhaseManager stores the X4OPhaseHandler and puts them in the right order. + * And will execute the phases when runPhases is called. + * + * @author Willem Cazander + * @version 1.0 Jan 6, 2008 + */ +public interface X4OPhaseManager { + + /** + * Returns all the X4OPhaseHandlers. + * @return Returns all X4OPhaseHandlers. + */ + Collection getAllPhases(); + + /** + * Returns all the X4OPhaseHandlers in ordered list. + * @return Returns all X4OPhaseHandler is order. + */ + List getOrderedPhases(X4OPhaseType type); + + public void doReleasePhaseManual(ElementLanguage languageContext) throws X4OPhaseException; + + /** + * Runs all the phases in the right order. + * @throws X4OPhaseException When a running handlers throws one. + */ + public void runPhases(ElementLanguage elementContext,X4OPhaseType type) throws X4OPhaseException; + + /** + * Runs phase on single element. + * @param e The Element to process. + * @param p The phase to run. + * @throws X4OPhaseException When a running handlers throws one. + */ + public void runPhasesForElement(Element e,X4OPhaseType type,X4OPhase p) throws X4OPhaseException; +} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManagerFactory.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManagerFactory.java new file mode 100644 index 0000000..775b80d --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseManagerFactory.java @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.core.phase; + +import java.util.List; + +import org.x4o.xml.core.phase.X4OPhaseFactory.X4OPhaseReadRunConfigurator; +import org.x4o.xml.element.Element; +import org.x4o.xml.element.ElementLanguage; + + +/** + * X4OPhaseManagerFactory + * + * @author Willem Cazander + * @version 1.0 Apr 30, 2013 + */ +public class X4OPhaseManagerFactory { + + static public X4OPhaseManager createDefaultX4OPhaseManager() { + X4OPhaseFactory factory = new X4OPhaseFactory(); + DefaultX4OPhaseManager phaseManager = new DefaultX4OPhaseManager(); + createPhasesInit(phaseManager,factory); + createPhasesRead(phaseManager,factory); + return phaseManager; + } + + static private void createPhasesInit(DefaultX4OPhaseManager manager,X4OPhaseFactory factory) { + manager.addX4OPhase(factory.initX4OPhase()); + manager.addX4OPhase(factory.createLanguagePhase()); + manager.addX4OPhase(factory.createLanguageSiblingsPhase()); + } + + static private void createPhasesRead(DefaultX4OPhaseManager manager,X4OPhaseFactory factory) { + // main startup + manager.addX4OPhase(factory.readStartX4OPhase()); + //manager.addX4OPhase(factory.createLanguagePhase()); + //manager.addX4OPhase(factory.createLanguageSiblingsPhase()); + manager.addX4OPhase(factory.readSAXStreamPhase()); + + // inject and opt phase + manager.addX4OPhase(factory.configGlobalElBeansPhase()); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + // meta start point +// manager.addX4OPhase(factory.startX4OPhase()); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + // config + X4OPhaseReadRunConfigurator runConf = factory.readRunConfiguratorPhase(); + manager.addX4OPhase(factory.configElementPhase(runConf)); + manager.addX4OPhase(factory.configElementInterfacePhase(runConf)); + manager.addX4OPhase(factory.configGlobalElementPhase(runConf)); + manager.addX4OPhase(factory.configGlobalAttributePhase(runConf)); + + // run all attribute events + manager.addX4OPhase(factory.runAttributesPhase()); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + // templating + manager.addX4OPhase(factory.fillTemplatingPhase()); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + // transforming + manager.addX4OPhase(factory.transformPhase()); + manager.addX4OPhase(factory.runDirtyElementPhase(manager)); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + // binding elements + manager.addX4OPhase(factory.bindElementPhase()); + + // runing and releasing + manager.addX4OPhase(factory.runPhase()); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + manager.addX4OPhase(runConf); + + manager.addX4OPhase(factory.runDirtyElementLastPhase(manager)); +// if (elementLanguage.hasX4ODebugWriter()) {manager.addX4OPhaseHandler(factory.debugPhase());} + + + manager.addX4OPhase(factory.readEndX4OPhase()); + + // after release phase Element Tree is not avible anymore + manager.addX4OPhase(factory.releasePhase()); + + // Add debug phase listener to all phases +// if (elementLanguage.hasX4ODebugWriter()) { + //for (X4OPhase h:manager.getOrderedPhases()) { +// h.addPhaseListener(elementLanguage.getX4ODebugWriter().createDebugX4OPhaseListener()); + //} + //} + + // We are done + } + + enum R { + + /** Defines this meta startup phase. */ + startupX4OPhase(true), + + /** Load all meta info of the language we are creating. */ + createLanguagePhase(true), + + /** Load all siblings languages. */ + createLanguageSiblingsPhase(true), + + /** Parse the xml from sax events. */ + parseSAXStreamPhase(true), + + /** Optional extra config phase for injecting bean instances into the EL context. */ + configGlobalElBeansPhase(true), + + /** emty meta phase to refer to that sax is ready and element s are waiting for processing. */ + startX4OPhase(true), + + /** re runnable phases which config xml to beans and binds them together. */ + configElementPhase, + configElementInterfacePhase, + configGlobalElementPhase, + configGlobalAttributePhase, + + /** Fill the bean attributes from the Element xml attributes. */ + runAttributesPhase, + + /** Fill in the x4o templating objects. */ + fillTemplatingPhase, + + /** transform phase , modifies the Element Tree. */ + transformPhase, + + /** Run the phases which needs to be runned again from a phase. */ + runDirtyElementPhase(true), + + /** Binds objects together */ + bindElementPhase, + + /** Run action stuff, we are ready with it. */ + runPhase(true), + + /** Rerun all needed phases for all element that requested it. */ + runDirtyElementLastPhase, + + /** Releases all Elements, which clears attributes and childeren etc. */ + releasePhase(true), + + /** write all phases and stuff to debug sax stream. */ + debugPhase; + + /** Defines which phase we start, when context is created. */ + public static final R FIRST_PHASE = startupX4OPhase; + + /** The order in which the phases are executed */ + static final R[] PHASE_ORDER = { startupX4OPhase, + createLanguagePhase, + createLanguageSiblingsPhase, + + parseSAXStreamPhase, + configGlobalElBeansPhase, + startX4OPhase, + configElementPhase,configElementInterfacePhase,configGlobalElementPhase, + configGlobalAttributePhase,runAttributesPhase,fillTemplatingPhase, + transformPhase,runDirtyElementPhase,bindElementPhase, + runPhase,runDirtyElementLastPhase, + releasePhase + }; + + /** Boolean indicating that this phase only may be run'ed once. */ + private boolean runOnce = false; + + /** + * Creates an X4O Phase. + */ + private R() { + } + + /** + * Creates an X4O Phase + * @param runOnce Flag indicating that this phase is runnable multiple times. + */ + private R(boolean runOnce) { + this.runOnce=runOnce; + } + + /** + * Returns a flag indicating that this phase is runnable multiple times. + * @return True if phase is restricted to run once. + */ + public boolean isRunOnce() { + return runOnce; + } + } +} diff --git a/x4o-core/src/test/java/org/x4o/xml/test/TestParser.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseType.java similarity index 77% rename from x4o-core/src/test/java/org/x4o/xml/test/TestParser.java rename to x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseType.java index 90cd907..32e8dec 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/TestParser.java +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/X4OPhaseType.java @@ -21,23 +21,19 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.test; +package org.x4o.xml.core.phase; -import org.x4o.xml.core.X4ODriver; -import org.x4o.xml.core.X4OParser; -import org.x4o.xml.element.ElementLanguage; - -public class TestParser extends X4OParser { - - public TestParser() { - super("test"); - } +/** + * X4OPhaseType + * + * @author Willem Cazander + * @version 1.0 Apr 30, 2013 + */ +public enum X4OPhaseType { - public ElementLanguage getElementLanguage() { - return getDriver().getElementLanguage(); - } - - public X4ODriver getDriver() { - return super.getDriver(); - } + INIT, + XML_RW, + XML_READ, + XML_WRITE, + XML_WRITE_SCHEMA } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/phase/package-info.java b/x4o-core/src/main/java/org/x4o/xml/core/phase/package-info.java new file mode 100644 index 0000000..a113d9f --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/core/phase/package-info.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * The core phase classes which runs the different phases of the language. + * + * @since 1.0 + */ + +package org.x4o.xml.core.phase; \ No newline at end of file diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELContext.java b/x4o-core/src/main/java/org/x4o/xml/el/X4OELContext.java similarity index 98% rename from x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELContext.java rename to x4o-core/src/main/java/org/x4o/xml/el/X4OELContext.java index 2706266..b7a1e86 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELContext.java +++ b/x4o-core/src/main/java/org/x4o/xml/el/X4OELContext.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.el; +package org.x4o.xml.el; import java.util.HashMap; diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELFunctionMapper.java b/x4o-core/src/main/java/org/x4o/xml/el/X4OELFunctionMapper.java similarity index 98% rename from x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELFunctionMapper.java rename to x4o-core/src/main/java/org/x4o/xml/el/X4OELFunctionMapper.java index 0fc07ac..c6ce113 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELFunctionMapper.java +++ b/x4o-core/src/main/java/org/x4o/xml/el/X4OELFunctionMapper.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.el; +package org.x4o.xml.el; import java.lang.reflect.Method; import java.lang.reflect.Modifier; diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELResolver.java b/x4o-core/src/main/java/org/x4o/xml/el/X4OELResolver.java similarity index 99% rename from x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELResolver.java rename to x4o-core/src/main/java/org/x4o/xml/el/X4OELResolver.java index 3bf8b95..cf86341 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELResolver.java +++ b/x4o-core/src/main/java/org/x4o/xml/el/X4OELResolver.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.el; +package org.x4o.xml.el; import java.util.Iterator; import java.util.Map; diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELVariableMapper.java b/x4o-core/src/main/java/org/x4o/xml/el/X4OELVariableMapper.java similarity index 98% rename from x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELVariableMapper.java rename to x4o-core/src/main/java/org/x4o/xml/el/X4OELVariableMapper.java index 691cb70..32607c3 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/el/X4OELVariableMapper.java +++ b/x4o-core/src/main/java/org/x4o/xml/el/X4OELVariableMapper.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.impl.el; +package org.x4o.xml.el; import java.util.HashMap; import java.util.Map; diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/el/package-info.java b/x4o-core/src/main/java/org/x4o/xml/el/package-info.java similarity index 98% rename from x4o-core/src/main/java/org/x4o/xml/impl/el/package-info.java rename to x4o-core/src/main/java/org/x4o/xml/el/package-info.java index a489b32..70f88e2 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/el/package-info.java +++ b/x4o-core/src/main/java/org/x4o/xml/el/package-info.java @@ -28,4 +28,4 @@ * @since 1.0 */ -package org.x4o.xml.impl.el; +package org.x4o.xml.el; diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupport.java b/x4o-core/src/main/java/org/x4o/xml/eld/CelDriver.java similarity index 57% rename from x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupport.java rename to x4o-core/src/main/java/org/x4o/xml/eld/CelDriver.java index bdb634a..65bbb20 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupport.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/CelDriver.java @@ -23,26 +23,38 @@ package org.x4o.xml.eld; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.core.config.DefaultX4OLanguage; +import org.x4o.xml.core.config.DefaultX4OLanguageConfiguration; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.phase.X4OPhaseManagerFactory; +import org.x4o.xml.element.ElementLanguageModule; + /** - * EldParserSupport can write the eld schema. + * CelDriver is the Core Element Language driver. * * @author Willem Cazander - * @version 1.0 Aug 22, 2012 + * @version 1.0 Aug 20, 2005 */ -public class EldParserSupport implements X4OParserSupport { +public class CelDriver extends X4ODriver { + + /** Defines the identifier of the 'Core Element Language' language. */ + public static final String LANGUAGE_NAME = "cel"; + public static final String[] LANGUAGE_VERSIONS = new String[]{X4ODriver.DEFAULT_LANGUAGE_VERSION}; + + @Override + public String getLanguageName() { + return LANGUAGE_NAME; + } + + @Override + public String[] getLanguageVersions() { + return null; + } - /** - * Loads the ElementLanguage of this language parser for support. - * @return The loaded ElementLanguage. - * @throws X4OParserSupportException When support language could not be loaded. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() - */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - EldParser parser = new EldParser(false); - return parser.loadElementLanguageSupport(); + @Override + public X4OLanguage buildLanguage(String version) { + return new DefaultX4OLanguage(new DefaultX4OLanguageConfiguration(),X4OPhaseManagerFactory.createDefaultX4OPhaseManager(),getLanguageName(),getLanguageVersionDefault()); } } diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldDriver.java b/x4o-core/src/main/java/org/x4o/xml/eld/EldDriver.java new file mode 100644 index 0000000..4d974a0 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/eld/EldDriver.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.eld; + +import org.x4o.xml.X4ODriver; +import org.x4o.xml.core.config.DefaultX4OLanguage; +import org.x4o.xml.core.config.DefaultX4OLanguageConfiguration; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.phase.X4OPhaseManagerFactory; +import org.x4o.xml.element.ElementLanguageModule; + + +/** + * An Element Language Definition X4O parser. + * This eld parser config parent x4o parser with the eld x4o parser. + * + * @author Willem Cazander + * @version 1.0 Aug 20, 2005 + */ +public class EldDriver extends X4ODriver { + + /** Defines the identifier of the 'Element Language Description' language. */ + public static final String LANGUAGE_NAME = "eld"; + + /** Defines the identifier of the ELD x4o language. */ + public static final String[] LANGUAGE_VERSIONS = new String[]{X4ODriver.DEFAULT_LANGUAGE_VERSION}; + + @Override + public String getLanguageName() { + return LANGUAGE_NAME; + } + + @Override + public String[] getLanguageVersions() { + return LANGUAGE_VERSIONS; + } + + @Override + public X4OLanguage buildLanguage(String version) { + return new DefaultX4OLanguage(new DefaultX4OLanguageConfiguration(),X4OPhaseManagerFactory.createDefaultX4OPhaseManager(),getLanguageName(),getLanguageVersionDefault()); + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoader.java b/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoader.java index 93f8872..043bac7 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoader.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoader.java @@ -29,10 +29,15 @@ import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; +import org.x4o.xml.core.config.X4OLanguageLocal; import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementLanguageModuleLoader; import org.x4o.xml.element.ElementLanguageModuleLoaderException; +import org.x4o.xml.io.DefaultX4OReader; +import org.x4o.xml.io.X4OReader; import org.xml.sax.SAXException; /** @@ -47,6 +52,17 @@ public class EldModuleLoader implements ElementLanguageModuleLoader { private String eldResource = null; private boolean isEldCore = false; + /** The EL key to access the parent language configuration. */ + public static final String EL_PARENT_LANGUAGE_CONFIGURATION = "parentLanguageConfiguration"; + + /** The EL key to access the parent language module. */ + public static final String EL_PARENT_ELEMENT_LANGUAGE_MODULE = "parentElementLanguageModule"; + + /** The EL key to access the parent language element langauge. */ + public static final String EL_PARENT_LANGUAGE = "parentLanguage"; + + + /** * Creates an ELD/CEL module loader. * @param eldResource The resource to load. @@ -68,11 +84,31 @@ public class EldModuleLoader implements ElementLanguageModuleLoader { * @throws ElementLanguageModuleLoaderException When eld language could not be loaded. * @see org.x4o.xml.element.ElementLanguageModuleLoader#loadLanguageModule(org.x4o.xml.element.ElementLanguage, org.x4o.xml.element.ElementLanguageModule) */ - public void loadLanguageModule(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { + public void loadLanguageModule(X4OLanguageLocal language,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { logger.fine("Loading name eld file from resource: "+eldResource); try { - EldParser parser = new EldParser(elementLanguage,elementLanguageModule,isEldCore); - parser.parseResource(eldResource); + //EldDriver parser = new EldDriver(elementLanguage,elementLanguageModule,isEldCore); + + X4ODriver driver = null; + if (isEldCore) { + driver = X4ODriverManager.getX4ODriver(CelDriver.LANGUAGE_NAME); + } else { + driver = X4ODriverManager.getX4ODriver(EldDriver.LANGUAGE_NAME); + } + + ElementLanguage eldLang = driver.createLanguageContext(driver.getLanguageVersionDefault()); + X4OReader reader = new DefaultX4OReader(eldLang); //driver.createReader(); + + + reader.addELBeanInstance(EL_PARENT_LANGUAGE_CONFIGURATION, language.getLanguageConfiguration()); + reader.addELBeanInstance(EL_PARENT_LANGUAGE, language); + reader.addELBeanInstance(EL_PARENT_ELEMENT_LANGUAGE_MODULE, elementLanguageModule); + +// TODO: if (language.getLanguageConfiguration().getLanguagePropertyBoolean(X4OLanguageProperty.DEBUG_OUTPUT_ELD_PARSER)) { +// eldLang.setX4ODebugWriter(elementLanguage.getLanguageConfiguration().getX4ODebugWriter()); +// } + + reader.readResource(eldResource); } catch (FileNotFoundException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage()+" while parsing: "+eldResource,e); } catch (SecurityException e) { diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoaderCore.java b/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoaderCore.java index ed17353..a048ad6 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoaderCore.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/EldModuleLoaderCore.java @@ -28,7 +28,9 @@ import java.util.List; import java.util.logging.Logger; import org.x4o.xml.conv.text.ClassConverter; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.core.config.X4OLanguageClassLoader; +import org.x4o.xml.core.config.X4OLanguageLocal; import org.x4o.xml.eld.lang.BeanElement; import org.x4o.xml.eld.lang.DescriptionElement; import org.x4o.xml.eld.lang.ElementClassAddParentElement; @@ -41,7 +43,6 @@ import org.x4o.xml.eld.lang.ModuleElement; import org.x4o.xml.element.ElementBindingHandler; import org.x4o.xml.element.ElementClass; import org.x4o.xml.element.ElementClassAttribute; -import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementLanguageModuleLoader; import org.x4o.xml.element.ElementLanguageModuleLoaderException; @@ -84,41 +85,41 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { * @param elementLanguageModule The module to load it in. * @see org.x4o.xml.element.ElementLanguageModuleLoader#loadLanguageModule(org.x4o.xml.element.ElementLanguage, org.x4o.xml.element.ElementLanguageModule) */ - public void loadLanguageModule(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { + public void loadLanguageModule(X4OLanguageLocal language,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { elementLanguageModule.setId("cel-module"); elementLanguageModule.setName("Core Element Languag Module"); elementLanguageModule.setProviderName(PP_CEL_PROVIDER); List elementClassList = new ArrayList(10); - elementClassList.add(new DefaultElementClass("attribute",elementLanguage.getLanguageConfiguration().getDefaultElementClassAttribute())); + elementClassList.add(new DefaultElementClass("attribute",language.getLanguageConfiguration().getDefaultElementClassAttribute())); elementClassList.add(new DefaultElementClass("classConverter",ClassConverter.class)); - createElementClasses(elementClassList,elementLanguage); // adds all meta info + createElementClasses(elementClassList,language); // adds all meta info ElementClassAttribute attr; - DefaultElementClass ns = new DefaultElementClass("namespace",elementLanguage.getLanguageConfiguration().getDefaultElementNamespaceContext()); - attr = newElementClassAttribute(elementLanguage); + DefaultElementClass ns = new DefaultElementClass("namespace",language.getLanguageConfiguration().getDefaultElementNamespaceContext()); + attr = newElementClassAttribute(language); attr.setName("uri"); attr.setRequired(true); ns.addElementClassAttribute(attr); elementClassList.add(ns); - DefaultElementClass dec = new DefaultElementClass("element",elementLanguage.getLanguageConfiguration().getDefaultElementClass()); - attr = newElementClassAttribute(elementLanguage); + DefaultElementClass dec = new DefaultElementClass("element",language.getLanguageConfiguration().getDefaultElementClass()); + attr = newElementClassAttribute(language); attr.setName("objectClass"); attr.setObjectConverter(new ClassConverter()); dec.addElementClassAttribute(attr); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("elementClass"); attr.setObjectConverter(new ClassConverter()); dec.addElementClassAttribute(attr); elementClassList.add(dec); - DefaultElementClass ec = new DefaultElementClass("elementInterface",elementLanguage.getLanguageConfiguration().getDefaultElementInterface()); - attr = newElementClassAttribute(elementLanguage); + DefaultElementClass ec = new DefaultElementClass("elementInterface",language.getLanguageConfiguration().getDefaultElementInterface()); + attr = newElementClassAttribute(language); attr.setName("interfaceClass"); attr.setObjectConverter(new ClassConverter()); ec.addElementClassAttribute(attr); @@ -127,7 +128,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { logger.finer("Creating eldcore namespace."); ElementNamespaceContext namespace; try { - namespace = (ElementNamespaceContext)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementNamespaceContext()); + namespace = (ElementNamespaceContext)X4OLanguageClassLoader.newInstance(language.getLanguageConfiguration().getDefaultElementNamespaceContext()); } catch (InstantiationException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage(),e); } catch (IllegalAccessException e) { @@ -135,7 +136,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { } try { namespace.setElementNamespaceInstanceProvider((ElementNamespaceInstanceProvider) - X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider()) + X4OLanguageClassLoader.newInstance(language.getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider()) ); } catch (InstantiationException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage(),e); @@ -161,7 +162,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { addBindingHandler("cel-namespace-bind",new ElementNamespaceContextBindingHandler(),elementLanguageModule); try { - namespace.getElementNamespaceInstanceProvider().start(elementLanguage, namespace); + namespace.getElementNamespaceInstanceProvider().start(language, namespace); } catch (ElementNamespaceInstanceProviderException e) { throw new ElementLanguageModuleLoaderException(this,"Error starting instance provider: "+e.getMessage(),e); } @@ -171,7 +172,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { // And define root try { - namespace = (ElementNamespaceContext)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementNamespaceContext()); + namespace = (ElementNamespaceContext)X4OLanguageClassLoader.newInstance(language.getLanguageConfiguration().getDefaultElementNamespaceContext()); } catch (InstantiationException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage(),e); } catch (IllegalAccessException e) { @@ -179,7 +180,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { } try { namespace.setElementNamespaceInstanceProvider((ElementNamespaceInstanceProvider) - X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider()) + X4OLanguageClassLoader.newInstance(language.getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider()) ); } catch (InstantiationException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage(),e); @@ -192,10 +193,10 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { namespace.setSchemaUri(CEL_ROOT_XSD_URI); namespace.setSchemaResource(CEL_ROOT_XSD_FILE); namespace.setSchemaPrefix(CEL_ROOT); - namespace.addElementClass(new DefaultElementClass("module",elementLanguage.getLanguageConfiguration().getDefaultElementLanguageModule(),ModuleElement.class)); + namespace.addElementClass(new DefaultElementClass("module",language.getLanguageConfiguration().getDefaultElementLanguageModule(),ModuleElement.class)); namespace.setLanguageRoot(true); // Only define single language root so xsd is (mostly) not cicle import. try { - namespace.getElementNamespaceInstanceProvider().start(elementLanguage, namespace); + namespace.getElementNamespaceInstanceProvider().start(language, namespace); } catch (ElementNamespaceInstanceProviderException e) { throw new ElementLanguageModuleLoaderException(this,"Error starting instance provider: "+e.getMessage(),e); } @@ -208,18 +209,18 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { * @param elementClassList The list to fill. * @throws ElementLanguageModuleLoaderException */ - private void createElementClasses(List elementClassList,ElementLanguage elementLanguage) throws ElementLanguageModuleLoaderException { + private void createElementClasses(List elementClassList,X4OLanguage language) throws ElementLanguageModuleLoaderException { ElementClass ec = null; ElementClassAttribute attr = null; ec = new DefaultElementClass("bindingHandler",null,BeanElement.class); ec.addElementParent(CEL_ROOT_URI, "module"); ec.addElementParent(CEL_CORE_URI, "elementInterface"); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("id"); attr.setRequired(true); ec.addElementClassAttribute(attr); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("bean.class"); attr.setRequired(true); ec.addElementClassAttribute(attr); @@ -227,7 +228,7 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { ec = new DefaultElementClass("attributeHandler",null,BeanElement.class); ec.addElementParent(CEL_ROOT_URI, "module"); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("bean.class"); attr.setRequired(true); ec.addElementClassAttribute(attr); @@ -236,22 +237,22 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { ec = new DefaultElementClass("configurator",null,BeanElement.class); ec.addElementParent(CEL_CORE_URI, "elementInterface"); ec.addElementParent(CEL_CORE_URI, "element"); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("bean.class"); attr.setRequired(true); ec.addElementClassAttribute(attr); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("configAction"); ec.addElementClassAttribute(attr); elementClassList.add(ec); ec = new DefaultElementClass("configuratorGlobal",null,BeanElement.class); ec.addElementParent(CEL_ROOT_URI, "module"); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("bean.class"); attr.setRequired(true); ec.addElementClassAttribute(attr); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("configAction"); ec.addElementClassAttribute(attr); elementClassList.add(ec); @@ -272,11 +273,11 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { ec = new DefaultElementClass("elementParent",null,ElementClassAddParentElement.class); ec.addElementParent(CEL_CORE_URI, "element"); ec.addElementParent(CEL_CORE_URI, "elementInterface"); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("tag"); attr.setRequired(true); ec.addElementClassAttribute(attr); - attr = newElementClassAttribute(elementLanguage); + attr = newElementClassAttribute(language); attr.setName("uri"); ec.addElementClassAttribute(attr); elementClassList.add(ec); @@ -288,9 +289,9 @@ public class EldModuleLoaderCore implements ElementLanguageModuleLoader { * @return The new ElementClassAttribute instance. * @throws ElementLanguageModuleLoaderException When class could not be created. */ - private ElementClassAttribute newElementClassAttribute(ElementLanguage elementLanguage) throws ElementLanguageModuleLoaderException { + private ElementClassAttribute newElementClassAttribute(X4OLanguage language) throws ElementLanguageModuleLoaderException { try { - return (ElementClassAttribute)X4OLanguageClassLoader.newInstance(elementLanguage.getLanguageConfiguration().getDefaultElementClassAttribute()); + return (ElementClassAttribute)X4OLanguageClassLoader.newInstance(language.getLanguageConfiguration().getDefaultElementClassAttribute()); } catch (InstantiationException e) { throw new ElementLanguageModuleLoaderException(this,e.getMessage(),e); } catch (IllegalAccessException e) { diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldParser.java b/x4o-core/src/main/java/org/x4o/xml/eld/EldParser.java deleted file mode 100644 index b73b8aa..0000000 --- a/x4o-core/src/main/java/org/x4o/xml/eld/EldParser.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2004-2012, Willem Cazander - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are permitted provided - * that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright notice, this list of conditions and the - * following disclaimer. - * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and - * the following disclaimer in the documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT - * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package org.x4o.xml.eld; - -import org.x4o.xml.core.X4ODriver; -import org.x4o.xml.core.X4OParser; -import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.element.ElementLanguageModule; - - -/** - * An Element Language Definition X4O parser. - * This eld parser config parent x4o parser with the eld x4o parser. - * - * @author Willem Cazander - * @version 1.0 Aug 20, 2005 - */ -public class EldParser extends X4OParser { - - /** Defines the identifier of the ELD x4o language. */ - public static final String ELD_VERSION = X4ODriver.DEFAULT_LANGUAGE_VERSION; - - /** Defines the identifier of the 'Element Language Description' language. */ - public static final String ELD_LANGUAGE = "eld"; - - /** Defines the identifier of the 'Core Element Language' language. */ - public static final String CEL_LANGUAGE = "cel"; - - /** The EL key to access the parent language configuration. */ - public static final String EL_PARENT_LANGUAGE_CONFIGURATION = "parentLanguageConfiguration"; - - /** The EL key to access the parent language module. */ - public static final String EL_PARENT_ELEMENT_LANGUAGE_MODULE = "parentElementLanguageModule"; - - /** The EL key to access the parent language element langauge. */ - public static final String EL_PARENT_LANGUAGE_ELEMENT_LANGUAGE = "parentLanguageElementLanguage"; - - /** - * Creates an Eld language parser for the language support. - * @param isEldCore If true then langauge is not eld but cel. - */ - protected EldParser(boolean isEldCore) { - super(isEldCore?CEL_LANGUAGE:ELD_LANGUAGE,ELD_VERSION); - } - - /** - * Returns the X4ODriver object. - * @return The X4ODriver. - */ - protected X4ODriver getDriver() { - X4ODriver driver = super.getDriver(); - // FAKE operation to make PMD happy as it does not see that "Overriding method merely calls super" - // this method is here only for visibility for unit tests of this package. - driver.getProperty(X4OLanguagePropertyKeys.LANGUAGE_NAME); - return driver; - } - - /** - * Creates the ELD x4o language parser. - * @param elementLanguage The elementLanguage to fill. - * @param elementLanguageModule The elementLanguageModule from to fill. - */ - public EldParser(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) { - this(elementLanguage,elementLanguageModule,false); - } - - /** - * Creates the ELD or CEL x4o language parser. - * @param elementLanguage The elementLanguage to fill. - * @param elementLanguageModule The elementLanguageModule from to fill. - * @param isEldCore If true then langauge is not eld but cel. - */ - public EldParser(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule,boolean isEldCore) { - this(isEldCore); - if (elementLanguage.getLanguageConfiguration().getLanguagePropertyBoolean(X4OLanguageProperty.DEBUG_OUTPUT_ELD_PARSER)) { - getDriver().getElementLanguage().getLanguageConfiguration().setX4ODebugWriter(elementLanguage.getLanguageConfiguration().getX4ODebugWriter()); - } - addELBeanInstance(EL_PARENT_LANGUAGE_CONFIGURATION, elementLanguage.getLanguageConfiguration()); - addELBeanInstance(EL_PARENT_LANGUAGE_ELEMENT_LANGUAGE, elementLanguage); - addELBeanInstance(EL_PARENT_ELEMENT_LANGUAGE_MODULE, elementLanguageModule); - } -} diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/lang/ElementModuleBindingHandler.java b/x4o-core/src/main/java/org/x4o/xml/eld/lang/ElementModuleBindingHandler.java index 9058e6e..2b8b053 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/lang/ElementModuleBindingHandler.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/lang/ElementModuleBindingHandler.java @@ -25,9 +25,10 @@ package org.x4o.xml.eld.lang; import java.util.Map; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.core.config.X4OLanguageClassLoader; import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.eld.EldParser; +import org.x4o.xml.eld.EldModuleLoader; import org.x4o.xml.element.AbstractElementBindingHandler; import org.x4o.xml.element.Element; import org.x4o.xml.element.ElementAttributeHandler; @@ -80,11 +81,11 @@ public class ElementModuleBindingHandler extends AbstractElementBindingHandler public void doBind(Object parentObject, Object childObject,Element childElement) throws ElementBindingHandlerException { @SuppressWarnings("rawtypes") - Map m = (Map)childElement.getElementLanguage().getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); + Map m = (Map)childElement.getElementLanguage().getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); if (m==null) { return; } - ElementLanguage x4oParsingContext = (ElementLanguage)m.get(EldParser.EL_PARENT_LANGUAGE_ELEMENT_LANGUAGE); + X4OLanguage x4oParsingContext = (X4OLanguage)m.get(EldModuleLoader.EL_PARENT_LANGUAGE); //ElementLanguageModule elementLanguageModule = (ElementLanguageModule)m.get(EldParser.PARENT_ELEMENT_LANGUAGE_MODULE); ElementLanguageModule elementLanguageModule = (ElementLanguageModule)parentObject; if (x4oParsingContext==null) { @@ -102,7 +103,7 @@ public class ElementModuleBindingHandler extends AbstractElementBindingHandler if (childObject instanceof ElementNamespaceContext) { ElementNamespaceContext elementNamespaceContext = (ElementNamespaceContext)childObject; try { - elementNamespaceContext.setElementNamespaceInstanceProvider((ElementNamespaceInstanceProvider)X4OLanguageClassLoader.newInstance(childElement.getElementLanguage().getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider())); + elementNamespaceContext.setElementNamespaceInstanceProvider((ElementNamespaceInstanceProvider)X4OLanguageClassLoader.newInstance(childElement.getElementLanguage().getLanguage().getLanguageConfiguration().getDefaultElementNamespaceInstanceProvider())); } catch (Exception e) { throw new ElementBindingHandlerException("Error loading: "+e.getMessage(),e); } diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/lang/ModuleElement.java b/x4o-core/src/main/java/org/x4o/xml/eld/lang/ModuleElement.java index 05c4941..b0f5d12 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/lang/ModuleElement.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/lang/ModuleElement.java @@ -26,7 +26,7 @@ package org.x4o.xml.eld.lang; import java.util.Map; import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.eld.EldParser; +import org.x4o.xml.eld.EldModuleLoader; import org.x4o.xml.element.AbstractElement; import org.x4o.xml.element.ElementException; import org.x4o.xml.element.ElementLanguageModule; @@ -50,11 +50,11 @@ public class ModuleElement extends AbstractElement { throw new ElementException("Need to be root tag"); } @SuppressWarnings("rawtypes") - Map m = (Map)getElementLanguage().getLanguageConfiguration().getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); + Map m = (Map)getElementLanguage().getLanguageProperty(X4OLanguageProperty.EL_BEAN_INSTANCE_MAP); if (m==null) { return; } - ElementLanguageModule elementLanguageModule = (ElementLanguageModule)m.get(EldParser.EL_PARENT_ELEMENT_LANGUAGE_MODULE); + ElementLanguageModule elementLanguageModule = (ElementLanguageModule)m.get(EldModuleLoader.EL_PARENT_ELEMENT_LANGUAGE_MODULE); setElementObject(elementLanguageModule); } } diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlGenerator.java b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlGenerator.java index 519479c..76d684c 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlGenerator.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlGenerator.java @@ -26,12 +26,12 @@ package org.x4o.xml.eld.xsd; import java.io.File; import java.io.FileOutputStream; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.element.ElementClass; -import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementException; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementNamespaceContext; -import org.x4o.xml.sax.XMLWriter; +import org.x4o.xml.io.sax.XMLWriter; import org.xml.sax.SAXException; import org.xml.sax.ext.DefaultHandler2; @@ -43,10 +43,10 @@ import org.xml.sax.ext.DefaultHandler2; */ public class EldXsdXmlGenerator { - private ElementLanguage context = null; + private X4OLanguage language = null; - public EldXsdXmlGenerator(ElementLanguage context) { - this.context=context; + public EldXsdXmlGenerator(X4OLanguage language) { + this.language=language; } @@ -62,7 +62,7 @@ public class EldXsdXmlGenerator { public void writeSchema(File basePath,String namespace) throws ElementException { try { if (namespace!=null) { - ElementNamespaceContext ns = context.findElementNamespaceContext(namespace); + ElementNamespaceContext ns = language.findElementNamespaceContext(namespace); if (ns==null) { throw new NullPointerException("Could not find namespace: "+namespace); } @@ -76,7 +76,7 @@ public class EldXsdXmlGenerator { } return; } - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:language.getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { checkNamespace(ns); FileOutputStream fio = new FileOutputStream(new File(basePath.getAbsolutePath()+File.separatorChar+ns.getSchemaResource())); @@ -96,14 +96,14 @@ public class EldXsdXmlGenerator { public void generateSchema(String namespaceUri,DefaultHandler2 xmlWriter) throws SAXException { - ElementNamespaceContext ns = context.findElementNamespaceContext(namespaceUri); + ElementNamespaceContext ns = language.findElementNamespaceContext(namespaceUri); if (ns==null) { throw new NullPointerException("Could not find namespace: "+namespaceUri); } - EldXsdXmlWriter xsdWriter = new EldXsdXmlWriter(xmlWriter,context); + EldXsdXmlWriter xsdWriter = new EldXsdXmlWriter(xmlWriter,language); xsdWriter.startNamespaces(namespaceUri); - xsdWriter.startSchema(ns,context); + xsdWriter.startSchema(ns); for (ElementClass ec:ns.getElementClasses()) { xsdWriter.writeElementClass(ec,ns); } diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlWriter.java b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlWriter.java index b997996..91dc6ed 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlWriter.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/EldXsdXmlWriter.java @@ -33,12 +33,12 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.element.ElementAttributeHandler; import org.x4o.xml.element.ElementBindingHandler; import org.x4o.xml.element.ElementClass; import org.x4o.xml.element.ElementClassAttribute; import org.x4o.xml.element.ElementInterface; -import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementNamespaceContext; import org.xml.sax.SAXException; @@ -58,14 +58,14 @@ public class EldXsdXmlWriter { static public final String SCHEMA_URI = "http://www.w3.org/2001/XMLSchema"; - protected ElementLanguage context = null; + protected X4OLanguage language = null; protected DefaultHandler2 xmlWriter = null; protected String writeNamespace = null; protected Map namespaces = null; - public EldXsdXmlWriter(DefaultHandler2 xmlWriter,ElementLanguage context) { + public EldXsdXmlWriter(DefaultHandler2 xmlWriter,X4OLanguage language) { this.xmlWriter=xmlWriter; - this.context=context; + this.language=language; this.namespaces=new HashMap(10); } @@ -110,27 +110,27 @@ public class EldXsdXmlWriter { this.namespaces.clear(); // redo this mess, add nice find for binding handlers - for (ElementLanguageModule modContext:context.getElementLanguageModules()) { + for (ElementLanguageModule modContext:language.getElementLanguageModules()) { for (ElementNamespaceContext nsContext:modContext.getElementNamespaceContexts()) { for (ElementClass ec:nsContext.getElementClasses()) { Class objectClass = null; if (ec.getObjectClass()!=null) { objectClass = ec.getObjectClass(); - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:language.getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { for (ElementClass checkClass:ns.getElementClasses()) { if (checkClass.getObjectClass()==null) { continue; } Class checkObjectClass = checkClass.getObjectClass(); - List b = context.findElementBindingHandlers(objectClass,checkObjectClass); + List b = language.findElementBindingHandlers(objectClass,checkObjectClass); if (b.isEmpty()==false) { startNamespace(ns.getUri(),ns.getSchemaPrefix()); } } } } - for (ElementInterface ei:context.findElementInterfaces(objectClass)) { + for (ElementInterface ei:language.findElementInterfaces(objectClass)) { List eiTags = ei.getElementParents(namespaceUri); if (eiTags!=null) { startNamespace(nsContext.getUri(),nsContext.getSchemaPrefix()); @@ -146,7 +146,7 @@ public class EldXsdXmlWriter { private static final String COMMENT_SEPERATOR = " ==================================================================== "; private static final String COMMENT_TEXT = "====="; - public void startSchema(ElementNamespaceContext ns,ElementLanguage elementLanguage) throws SAXException { + public void startSchema(ElementNamespaceContext ns) throws SAXException { xmlWriter.startDocument(); @@ -156,7 +156,7 @@ public class EldXsdXmlWriter { xmlWriter.ignorableWhitespace(msg,0,msg.length); msg = COMMENT_SEPERATOR.toCharArray(); xmlWriter.comment(msg,0,msg.length); - String desc = "Automatic generated schema for language: "+elementLanguage.getLanguageConfiguration().getLanguage(); + String desc = "Automatic generated schema for language: "+language.getLanguageName(); int space = COMMENT_SEPERATOR.length()-desc.length()-(2*COMMENT_TEXT.length())-4; StringBuffer b = new StringBuffer(COMMENT_SEPERATOR.length()); b.append(" "); @@ -181,7 +181,7 @@ public class EldXsdXmlWriter { xmlWriter.ignorableWhitespace(msg,0,msg.length); ElementLanguageModule module = null; - for (ElementLanguageModule elm:elementLanguage.getElementLanguageModules()) { + for (ElementLanguageModule elm:language.getElementLanguageModules()) { ElementNamespaceContext s = elm.getElementNamespaceContext(ns.getUri()); if (s!=null) { module = elm; @@ -223,7 +223,7 @@ public class EldXsdXmlWriter { if (ns.getUri().equals(uri)) { continue; } - ElementNamespaceContext nsContext = context.findElementNamespaceContext(uri); + ElementNamespaceContext nsContext = language.findElementNamespaceContext(uri); atts = new AttributesImpl(); atts.addAttribute ("", "namespace", "", "", nsContext.getUri()); atts.addAttribute ("", "schemaLocation", "", "", nsContext.getSchemaResource()); @@ -272,7 +272,7 @@ public class EldXsdXmlWriter { atts.addAttribute ("", "maxOccurs", "", "", "unbounded"); xmlWriter.startElement (SCHEMA_URI, "choice", "", atts); - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:language.getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { writeElementClassNamespaces(ec,nsWrite,ns); } @@ -293,7 +293,7 @@ public class EldXsdXmlWriter { xmlWriter.endElement(SCHEMA_URI, "attribute", ""); } - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:language.getElementLanguageModules()) { for (ElementAttributeHandler eah:mod.getElementAttributeHandlers()) { attrNames.add(eah.getAttributeName()); atts = new AttributesImpl(); @@ -381,7 +381,7 @@ public class EldXsdXmlWriter { if (checkClass.getObjectClass()==null) { continue; } - for (ElementInterface ei:context.findElementInterfaces(checkClass.getObjectClass())) { + for (ElementInterface ei:language.findElementInterfaces(checkClass.getObjectClass())) { parents = ei.getElementParents(nsWrite.getUri()); if (parents!=null && parents.contains(ecWrite.getTag())) { refElements.add(checkClass.getTag()); @@ -393,7 +393,7 @@ public class EldXsdXmlWriter { } Class objectClass = ecWrite.getObjectClass(); Class checkObjectClass = checkClass.getObjectClass(); - List b = context.findElementBindingHandlers(objectClass,checkObjectClass); + List b = language.findElementBindingHandlers(objectClass,checkObjectClass); if (b.isEmpty()==false) { refElements.add(checkClass.getTag()); } diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OLanguageEldXsdWriter.java b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OSchemaWriterExecutor.java similarity index 59% rename from x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OLanguageEldXsdWriter.java rename to x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OSchemaWriterExecutor.java index 4ab1688..1e6ac93 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OLanguageEldXsdWriter.java +++ b/x4o-core/src/main/java/org/x4o/xml/eld/xsd/X4OSchemaWriterExecutor.java @@ -28,11 +28,10 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.core.config.X4OLanguageClassLoader; -import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; import org.x4o.xml.element.ElementException; +import org.x4o.xml.io.X4OSchemaWriter; /** * X4OLanguageSchemaWriter is support class to write schema files from eld. @@ -40,22 +39,22 @@ import org.x4o.xml.element.ElementException; * @author Willem Cazander * @version 1.0 Aug 22, 2012 */ -public class X4OLanguageEldXsdWriter { +public class X4OSchemaWriterExecutor { - private Class languageParserSupport = null; + private String language = null; private String languageNamespaceUri = null; private File basePath; - @SuppressWarnings("unchecked") static public void main(String argu[]) { - X4OLanguageEldXsdWriter languageSchema = new X4OLanguageEldXsdWriter(); + X4OSchemaWriterExecutor languageSchema = new X4OSchemaWriterExecutor(); List arguList = Arrays.asList(argu); Iterator arguIterator = arguList.iterator(); + boolean printStack = false; while (arguIterator.hasNext()) { String arg = arguIterator.next(); - if ("-path".equals(arg)) { + if ("-path".equals(arg) || "-p".equals(arg)) { if (arguIterator.hasNext()==false) { - System.out.println("No argument for -path given."); + System.out.println("No argument for "+arg+" given."); System.exit(1); return; } @@ -68,73 +67,60 @@ public class X4OLanguageEldXsdWriter { languageSchema.setBasePath(schemaBasePath); continue; } - if ("-uri".equals(arg)) { + if ("-language".equals(arg) || "-l".equals(arg)) { if (arguIterator.hasNext()==false) { - System.out.println("No argument for -uri given."); + System.out.println("No argument for "+arg+" given."); System.exit(1); return; } - languageSchema.setLanguageNamespaceUri(arguIterator.next()); + languageSchema.setLanguage(arguIterator.next()); continue; } - if ("-class".equals(arg)) { - if (arguIterator.hasNext()==false) { - System.out.println("No argument for -class given."); - System.exit(1); - return; - } - String apiClass = arguIterator.next(); - try { - languageSchema.setLanguageParserSupport((Class) X4OLanguageClassLoader.loadClass(apiClass)); - } catch (ClassNotFoundException e) { - System.out.println("Schema api class is not found: "+apiClass); - System.exit(1); - return; - } - continue; + if ("-verbose".equals(arg) || "-v".equals(arg)) { + printStack = true; } } + Exception e = null; try { languageSchema.execute(); - } catch (X4OParserSupportException e) { + } catch (ElementException e1) { + e = e1; + } catch (InstantiationException e2) { + e = e2; + } catch (IllegalAccessException e3) { + e = e3; + } + if (e!=null) { System.out.println("Error while schema writing: "+e.getMessage()); - e.printStackTrace(); + if (printStack) { + e.printStackTrace(); + } System.exit(1); return; + } else { + return; } } - public void execute() throws X4OParserSupportException { - try { - // Get the support context - X4OParserSupport languageSupport = (X4OParserSupport)getLanguageParserSupport().newInstance(); - ElementLanguage context = languageSupport.loadElementLanguageSupport(); - - // Start xsd generator - EldXsdXmlGenerator xsd = new EldXsdXmlGenerator(context); - xsd.writeSchema(getBasePath(), getLanguageNamespaceUri()); - - } catch (InstantiationException e) { - throw new X4OParserSupportException(e); - } catch (IllegalAccessException e) { - throw new X4OParserSupportException(e); - } catch (ElementException e) { - throw new X4OParserSupportException(e); - } + public void execute() throws ElementException, InstantiationException, IllegalAccessException { + // Start xsd generator + X4ODriver driver = X4ODriverManager.getX4ODriver(getLanguage()); + X4OSchemaWriter xsd = driver.createSchemaWriter(driver.getLanguageVersionDefault()); + xsd.writeSchema(getBasePath(), getLanguageNamespaceUri()); } /** - * @return the languageParserSupport + * @return the language */ - public Class getLanguageParserSupport() { - return languageParserSupport; + public String getLanguage() { + return language; } /** - * @param languageParserSupport the languageParserSupport to set + * @param language the language to set */ - public void setLanguageParserSupport(Class languageParserSupport) { - this.languageParserSupport = languageParserSupport; + public void setLanguage(String language) { + this.language = language; } /** diff --git a/x4o-core/src/main/java/org/x4o/xml/element/AbstractElement.java b/x4o-core/src/main/java/org/x4o/xml/element/AbstractElement.java index 3c2fe32..095f048 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/AbstractElement.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/AbstractElement.java @@ -132,7 +132,7 @@ public abstract class AbstractElement implements Element { */ public void doCharacters(String characters) throws ElementException { try { - Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguageConfiguration().getDefaultElementBodyCharacters()); + Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguage().getLanguageConfiguration().getDefaultElementBodyCharacters()); e.setElementObject(characters); addChild(e); } catch (Exception exception) { @@ -145,7 +145,7 @@ public abstract class AbstractElement implements Element { */ public void doComment(String comment) throws ElementException { try { - Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguageConfiguration().getDefaultElementBodyComment()); + Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguage().getLanguageConfiguration().getDefaultElementBodyComment()); e.setElementObject(comment); addChild(e); } catch (Exception exception) { @@ -158,7 +158,7 @@ public abstract class AbstractElement implements Element { */ public void doIgnorableWhitespace(String space) throws ElementException { try { - Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguageConfiguration().getDefaultElementBodyWhitespace()); + Element e = (Element)X4OLanguageClassLoader.newInstance(getElementLanguage().getLanguage().getLanguageConfiguration().getDefaultElementBodyWhitespace()); e.setElementObject(space); addChild(e); } catch (Exception exception) { diff --git a/x4o-core/src/main/java/org/x4o/xml/element/AbstractElementLanguage.java b/x4o-core/src/main/java/org/x4o/xml/element/AbstractElementLanguage.java index ae26d5e..5f2c136 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/AbstractElementLanguage.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/AbstractElementLanguage.java @@ -23,17 +23,17 @@ package org.x4o.xml.element; -import java.util.List; import java.util.Map; import java.util.HashMap; -import java.util.ArrayList; import java.util.logging.Logger; import javax.el.ELContext; import javax.el.ExpressionFactory; -import org.x4o.xml.core.X4OPhase; -import org.x4o.xml.core.config.X4OLanguageConfiguration; +import org.x4o.xml.core.X4ODebugWriter; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.config.X4OLanguageProperty; +import org.x4o.xml.core.phase.X4OPhase; /** * An AbstractElementLanguage. @@ -44,6 +44,7 @@ import org.x4o.xml.core.config.X4OLanguageConfiguration; public abstract class AbstractElementLanguage implements ElementLanguageLocal { private Logger logger = null; + private X4OLanguage language = null; private ExpressionFactory expressionFactory = null; private ELContext eLContext = null; private ElementAttributeValueParser elementAttributeValueParser = null; @@ -51,18 +52,33 @@ public abstract class AbstractElementLanguage implements ElementLanguageLocal { private X4OPhase currentX4OPhase = null; private Map dirtyElements = null; private Element rootElement = null; - private X4OLanguageConfiguration languageConfiguration = null; - private List elementLanguageModules = null; + private X4ODebugWriter debugWriter; + private Map languageProperties; /** * Creates a new empty ElementLanguage. */ - public AbstractElementLanguage() { + public AbstractElementLanguage(X4OLanguage language,String languageVersion) { + if (language==null) { + throw new NullPointerException("language may not be null"); + } + if (languageVersion==null) { + throw new NullPointerException("languageVersion may not be null"); + } + if (languageVersion.length()==0) { + throw new IllegalArgumentException("languageVersion may not be empty"); + } logger = Logger.getLogger(AbstractElementLanguage.class.getName()); logger.finest("Creating new ParsingContext"); - elementLanguageModules = new ArrayList(20); - currentX4OPhase = X4OPhase.FIRST_PHASE; + this.language=language; dirtyElements = new HashMap(40); + languageProperties = new HashMap(20); + languageProperties.put(X4OLanguageProperty.LANGUAGE_NAME.toUri(), language.getLanguageName()); + languageProperties.put(X4OLanguageProperty.LANGUAGE_VERSION.toUri(), languageVersion); + } + + public X4OLanguage getLanguage() { + return language; } /** @@ -141,14 +157,14 @@ public abstract class AbstractElementLanguage implements ElementLanguageLocal { } /** - * @see org.x4o.xml.element.ElementLanguage#setCurrentX4OPhase(org.x4o.xml.core.X4OPhase) + * @see org.x4o.xml.element.ElementLanguage#setCurrentX4OPhase(org.x4o.xml.core.phase.X4OPhase) */ public void setCurrentX4OPhase(X4OPhase currentX4OPhase) { this.currentX4OPhase = currentX4OPhase; } /** - * @see org.x4o.xml.element.ElementLanguage#addDirtyElement(org.x4o.xml.element.Element, org.x4o.xml.core.X4OPhase) + * @see org.x4o.xml.element.ElementLanguage#addDirtyElement(org.x4o.xml.element.Element, org.x4o.xml.core.phase.X4OPhase) */ public void addDirtyElement(Element element, X4OPhase phase) { if (dirtyElements.containsKey(element)) { @@ -184,120 +200,80 @@ public abstract class AbstractElementLanguage implements ElementLanguageLocal { //} rootElement=element; } - - /** - * @return the languageConfiguration - */ - public X4OLanguageConfiguration getLanguageConfiguration() { - return languageConfiguration; - } - - /** - * @param languageConfiguration the languageConfiguration to set - */ - public void setLanguageConfiguration(X4OLanguageConfiguration languageConfiguration) { - this.languageConfiguration = languageConfiguration; - } - - /** - * @see org.x4o.xml.element.ElementLanguage#addElementLanguageModule(org.x4o.xml.element.ElementLanguageModule) - */ - public void addElementLanguageModule(ElementLanguageModule elementLanguageModule) { - if (elementLanguageModule.getId()==null) { - throw new NullPointerException("Can't add module without id."); - } - elementLanguageModules.add(elementLanguageModule); - } - - /** - * @see org.x4o.xml.element.ElementLanguage#getElementLanguageModules() - */ - public List getElementLanguageModules() { - return elementLanguageModules; + + public Object getLanguageProperty(String key) { + return languageProperties.get(key); } - - /** - * @see org.x4o.xml.element.ElementLanguage#findElementBindingHandlers(java.lang.Object,java.lang.Object) - */ - public List findElementBindingHandlers(Object parent,Object child) { - List result = new ArrayList(50); - for (int i=0;i result,List checkList) { - for (ElementBindingHandler binding:checkList) { - boolean parentBind = false; - if (parent instanceof Class) { - parentBind = binding.getBindParentClass().isAssignableFrom((Class)parent); - } else { - parentBind = binding.getBindParentClass().isInstance(parent); - } - if (parentBind==false) { - continue; - } - boolean childBind = false; - for (Class childClass:binding.getBindChildClasses()) { - if (child instanceof Class && childClass.isAssignableFrom((Class)child)) { - childBind=true; - break; - } else if (childClass.isInstance(child)) { - childBind=true; - break; - } - } - if (parentBind & childBind) { - result.add(binding); - } - } + public void setLanguageProperty(String key,Object value) { + languageProperties.put(key, value); } /** - * @see org.x4o.xml.element.ElementLanguage#findElementInterfaces(java.lang.Object) + * @see org.x4o.xml.core.config.X4OLanguageConfiguration#getLanguageProperty(org.x4o.xml.core.config.X4OLanguageProperty) */ - public List findElementInterfaces(Object elementObject) { - if (elementObject==null) { - throw new NullPointerException("Can't search for null object."); - } - List result = new ArrayList(50); - for (int i=0;i eClass = ei.getInterfaceClass(); - logger.finest("Checking interface handler: "+ei+" for class: "+eClass); - if (elementObject instanceof Class && eClass.isAssignableFrom((Class)elementObject)) { - logger.finer("Found interface match from class; "+elementObject); - result.add(ei); - } else if (eClass.isInstance(elementObject)) { - logger.finer("Found interface match from object; "+elementObject); - result.add(ei); - } - } - } - return result; + public Object getLanguageProperty(X4OLanguageProperty property) { + return getLanguageProperty(property.toUri()); } /** - * @see org.x4o.xml.element.ElementLanguage#findElementNamespaceContext(java.lang.String) + * @see org.x4o.xml.core.config.X4OLanguageConfiguration#setLanguageProperty(org.x4o.xml.core.config.X4OLanguageProperty, java.lang.Object) */ - public ElementNamespaceContext findElementNamespaceContext(String namespaceUri) { - - // TODO: refactor so no search for every tag !! - ElementNamespaceContext result = null; - for (int i=0;i findElementBindingHandlers(Object parent,Object child); - - /** - * Returns list of ElementInterfaces for an element. - * @param object The element object or class to search for. - * @return The list of elementInterfaces. - */ - List findElementInterfaces(Object object); - - /** - * Returns the namespace context for an namespace uri. - * @param namespaceUri the namespace uri. - * @return The ElementNamespaceContext. - */ - ElementNamespaceContext findElementNamespaceContext(String namespaceUri); + X4OLanguage getLanguage(); /** * Gets the EL Context. @@ -123,20 +103,24 @@ public interface ElementLanguage { * @param element The root element to set. */ void setRootElement(Element element); - - /** - * @return the languageConfiguration. - */ - X4OLanguageConfiguration getLanguageConfiguration(); + /** - * Adds an ElementLanguageModule to this language. - * @param elementLanguageModule The element language module to add. + * @return Returns null or an X4ODebugWriter to write parsing steps and debug data to. */ - void addElementLanguageModule(ElementLanguageModule elementLanguageModule); + X4ODebugWriter getX4ODebugWriter(); - /** - * @return Returns a list of element language modules in this defined and loaded language. + /** + * @return Returns true if this config has a debug writer. */ - List getElementLanguageModules(); + boolean hasX4ODebugWriter(); + + Object getLanguageProperty(String key); + void setLanguageProperty(String key,Object value); + + Object getLanguageProperty(X4OLanguageProperty property); + void setLanguageProperty(X4OLanguageProperty property,Object value); + boolean getLanguagePropertyBoolean(X4OLanguageProperty property); + int getLanguagePropertyInteger(X4OLanguageProperty property); + String getLanguagePropertyString(X4OLanguageProperty property); } diff --git a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageLocal.java b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageLocal.java index 9f3ca5f..b9d6c4c 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageLocal.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageLocal.java @@ -26,8 +26,7 @@ package org.x4o.xml.element; import javax.el.ELContext; import javax.el.ExpressionFactory; -import org.x4o.xml.core.config.X4OLanguageConfiguration; - +import org.x4o.xml.core.X4ODebugWriter; /** * ElementLanguageLocal is the local set interface for ElementLanguage. @@ -54,14 +53,13 @@ public interface ElementLanguageLocal extends ElementLanguage { */ void setElementAttributeValueParser(ElementAttributeValueParser elementAttributeValueParser); - /** * @param elementObjectPropertyValue The elementObjectPropertyValue to set. */ void setElementObjectPropertyValue(ElementObjectPropertyValue elementObjectPropertyValue); - + /** - * @param parserConfiguration The parserConfiguration to set. + * @param debugWriter The debug writer to set */ - void setLanguageConfiguration(X4OLanguageConfiguration parserConfiguration); + void setX4ODebugWriter(X4ODebugWriter debugWriter); } diff --git a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoader.java b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoader.java index a7c4ac3..eacd1d8 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoader.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoader.java @@ -23,6 +23,8 @@ package org.x4o.xml.element; +import org.x4o.xml.core.config.X4OLanguageLocal; + /** * Provides elements from tag.
@@ -36,9 +38,9 @@ public interface ElementLanguageModuleLoader { /** * Starts the ElementProvider. - * @param elementLanguage The ElementLanguage to load for. + * @param languageLocal The ElementLanguage to load for. * @param elementLanguageModule The ElementLanguageModule to load it into. * @throws ElementLanguageModuleLoaderException Gets thrown when modules could not be correctly loaded. */ - void loadLanguageModule(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException; + void loadLanguageModule(X4OLanguageLocal languageLocal,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoaderSibling.java b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoaderSibling.java index 9dfc3e4..4a23a32 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoaderSibling.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/ElementLanguageModuleLoaderSibling.java @@ -25,6 +25,7 @@ package org.x4o.xml.element; import org.x4o.xml.core.config.X4OLanguageLoader; import org.x4o.xml.core.config.X4OLanguageLoaderException; +import org.x4o.xml.core.config.X4OLanguageLocal; /** @@ -38,9 +39,9 @@ public interface ElementLanguageModuleLoaderSibling extends ElementLanguageModul /** * Loads in the sibling language. - * @param elementLanguage The ElementLanguage for which we load an sibling. + * @param languageLocal The ElementLanguage for which we load an sibling. * @param loader The loader to use to load the x4o languages. * @throws X4OLanguageLoaderException Gets thrown when there is an error loading the sibling language. */ - void loadLanguageSibling(ElementLanguage elementLanguage,X4OLanguageLoader loader) throws X4OLanguageLoaderException; + void loadLanguageSibling(X4OLanguageLocal languageLocal,X4OLanguageLoader loader) throws X4OLanguageLoaderException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/element/ElementNamespaceInstanceProvider.java b/x4o-core/src/main/java/org/x4o/xml/element/ElementNamespaceInstanceProvider.java index 597d1fc..a88545a 100644 --- a/x4o-core/src/main/java/org/x4o/xml/element/ElementNamespaceInstanceProvider.java +++ b/x4o-core/src/main/java/org/x4o/xml/element/ElementNamespaceInstanceProvider.java @@ -23,6 +23,8 @@ package org.x4o.xml.element; +import org.x4o.xml.core.config.X4OLanguage; + /** * ElementNamespaceInstanceProvider is provider for creating new Element instances for an xml tag.
* @@ -37,7 +39,7 @@ public interface ElementNamespaceInstanceProvider { * @param elementNamespaceContext The ElementNamespaceContext to start for. * @throws ElementNamespaceInstanceProviderException Thrown when error happened in language. */ - void start(ElementLanguage elementLanguage,ElementNamespaceContext elementNamespaceContext) throws ElementNamespaceInstanceProviderException; + void start(X4OLanguage elementLanguage,ElementNamespaceContext elementNamespaceContext) throws ElementNamespaceInstanceProviderException; /** * Provide an Element for an xml tag. @@ -45,5 +47,5 @@ public interface ElementNamespaceInstanceProvider { * @return An new Element instance. * @throws ElementNamespaceInstanceProviderException Thrown when error happened in language. */ - Element createElementInstance(String tag) throws ElementNamespaceInstanceProviderException; + Element createElementInstance(ElementLanguage elementLanguage,String tag) throws ElementNamespaceInstanceProviderException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementAttributeValueParser.java b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementAttributeValueParser.java index 0d39377..1b788bd 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementAttributeValueParser.java +++ b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementAttributeValueParser.java @@ -88,7 +88,7 @@ public class DefaultElementAttributeValueParser implements ElementAttributeValue if (element.getElementObject()==null) { return value; } - for (ElementInterface ei:element.getElementLanguage().findElementInterfaces(element.getElementObject())) { + for (ElementInterface ei:element.getElementLanguage().getLanguage().findElementInterfaces(element.getElementObject())) { logger.finer("Found interface match executing converter."); for (ElementClassAttribute attrClass:ei.getElementClassAttributes()) { if (name.equals(attrClass.getName())==false) { @@ -135,7 +135,7 @@ public class DefaultElementAttributeValueParser implements ElementAttributeValue return false; } - for (ElementInterface ei:element.getElementLanguage().findElementInterfaces(element.getElementObject())) { + for (ElementInterface ei:element.getElementLanguage().getLanguage().findElementInterfaces(element.getElementObject())) { logger.finest("Found interface match checking disables el parameters."); attr = ei.getElementClassAttributeByName(name); diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguage.java b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguage.java index 6ff5008..660d8b9 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguage.java +++ b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguage.java @@ -23,6 +23,7 @@ package org.x4o.xml.impl; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.element.AbstractElementLanguage; /** @@ -33,4 +34,7 @@ import org.x4o.xml.element.AbstractElementLanguage; */ public class DefaultElementLanguage extends AbstractElementLanguage { + public DefaultElementLanguage(X4OLanguage language, String languageVersion) { + super(language, languageVersion); + } } diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguageModuleLoaderDummy.java b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguageModuleLoaderDummy.java index 504984f..6060f36 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguageModuleLoaderDummy.java +++ b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementLanguageModuleLoaderDummy.java @@ -25,7 +25,7 @@ package org.x4o.xml.impl; import java.util.logging.Logger; -import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.core.config.X4OLanguageLocal; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementLanguageModuleLoader; @@ -51,7 +51,7 @@ public class DefaultElementLanguageModuleLoaderDummy implements ElementLanguageM * @param elementLanguageModule The elementLanguageModule to load for. * @see org.x4o.xml.element.ElementLanguageModuleLoader#loadLanguageModule(org.x4o.xml.element.ElementLanguage, org.x4o.xml.element.ElementLanguageModule) */ - public void loadLanguageModule(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) { + public void loadLanguageModule(X4OLanguageLocal elementLanguage,ElementLanguageModule elementLanguageModule) { logger.fine("Dummy loader loads nothing."); } } diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementNamespaceInstanceProvider.java b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementNamespaceInstanceProvider.java index 90f9a9a..04b5709 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementNamespaceInstanceProvider.java +++ b/x4o-core/src/main/java/org/x4o/xml/impl/DefaultElementNamespaceInstanceProvider.java @@ -25,6 +25,7 @@ package org.x4o.xml.impl; import java.util.logging.Logger; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.core.config.X4OLanguageClassLoader; import org.x4o.xml.element.Element; import org.x4o.xml.element.ElementClass; @@ -42,7 +43,6 @@ import org.x4o.xml.element.ElementNamespaceInstanceProviderException; public class DefaultElementNamespaceInstanceProvider implements ElementNamespaceInstanceProvider { private Logger logger = null; - private ElementLanguage elementLanguage = null; private ElementNamespaceContext elementNamespaceContext = null; /** @@ -53,12 +53,11 @@ public class DefaultElementNamespaceInstanceProvider implements ElementNamespace } /** - * @param elementLanguage The elementLanguage of this provider. + * @param language The elementLanguage of this provider. * @param elementNamespaceContext The elementNamespaceContext for this provider. * @see org.x4o.xml.element.ElementNamespaceInstanceProvider#start(org.x4o.xml.element.ElementLanguage, org.x4o.xml.element.ElementNamespaceContext) */ - public void start(ElementLanguage elementLanguage,ElementNamespaceContext elementNamespaceContext) { - this.elementLanguage=elementLanguage; + public void start(X4OLanguage language,ElementNamespaceContext elementNamespaceContext) { this.elementNamespaceContext=elementNamespaceContext; logger.finer("Starting DefaultElementNamespaceInstanceProvider for: "+elementNamespaceContext.getUri()); } @@ -69,7 +68,7 @@ public class DefaultElementNamespaceInstanceProvider implements ElementNamespace * @throws ElementNamespaceInstanceProviderException * @see org.x4o.xml.element.ElementNamespaceInstanceProvider#createElementInstance(java.lang.String) */ - public Element createElementInstance(String tag) throws ElementNamespaceInstanceProviderException { + public Element createElementInstance(ElementLanguage elementLanguage,String tag) throws ElementNamespaceInstanceProviderException { ElementClass elementClass = elementNamespaceContext.getElementClass(tag); Element element = null; @@ -85,7 +84,7 @@ public class DefaultElementNamespaceInstanceProvider implements ElementNamespace } element = (Element) obj; } else { - element = (Element)X4OLanguageClassLoader.newInstance((elementLanguage.getLanguageConfiguration().getDefaultElement())); + element = (Element)X4OLanguageClassLoader.newInstance((elementLanguage.getLanguage().getLanguageConfiguration().getDefaultElement())); } if (elementClass.getObjectClass()!=null) { diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport2.java b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OConnection.java similarity index 51% rename from x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport2.java rename to x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OConnection.java index 05ee68b..35df2c5 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport2.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OConnection.java @@ -21,28 +21,49 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.test.swixml; +package org.x4o.xml.io; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; +import org.x4o.xml.core.config.X4OLanguageProperty; import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; -/** - * SwiXmlWriteSchema2 lets user write schema without parser. - * - * @author Willem Cazander - * @version 1.0 Aug 22, 2012 - */ -public class SwiXmlParserSupport2 implements X4OParserSupport { +public abstract class AbstractX4OConnection implements X4OConnection { + + private ElementLanguage languageContext = null; + + public AbstractX4OConnection(ElementLanguage languageContext) { + this.languageContext=languageContext; + } + + protected ElementLanguage getLanguageContext() { + return languageContext; + } /** - * Loads the ElementLanguage of this language parser for support. - * @return The loaded ElementLanguage. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() + * Sets an X4O Language property. + * @param key The key of the property to set. + * @param value The vlue of the property to set. */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - SwiXmlParser parser = new SwiXmlParser(SwiXmlVersion.VERSION_2); - return parser.loadElementLanguageSupport(); + public void setProperty(String key,Object value) { + String keyLimits[] = getPropertyKeySet(); + for (int i=0;i extends AbstractX4OReaderContext implements X4OReader { + public AbstractX4OReader(ElementLanguage elementLanguage) { + super(elementLanguage); + } + /** - * Method to parse the xml data. - * @param input The inputStream to parse. - * @throws ParserConfigurationException - * @throws SAXException - * @throws IOException + * @see org.x4o.xml.io.X4OConnection#getPropertyKeySet() */ - abstract public void parse(InputStream input,String systemId,URL basePath) throws ParserConfigurationException,SAXException,IOException; - - /** - * Reads the file fileName and parses it as an InputStream. - * @param fileName The file name to parse. - * @throws ParserConfigurationException - * @throws FileNotFoundException - * @throws SecurityException - * @throws NullPointerException - * @throws SAXException - * @throws IOException - * @see org.x4o.xml.sax.AbstractXMLParser#parse(java.io.InputStream,java.lang.String,java.net.URL) - */ - public void parseFile(String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { - if (fileName==null) { - throw new NullPointerException("Can't convert null fileName to file object."); - } - parseFile(new File(fileName)); + public String[] getPropertyKeySet() { + return X4OLanguagePropertyKeys.DEFAULT_X4O_READER_KEYS; + } + + @SuppressWarnings("unchecked") + public T read(InputStream input, String systemId, URL basePath) throws ParserConfigurationException, SAXException, IOException { + ElementLanguage context = readContext(input, systemId, basePath); + return (T)context.getRootElement().getElementObject(); } /** - * Reads the file and parses it as an InputStream. - * @param file The file to parse. - * @throws ParserConfigurationException + * Reads the file fileName and reads it as an InputStream. + * @param fileName The file name to read. + * @throws readrConfigurationException * @throws FileNotFoundException * @throws SecurityException * @throws NullPointerException * @throws SAXException * @throws IOException - * @see org.x4o.xml.sax.AbstractXMLParser#parse(java.io.InputStream,java.lang.String,java.net.URL) + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) */ - public void parseFile(File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + public T readFile(String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (fileName==null) { + throw new NullPointerException("Can't convert null fileName to file object."); + } + return readFile(new File(fileName)); + } + + /** + * Reads the file and reads it as an InputStream. + * @param file The file to read. + * @throws readrConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) + */ + public T readFile(File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { if (file==null) { - throw new NullPointerException("Can't load null file."); + throw new NullPointerException("Can't read null file."); } if (file.exists()==false) { throw new FileNotFoundException("File does not exists; "+file); @@ -95,7 +105,7 @@ abstract public class AbstractXMLParser { URL basePath = new File(file.getAbsolutePath()).toURI().toURL(); InputStream inputStream = new FileInputStream(file); try { - parse(inputStream,file.getAbsolutePath(),basePath); + return read(inputStream,file.getAbsolutePath(),basePath); } finally { if(inputStream!=null) { inputStream.close(); @@ -104,18 +114,18 @@ abstract public class AbstractXMLParser { } /** - * Parses an resource locaction. - * @param resourceName The resource to parser. - * @throws ParserConfigurationException + * reads an resource locaction. + * @param resourceName The resource to readr. + * @throws readrConfigurationException * @throws FileNotFoundException * @throws SecurityException * @throws NullPointerException * @throws SAXException * @throws IOException */ - public void parseResource(String resourceName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + public T readResource(String resourceName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { if (resourceName==null) { - throw new NullPointerException("Can't load null resourceName from classpath."); + throw new NullPointerException("Can't read null resourceName from classpath."); } ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) cl = getClass().getClassLoader(); // fallback @@ -131,7 +141,7 @@ abstract public class AbstractXMLParser { URL basePath = new URL(baseUrl); InputStream inputStream = cl.getResourceAsStream(resourceName); try { - parse(inputStream,url.toExternalForm(),basePath); + return read(inputStream,url.toExternalForm(),basePath); } finally { if(inputStream!=null) { inputStream.close(); @@ -140,36 +150,36 @@ abstract public class AbstractXMLParser { } /** - * Converts a String to a InputStream to is can me parsed by SAX. - * @param xmlString The xml as String to parse. - * @throws ParserConfigurationException + * Converts a String to a InputStream to is can me readd by SAX. + * @param xmlString The xml as String to read. + * @throws readrConfigurationException * @throws SAXException * @throws IOException * @throws NullPointerException - * @see org.x4o.xml.sax.AbstractXMLParser#parse(java.io.InputStream,java.lang.String,java.net.URL) + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) */ - public void parseXml(String xmlString) throws ParserConfigurationException,SAXException,IOException,NullPointerException { + public T readString(String xmlString) throws ParserConfigurationException,SAXException,IOException,NullPointerException { if (xmlString==null) { - throw new NullPointerException("Can't parse null xml string."); + throw new NullPointerException("Can't read null xml string."); } URL basePath = new File(System.getProperty("user.dir")).toURI().toURL(); - parse(new ByteArrayInputStream(xmlString.getBytes()),"inline-xml",basePath); + return read(new ByteArrayInputStream(xmlString.getBytes()),"inline-xml",basePath); } /** - * Fetched the data direct from remote url to a InputStream to is can me parsed by SAX. - * @param url The url to parse. - * @throws ParserConfigurationException + * Fetched the data direct from remote url to a InputStream to is can me readd by SAX. + * @param url The url to read. + * @throws readrConfigurationException * @throws SAXException * @throws IOException * @throws NullPointerException - * @see org.x4o.xml.sax.AbstractXMLParser#parse(java.io.InputStream,java.lang.String,java.net.URL) + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) */ - public void parseUrl(URL url) throws ParserConfigurationException,SAXException,IOException,NullPointerException { + public T readUrl(URL url) throws ParserConfigurationException,SAXException,IOException,NullPointerException { if (url==null) { - throw new NullPointerException("Can't parse null url."); + throw new NullPointerException("Can't read null url."); } URL basePath = new URL(url.toExternalForm().substring(0,url.toExternalForm().length()-url.getFile().length())); - parse(url.openStream(),url.toExternalForm(),basePath); + return read(url.openStream(),url.toExternalForm(),basePath); } } diff --git a/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OReaderContext.java b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OReaderContext.java new file mode 100644 index 0000000..d480c36 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OReaderContext.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.x4o.xml.element.ElementLanguage; +import org.xml.sax.SAXException; +import javax.xml.parsers.ParserConfigurationException; + +/** + * AbstractX4OContextReader + + * + * @author Willem Cazander + * @version 1.0 Apr 6, 2013 + */ +abstract public class AbstractX4OReaderContext extends AbstractX4OConnection implements X4OReaderContext { + + public AbstractX4OReaderContext(ElementLanguage languageContext) { + super(languageContext); + } + + /** + * Reads the file fileName and reads it as an InputStream. + * @param fileName The file name to read. + * @throws readrConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) + */ + public ElementLanguage readFileContext(String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (fileName==null) { + throw new NullPointerException("Can't convert null fileName to file object."); + } + return readFileContext(new File(fileName)); + } + + /** + * Reads the file and reads it as an InputStream. + * @param file The file to read. + * @throws readrConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) + */ + public ElementLanguage readFileContext(File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (file==null) { + throw new NullPointerException("Can't read null file."); + } + if (file.exists()==false) { + throw new FileNotFoundException("File does not exists; "+file); + } + if (file.canRead()==false) { + throw new IOException("File exists but can't read file: "+file); + } + URL basePath = new File(file.getAbsolutePath()).toURI().toURL(); + InputStream inputStream = new FileInputStream(file); + try { + return readContext(inputStream,file.getAbsolutePath(),basePath); + } finally { + if(inputStream!=null) { + inputStream.close(); + } + } + } + + /** + * reads an resource locaction. + * @param resourceName The resource to readr. + * @throws readrConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + */ + public ElementLanguage readResourceContext(String resourceName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (resourceName==null) { + throw new NullPointerException("Can't read null resourceName from classpath."); + } + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + if (cl == null) cl = getClass().getClassLoader(); // fallback + URL url = cl.getResource(resourceName); + if (url==null) { + throw new NullPointerException("Could not find resource on classpath: "+resourceName); + } + String baseUrl = url.toExternalForm(); + int lastSlash = baseUrl.lastIndexOf('/'); + if (lastSlash > 0 && (lastSlash+1) < baseUrl.length()) { + baseUrl = baseUrl.substring(0,lastSlash+1); + } + URL basePath = new URL(baseUrl); + InputStream inputStream = cl.getResourceAsStream(resourceName); + try { + return readContext(inputStream,url.toExternalForm(),basePath); + } finally { + if(inputStream!=null) { + inputStream.close(); + } + } + } + + /** + * Converts a String to a InputStream to is can me readd by SAX. + * @param xmlString The xml as String to read. + * @throws readrConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) + */ + public ElementLanguage readStringContext(String xmlString) throws ParserConfigurationException,SAXException,IOException,NullPointerException { + if (xmlString==null) { + throw new NullPointerException("Can't read null xml string."); + } + URL basePath = new File(System.getProperty("user.dir")).toURI().toURL(); + return readContext(new ByteArrayInputStream(xmlString.getBytes()),"inline-xml",basePath); + } + + /** + * Fetched the data direct from remote url to a InputStream to is can me readd by SAX. + * @param url The url to read. + * @throws readrConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.sax.AbstractXMLreadr#read(java.io.InputStream,java.lang.String,java.net.URL) + */ + public ElementLanguage readUrlContext(URL url) throws ParserConfigurationException,SAXException,IOException,NullPointerException { + if (url==null) { + throw new NullPointerException("Can't read null url."); + } + URL basePath = new URL(url.toExternalForm().substring(0,url.toExternalForm().length()-url.getFile().length())); + return readContext(url.openStream(),url.toExternalForm(),basePath); + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriter.java b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriter.java new file mode 100644 index 0000000..7156fe1 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriter.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import javax.xml.parsers.ParserConfigurationException; + +import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.element.ElementLanguage; +import org.xml.sax.SAXException; + +public abstract class AbstractX4OWriter extends AbstractX4OWriterContext implements X4OWriter { + + public AbstractX4OWriter(ElementLanguage elementLanguage) { + super(elementLanguage); + } + + /** + * @see org.x4o.xml.io.X4OConnection#getPropertyKeySet() + */ + public String[] getPropertyKeySet() { + return X4OLanguagePropertyKeys.DEFAULT_X4O_WRITER_KEYS; + } + + public void write(T object,OutputStream output) throws ParserConfigurationException, SAXException, IOException { + ElementLanguage context = getLanguageContext(); + context.getRootElement().setElementObject(object); //TODO: check ?? + writeContext(context,output); + } + + public void writeFile(T object,String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (fileName==null) { + throw new NullPointerException("Can't convert null fileName to file object."); + } + writeFile(object,new File(fileName)); + } + + public void writeFile(T object,File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (file==null) { + throw new NullPointerException("Can't read null file."); + } + if (file.exists()) { + throw new FileNotFoundException("File does already exists; "+file); + } + if (file.canWrite()==false) { + throw new IOException("Can't write file: "+file); + } + OutputStream outputStream = new FileOutputStream(file); + try { + write(object,outputStream); + } finally { + if(outputStream!=null) { + outputStream.close(); + } + } + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriterContext.java b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriterContext.java new file mode 100644 index 0000000..d824e09 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/AbstractX4OWriterContext.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import javax.xml.parsers.ParserConfigurationException; + +import org.x4o.xml.element.ElementLanguage; +import org.xml.sax.SAXException; + +public abstract class AbstractX4OWriterContext extends AbstractX4OConnection implements X4OWriterContext { + + public AbstractX4OWriterContext(ElementLanguage elementLanguage) { + super(elementLanguage); + } + + public void writeFileContext(ElementLanguage context,String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (fileName==null) { + throw new NullPointerException("Can't convert null fileName to file object."); + } + writeFileContext(context,new File(fileName)); + } + + public void writeFileContext(ElementLanguage context,File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException { + if (file==null) { + throw new NullPointerException("Can't read null file."); + } + if (file.exists()) { + throw new FileNotFoundException("File does already exists; "+file); + } + if (file.canWrite()==false) { + throw new IOException("Can't write file: "+file); + } + OutputStream outputStream = new FileOutputStream(file); + try { + writeContext(context,outputStream); + } finally { + if(outputStream!=null) { + outputStream.close(); + } + } + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupportException.java b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4ODriver.java similarity index 57% rename from x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupportException.java rename to x4o-core/src/main/java/org/x4o/xml/io/DefaultX4ODriver.java index b35f5f7..aa066c7 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupportException.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4ODriver.java @@ -21,48 +21,41 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.core; +package org.x4o.xml.io; -/** - * X4OParserSupportException is exception when executing an language supporting feature. - * - * @author Willem Cazander - * @version 1.0 Aug 22, 2012 - */ -public class X4OParserSupportException extends Exception { +import org.x4o.xml.X4ODriver; +import org.x4o.xml.core.config.DefaultX4OLanguage; +import org.x4o.xml.core.config.DefaultX4OLanguageConfiguration; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.phase.X4OPhaseManagerFactory; + +public class DefaultX4ODriver extends X4ODriver { + + private final String languageName; + private final String languageVersion; - /** The serial version uid */ - static final long serialVersionUID = 10L; - - /** - * Constructs an X4OWriteSchemaException without a detail message. - */ - public X4OParserSupportException() { + public DefaultX4ODriver(String languageName) { + this(languageName,X4ODriver.DEFAULT_LANGUAGE_VERSION); + } + + public DefaultX4ODriver(String languageName,String languageVersion) { super(); + this.languageName=languageName; + this.languageVersion=languageVersion; + } + + @Override + public String getLanguageName() { + return languageName; } - /** - * Constructs an X4OWriteSchemaException with a detail message. - * @param message The message of this Exception - */ - public X4OParserSupportException(String message) { - super(message); + @Override + public X4OLanguage buildLanguage(String version) { + return new DefaultX4OLanguage(new DefaultX4OLanguageConfiguration(),X4OPhaseManagerFactory.createDefaultX4OPhaseManager(),getLanguageName(),languageVersion); } - - /** - * Creates an X4OWriteSchemaException from a parent exception. - * @param e The error exception. - */ - public X4OParserSupportException(Exception e) { - super(e); - } - - /** - * Constructs an X4OWriteSchemaException with a detail message. - * @param message The message of this Exception - * @param e The error exception. - */ - public X4OParserSupportException(String message,Exception e) { - super(message,e); + + @Override + public String[] getLanguageVersions() { + return new String[]{languageVersion}; } } diff --git a/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OReader.java b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OReader.java new file mode 100644 index 0000000..b88a31b --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OReader.java @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import javax.xml.parsers.ParserConfigurationException; + +import org.x4o.xml.core.X4ODebugWriter; +import org.x4o.xml.core.config.X4OLanguageProperty; +import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.core.phase.X4OPhaseException; +import org.x4o.xml.core.phase.X4OPhaseType; +import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.element.ElementLanguageLocal; +import org.x4o.xml.io.sax.XMLWriter; +import org.xml.sax.SAXException; +import org.xml.sax.ext.DefaultHandler2; +import org.xml.sax.helpers.AttributesImpl; + +/** + * DefaultX4OReader can read and parse the xml language. + * + * @author Willem Cazander + * @version 1.0 Aug 9, 2012 + */ +public class DefaultX4OReader extends AbstractX4OReader { + + + /** The logger to log to. */ + private Logger logger = null; + + public DefaultX4OReader(ElementLanguage elementLanguage) { + super(elementLanguage); + logger = Logger.getLogger(DefaultX4OReader.class.getName()); + } + + public ElementLanguage readContext(InputStream input, String systemId, URL basePath) throws ParserConfigurationException, SAXException, IOException { + setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_STREAM, input); + setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_SYSTEM_ID, systemId); + setProperty(X4OLanguagePropertyKeys.INPUT_SOURCE_BASE_PATH, basePath); + read(); + return getLanguageContext(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public void addELBeanInstance(String name,Object bean) { + if (name==null) { + throw new NullPointerException("Can't add null name."); + } + if (name.length()==0) { + throw new NullPointerException("Can't add empty name."); + } + if (bean==null) { + throw new NullPointerException("Can't add null bean."); + } + Map map = (Map)getProperty(X4OLanguagePropertyKeys.EL_BEAN_INSTANCE_MAP); + if (map==null) { + map = new HashMap(20); + setProperty(X4OLanguagePropertyKeys.EL_BEAN_INSTANCE_MAP, map); + } + logger.finer("Adding el bean: "+name+" type: "+bean.getClass()); + map.put(name,bean); + } + + /** + * Parses the input stream as a X4O document. + */ + protected void read() throws ParserConfigurationException,SAXException,IOException { + ElementLanguage elementLanguage = getLanguageContext(); + if (elementLanguage.getLanguage()==null) { + throw new ParserConfigurationException("parserConfig is broken getLanguage() returns null."); + } + + // init debugWriter if enabled + boolean startedDebugWriter = false; + Object debugOutputHandler = elementLanguage.getLanguageProperty(X4OLanguageProperty.DEBUG_OUTPUT_HANDLER); + Object debugOutputStream = elementLanguage.getLanguageProperty(X4OLanguageProperty.DEBUG_OUTPUT_STREAM); + if (elementLanguage.getX4ODebugWriter()==null) { + DefaultHandler2 xmlDebugWriter = null; + if (debugOutputHandler instanceof DefaultHandler2) { + xmlDebugWriter = (DefaultHandler2)debugOutputHandler; + } else if (debugOutputStream instanceof OutputStream) { + xmlDebugWriter = new XMLWriter((OutputStream)debugOutputStream); + } + if (xmlDebugWriter!=null) { + xmlDebugWriter.startDocument(); + xmlDebugWriter.startPrefixMapping("debug", X4ODebugWriter.DEBUG_URI); + X4ODebugWriter debugWriter = new X4ODebugWriter(xmlDebugWriter); + ElementLanguageLocal local = (ElementLanguageLocal)elementLanguage; + local.setX4ODebugWriter(debugWriter); + startedDebugWriter = true; + } + } + + // debug language + if (elementLanguage.hasX4ODebugWriter()) { + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute ("", "language", "", "", elementLanguage.getLanguage().getLanguageName()); + atts.addAttribute ("", "currentTimeMillis", "", "", System.currentTimeMillis()+""); + elementLanguage.getX4ODebugWriter().getDebugWriter().startElement(X4ODebugWriter.DEBUG_URI, "X4ODriver", "", atts); + } + + // start parsing language + try { + getLanguageContext().getLanguage().getPhaseManager().runPhases(getLanguageContext(), X4OPhaseType.XML_READ); + } catch (Exception e) { + + // also debug exceptions + if (elementLanguage.hasX4ODebugWriter()) { + try { + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute ("", "message", "", "", e.getMessage()); + if (e instanceof X4OPhaseException) { + atts.addAttribute ("", "phase", "", "", ((X4OPhaseException)e).getX4OPhaseHandler().getId()); + } + elementLanguage.getX4ODebugWriter().getDebugWriter().startElement(X4ODebugWriter.DEBUG_URI, "exceptionStackTrace", "", atts); + StringWriter writer = new StringWriter(); + PrintWriter printer = new PrintWriter(writer); + printer.append('\n'); + if (e.getCause()==null) { + e.printStackTrace(printer); + } else { + e.getCause().printStackTrace(printer); + } + char[] stack = writer.getBuffer().toString().toCharArray(); + elementLanguage.getX4ODebugWriter().getDebugWriter().characters(stack, 0, stack.length); + elementLanguage.getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "exceptionStackTrace", ""); + } catch (Exception ee) { + ee.printStackTrace(); + } + } + + // unwrap exception + if (e.getCause() instanceof ParserConfigurationException) { + throw (ParserConfigurationException)e.getCause(); + } + if (e.getCause() instanceof SAXException) { + throw (SAXException)e.getCause(); + } + if (e.getCause() instanceof IOException) { + throw (IOException)e.getCause(); + } + if (e.getCause()==null) { + throw new SAXException(e); + } else { + throw new SAXException((Exception)e.getCause()); + } + } finally { + // close all our resources. + //if (inputStream!=null) { + // inputStream.close(); + //} + if (elementLanguage.hasX4ODebugWriter()) { + elementLanguage.getX4ODebugWriter().getDebugWriter().endElement(X4ODebugWriter.DEBUG_URI, "X4ODriver", ""); + } + if (startedDebugWriter && elementLanguage.hasX4ODebugWriter()) { + elementLanguage.getX4ODebugWriter().getDebugWriter().endPrefixMapping("debug"); + elementLanguage.getX4ODebugWriter().getDebugWriter().endDocument(); + if (debugOutputStream instanceof OutputStream) { + OutputStream outputStream = (OutputStream)debugOutputStream; + outputStream.flush(); + outputStream.close(); // need this here ? + } + } + } + } + + public void releaseContext(ElementLanguage context) throws X4OPhaseException { + if (context==null) { + return; + } + if (context.getLanguage()==null) { + return; + } + if (context.getLanguage().getPhaseManager()==null) { + return; + } + context.getLanguage().getPhaseManager().doReleasePhaseManual(context); + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupportCore.java b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OSchemaWriter.java similarity index 57% rename from x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupportCore.java rename to x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OSchemaWriter.java index 854af7d..e0772a9 100644 --- a/x4o-core/src/main/java/org/x4o/xml/eld/EldParserSupportCore.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OSchemaWriter.java @@ -21,28 +21,41 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.eld; +package org.x4o.xml.io; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; +import java.io.File; + +import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.eld.xsd.EldXsdXmlGenerator; +import org.x4o.xml.element.ElementException; import org.x4o.xml.element.ElementLanguage; -/** - * EldParserSupportCore can write the cel schema. - * - * @author Willem Cazander - * @version 1.0 Aug 22, 2012 - */ -public class EldParserSupportCore implements X4OParserSupport { +public class DefaultX4OSchemaWriter extends AbstractX4OConnection implements X4OSchemaWriter { + + public DefaultX4OSchemaWriter(ElementLanguage languageContext) { + super(languageContext); + } /** - * Loads the ElementLanguage of this language parser for support. - * @return The loaded ElementLanguage. - * @throws X4OParserSupportException When support language could not be loaded. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() + * @see org.x4o.xml.io.X4OConnection#getPropertyKeySet() */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - EldParser parser = new EldParser(true); - return parser.loadElementLanguageSupport(); + public String[] getPropertyKeySet() { + return X4OLanguagePropertyKeys.DEFAULT_X4O_SCHEMA_WRITER_KEYS; + } + + /** + * @see org.x4o.xml.io.X4OSchemaWriter#writeSchema(java.io.File) + */ + public void writeSchema(File basePath) throws ElementException { + writeSchema(basePath, null); + } + + /** + * @see org.x4o.xml.io.X4OSchemaWriter#writeSchema(java.io.File, java.lang.String) + */ + public void writeSchema(File basePath, String namespace) throws ElementException { + // Start xsd generator + EldXsdXmlGenerator xsd = new EldXsdXmlGenerator(getLanguageContext().getLanguage()); + xsd.writeSchema(basePath, namespace); } } diff --git a/x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestParser.java b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OWriter.java similarity index 69% rename from x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestParser.java rename to x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OWriter.java index 406411f..7a6633d 100644 --- a/x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestParser.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/DefaultX4OWriter.java @@ -21,23 +21,28 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.meta.test; +package org.x4o.xml.io; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; + +import javax.xml.parsers.ParserConfigurationException; -import org.x4o.xml.core.X4ODriver; -import org.x4o.xml.core.X4OParser; import org.x4o.xml.element.ElementLanguage; +import org.xml.sax.SAXException; -public class MTestParser extends X4OParser { +public class DefaultX4OWriter extends AbstractX4OWriter { - public MTestParser() { - super("mtest"); + public DefaultX4OWriter(ElementLanguage elementLanguage) { + super(elementLanguage); } - - public ElementLanguage getElementLanguage() { - return getDriver().getElementLanguage(); - } - - public X4ODriver getDriver() { - return super.getDriver(); + + public void writeContext(ElementLanguage context,OutputStream out) throws ParserConfigurationException, + FileNotFoundException, SecurityException, NullPointerException, + SAXException, IOException { + +// getLanguageContext().setRootElement(element) } + } diff --git a/x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupport.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OConnection.java similarity index 71% rename from x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupport.java rename to x4o-core/src/main/java/org/x4o/xml/io/X4OConnection.java index b628152..5b7e1ba 100644 --- a/x4o-core/src/main/java/org/x4o/xml/core/X4OParserSupport.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OConnection.java @@ -21,23 +21,26 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.core; +package org.x4o.xml.io; -import org.x4o.xml.element.ElementLanguage; - -/** - * X4OParserSupport is interface for language features without integration with parsing code. - * - * @author Willem Cazander - * @version 1.0 Aug 22, 2012 - */ -public interface X4OParserSupport { +public interface X4OConnection { /** - * Loads the language ElementLanguage to provide support. - * - * @return Returns the ElementLanguage. - * @throws X4OParserSupportException Is thrown when supporting language could not be loaded. + * Sets an X4O Language property. + * @param key The key of the property to set. + * @param value The vlue of the property to set. */ - ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException; + void setProperty(String key,Object value); + + /** + * Returns the value an X4O Language property. + * @param key The key of the property to get the value for. + * @return Returns null or the value of the property. + */ + Object getProperty(String key); + + /** + * @return Returns the propery keys which can be set. + */ + String[] getPropertyKeySet(); } diff --git a/x4o-core/src/main/java/org/x4o/xml/io/X4OReader.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OReader.java new file mode 100644 index 0000000..4f19e03 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OReader.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import javax.xml.parsers.ParserConfigurationException; + +import org.xml.sax.SAXException; + +public interface X4OReader extends X4OConnection { + + public void addELBeanInstance(String name,Object bean); + + /** + * Method to parse the xml data. + * @param input The inputStream to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + */ + T read(InputStream input,String systemId,URL basePath) throws ParserConfigurationException,SAXException,IOException; + + /** + * Reads the file fileName and parses it as an InputStream. + * @param fileName The file name to parse. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + T readFile(String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Reads the file and parses it as an InputStream. + * @param file The file to parse. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + T readFile(File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Parses an resource locaction. + * @param resourceName The resource to parser. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + */ + T readResource(String resourceName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Converts a String to a InputStream to is can me parsed by SAX. + * @param xmlString The xml as String to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + T readString(String xmlString) throws ParserConfigurationException,SAXException,IOException,NullPointerException; + + /** + * Fetched the data direct from remote url to a InputStream to is can me parsed by SAX. + * @param url The url to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + T readUrl(URL url) throws ParserConfigurationException,SAXException,IOException,NullPointerException; +} diff --git a/x4o-core/src/main/java/org/x4o/xml/io/X4OReaderContext.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OReaderContext.java new file mode 100644 index 0000000..fad5b3c --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OReaderContext.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import javax.xml.parsers.ParserConfigurationException; + +import org.x4o.xml.core.phase.X4OPhaseException; +import org.x4o.xml.element.ElementLanguage; +import org.xml.sax.SAXException; + +public interface X4OReaderContext extends X4OReader { + + void releaseContext(ElementLanguage context) throws X4OPhaseException; + + /** + * Method to parse the xml data. + * @param input The inputStream to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + */ + ElementLanguage readContext(InputStream input,String systemId,URL basePath) throws ParserConfigurationException,SAXException,IOException; + + /** + * Reads the file fileName and parses it as an InputStream. + * @param fileName The file name to parse. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + ElementLanguage readFileContext(String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Reads the file and parses it as an InputStream. + * @param file The file to parse. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + ElementLanguage readFileContext(File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Parses an resource locaction. + * @param resourceName The resource to parser. + * @throws ParserConfigurationException + * @throws FileNotFoundException + * @throws SecurityException + * @throws NullPointerException + * @throws SAXException + * @throws IOException + */ + ElementLanguage readResourceContext(String resourceName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + /** + * Converts a String to a InputStream to is can me parsed by SAX. + * @param xmlString The xml as String to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + ElementLanguage readStringContext(String xmlString) throws ParserConfigurationException,SAXException,IOException,NullPointerException; + + /** + * Fetched the data direct from remote url to a InputStream to is can me parsed by SAX. + * @param url The url to parse. + * @throws ParserConfigurationException + * @throws SAXException + * @throws IOException + * @throws NullPointerException + * @see org.x4o.xml.io.AbstractX4OReader#parse(java.io.InputStream,java.lang.String,java.net.URL) + */ + ElementLanguage readUrlContext(URL url) throws ParserConfigurationException,SAXException,IOException,NullPointerException; +} diff --git a/x4o-core/src/main/java/org/x4o/xml/io/X4OSchemaWriter.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OSchemaWriter.java new file mode 100644 index 0000000..ec0dfdf --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OSchemaWriter.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +import java.io.File; + +import org.x4o.xml.element.ElementException; + +public interface X4OSchemaWriter extends X4OConnection { + + void writeSchema(File basePath) throws ElementException; + void writeSchema(File basePath,String namespace) throws ElementException; +} diff --git a/x4o-core/src/test/java/org/x4o/xml/eld/EldErrorParserSupport.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OWriter.java similarity index 63% rename from x4o-core/src/test/java/org/x4o/xml/eld/EldErrorParserSupport.java rename to x4o-core/src/main/java/org/x4o/xml/io/X4OWriter.java index c5c018c..0e578db 100644 --- a/x4o-core/src/test/java/org/x4o/xml/eld/EldErrorParserSupport.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OWriter.java @@ -21,18 +21,22 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.eld; +package org.x4o.xml.io; -import org.x4o.xml.core.X4ODriver; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.impl.config.DefaultX4OLanguageConfiguration; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; -public class EldErrorParserSupport implements X4OParserSupport { +import javax.xml.parsers.ParserConfigurationException; - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - X4ODriver driver = new X4ODriver(new DefaultX4OLanguageConfiguration("test", "version-error")); - return driver.loadElementLanguageSupport(); - } +import org.xml.sax.SAXException; + +public interface X4OWriter extends X4OConnection { + + void write(T object,OutputStream out) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + void writeFile(T object,String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + void writeFile(T object,File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport3.java b/x4o-core/src/main/java/org/x4o/xml/io/X4OWriterContext.java similarity index 62% rename from x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport3.java rename to x4o-core/src/main/java/org/x4o/xml/io/X4OWriterContext.java index b703aea..e0b9d7b 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParserSupport3.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/X4OWriterContext.java @@ -21,29 +21,23 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.test.swixml; +package org.x4o.xml.io; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; + +import javax.xml.parsers.ParserConfigurationException; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; import org.x4o.xml.element.ElementLanguage; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; +import org.xml.sax.SAXException; -/** - * SwiXmlWriteSchema3 lets user write schema without parser. - * - * @author Willem Cazander - * @version 1.0 Aug 22, 2012 - */ -public class SwiXmlParserSupport3 implements X4OParserSupport { +public interface X4OWriterContext extends X4OWriter { + void writeContext(ElementLanguage context,OutputStream out) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; - /** - * Loads the ElementLanguage of this language parser for support. - * @return The loaded ElementLanguage. - * @see org.x4o.xml.core.X4OParserSupport#loadElementLanguageSupport() - */ - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - SwiXmlParser parser = new SwiXmlParser(SwiXmlVersion.VERSION_3); - return parser.loadElementLanguageSupport(); - } + void writeFileContext(ElementLanguage context,String fileName) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; + + void writeFileContext(ElementLanguage context,File file) throws ParserConfigurationException,FileNotFoundException,SecurityException,NullPointerException,SAXException,IOException; } diff --git a/x4o-core/src/main/java/org/x4o/xml/io/XMLConstants.java b/x4o-core/src/main/java/org/x4o/xml/io/XMLConstants.java new file mode 100644 index 0000000..77384e2 --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/io/XMLConstants.java @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.io; + +/** + * XMLConstants for writing XML. + * + * @author Willem Cazander + * @version 1.0 Mrt 31, 2012 + */ +public final class XMLConstants { + + /** + * Lowcase xml. + */ + public static final String XML = "xml"; + + /** + * XML Default encoding is utf-8. + */ + public static final String XML_DEFAULT_ENCODING = "UTF-8"; + + /** + * XML Default version is 1.0. + */ + public static final String XML_DEFAULT_VERSION = "1.0"; + + /** + * XML Namespace prefix attribute. + */ + public static final String XMLNS_ATTRIBUTE = "xmlns"; + + /** + * XML Namespace prefix seperator + */ + public static final String XMLNS_ASSIGN = ":"; + + /** + * XML Schema namespace URI. + */ + public static final String XML_SCHEMA_NS_URI = "http://www.w3.org/2001/XMLSchema"; + + /** + * XML Schema instance namespace URI. + */ + public static final String XML_SCHEMA_INSTANCE_NS_URI = "http://www.w3.org/2001/XMLSchema-instance"; + + /** + * Null or empty namespace uri. + * @see Namespaces in XML, 5.2 Namespace Defaulting + */ + public static final String NULL_NS_URI = ""; + + /** + * Opens xml element tag. + */ + public static final String TAG_OPEN = "<"; + + /** + * Opens end xml element tag. + */ + public static final String TAG_OPEN_END = ""; + + /** + * Close empty xml element tag. + */ + public static final String TAG_CLOSE_EMPTY = "/>"; + + /** + * Starts a comment. + */ + public static final String COMMENT_START = ""; + + /** + * Starts a processing instruction. + */ + public static final String PROCESS_START = ""; + + /** + * Tab char + */ + public static final String CHAR_TAB = "\t"; + + /** + * Newline char + */ + public static final String CHAR_NEWLINE = "\r\n"; + + + + + static public String getDocumentDeclaration(String encoding) { + return getDocumentDeclaration(encoding,null); + } + + static public String getDocumentDeclaration(String encoding,String version) { + if (encoding==null) { + encoding=XML_DEFAULT_ENCODING; + } + if (version==null) { + version=XML_DEFAULT_VERSION; + } + return String.format("", version,encoding); + } + + static public boolean isChar(int c) { + // Exclude "compatibility characters", as defined in section 2.3 of [Unicode] + if (c>=0x7F & c<=0x84) { return false; } + if (c>=0x86 & c<=0x9F) { return false; } + if (c>=0xFDD0 & c<=0xFDEF) { return false; } + if ((c>=0x1FFFE & c<=0x1FFFF)||(c>=0x2FFFE & c<=0x2FFFF)|(c>=0x3FFFE & c<=0x3FFFF)) { return false; } + if ((c>=0x4FFFE & c<=0x4FFFF)||(c>=0x5FFFE & c<=0x5FFFF)|(c>=0x6FFFE & c<=0x6FFFF)) { return false; } + if ((c>=0x7FFFE & c<=0x7FFFF)||(c>=0x8FFFE & c<=0x8FFFF)|(c>=0x9FFFE & c<=0x9FFFF)) { return false; } + if ((c>=0xAFFFE & c<=0xAFFFF)||(c>=0xBFFFE & c<=0xBFFFF)|(c>=0xCFFFE & c<=0xCFFFF)) { return false; } + if ((c>=0xDFFFE & c<=0xDFFFF)||(c>=0xEFFFE & c<=0xEFFFF)|(c>=0xFFFFE & c<=0xFFFFF)) { return false; } + if (c>=0x10FFFE & c<=0x10FFFF) { return false; } + + // Source; + // #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] + if (c==0x9) { return true; } + if (c==0xA) { return true; } + if (c==0xD) { return true; } + if (c>=0x20 & c<=0xD7FF) { return true; } + if (c>=0xE000 & c<=0xFFFD) { return true; } + if (c>=0x10000 & c<=0x10FFFF) { return true; } + return false; + } + + static public boolean isNameStartChar(int c) { + // Source; + // ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] + if (c>='a' & c<='z') { return true; } + if (c>='A' & c<='Z') { return true; } + if (c==':' || c=='_') { return true; } + if (c>=0xC0 & c<=0xD6) { return true; } + if (c>=0xD8 & c<=0xF6) { return true; } + if (c>=0xF8 & c<=0x2FF) { return true; } + if (c>=0x370 & c<=0x37D) { return true; } + if (c>=0x37F & c<=0x1FFF) { return true; } + if (c>=0x200C & c<=0x200D) { return true; } + if (c>=0x2070 & c<=0x218F) { return true; } + if (c>=0x2C00 & c<=0x2FEF) { return true; } + if (c>=0x3001 & c<=0xD7FF) { return true; } + if (c>=0xF900 & c<=0xFDCF) { return true; } + if (c>=0xFDF0 & c<=0xFFFD) { return true; } + if (c>=0x10000 & c<=0xEFFFF) { return true; } + return false; + } + + static public boolean isNameChar(int c) { + // Source; + // NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] + if (isNameStartChar(c)) { + return true; + } + if (c=='-' || c=='.') { return true; } + if (c>='0' & c<='9') { return true; } + if (c==0xB7) { return true; } + if (c>=0x0300 & c<=0x036F) { return true; } + if (c>=0x203F & c<=0x2040) { return true; } + return false; + } + + static public String escapeAttributeValue(String value) { + int l = value.length(); + StringBuffer result = new StringBuffer(l); + for (int i=0;i') { + result.append(">"); + continue; + } + if (c=='&') { + result.append("&"); + continue; + } + if (c=='\"') { + result.append(""e;"); + continue; + } + if (c=='\'') { + result.append("'"); + continue; + } + if (isNameChar(c)==false) { + result.append("#x"); + result.append(Integer.toHexString(c)); + result.append(";"); + continue; + } else { + result.append(c); + } + } + return result.toString(); + } +} diff --git a/x4o-core/src/main/java/org/x4o/xml/impl/config/package-info.java b/x4o-core/src/main/java/org/x4o/xml/io/package-info.java similarity index 93% rename from x4o-core/src/main/java/org/x4o/xml/impl/config/package-info.java rename to x4o-core/src/main/java/org/x4o/xml/io/package-info.java index cd155af..376a9bb 100644 --- a/x4o-core/src/main/java/org/x4o/xml/impl/config/package-info.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/package-info.java @@ -22,10 +22,9 @@ */ /** - * The X4O Config implementation which loads the language. - * + * The X4O Input and Output classes. * * @since 1.0 */ -package org.x4o.xml.impl.config; +package org.x4o.xml.io; \ No newline at end of file diff --git a/x4o-core/src/main/java/org/x4o/xml/sax/AttributeMap.java b/x4o-core/src/main/java/org/x4o/xml/io/sax/AttributeMap.java similarity index 99% rename from x4o-core/src/main/java/org/x4o/xml/sax/AttributeMap.java rename to x4o-core/src/main/java/org/x4o/xml/io/sax/AttributeMap.java index 050f6de..ff5e1b4 100644 --- a/x4o-core/src/main/java/org/x4o/xml/sax/AttributeMap.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/sax/AttributeMap.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.sax; +package org.x4o.xml.io.sax; import org.xml.sax.Attributes; import java.util.ArrayList; diff --git a/x4o-core/src/main/java/org/x4o/xml/sax/XMLWriter.java b/x4o-core/src/main/java/org/x4o/xml/io/sax/XMLWriter.java similarity index 73% rename from x4o-core/src/main/java/org/x4o/xml/sax/XMLWriter.java rename to x4o-core/src/main/java/org/x4o/xml/io/sax/XMLWriter.java index f65378c..9f1909a 100644 --- a/x4o-core/src/main/java/org/x4o/xml/sax/XMLWriter.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/sax/XMLWriter.java @@ -21,7 +21,7 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.sax; +package org.x4o.xml.io.sax; import java.io.IOException; import java.io.OutputStream; @@ -34,6 +34,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.x4o.xml.io.XMLConstants; import org.xml.sax.Attributes; import org.xml.sax.Locator; import org.xml.sax.SAXException; @@ -48,10 +49,18 @@ import org.xml.sax.ext.DefaultHandler2; */ public class XMLWriter extends DefaultHandler2 { + private final static String ENCODING = "http://writer.x4o.org/xml/properties/encoding"; + private final static String CHAR_NEWLINE = "http://writer.x4o.org/xml/properties/char/newline"; + private final static String CHAR_TAB = "http://writer.x4o.org/xml/properties/char/tab"; + private final static String URI_PREFX = "http://writer.x4o.org/xml/properties/char/"; + + private String encoding = null; + private String charNewline = null; + private String charTab = null; private Writer out = null; private int indent = 0; - private Map prefixMapping = new HashMap(10); - private List printedMappings = new ArrayList(10); + private Map prefixMapping = null; + private List printedMappings = null; private StringBuffer startElement = null; private boolean printedReturn = false; @@ -59,8 +68,50 @@ public class XMLWriter extends DefaultHandler2 { * Creates XmlWriter which prints to the Writer interface. * @param out The writer to print the xml to. */ - public XMLWriter(Writer out) { + public XMLWriter(Writer out,String encoding,String charNewLine,String charTab) { + if (out==null) { + throw new NullPointerException("Can't write on null writer."); + } + if (encoding==null) { + encoding = XMLConstants.XML_DEFAULT_ENCODING; + } + if (charNewLine==null) { + charNewLine = XMLConstants.CHAR_NEWLINE; + } + if (charTab==null) { + charTab = XMLConstants.CHAR_TAB; + } this.out = out; + this.encoding = encoding; + this.charNewline = charNewLine; + this.charTab = charTab; + prefixMapping = new HashMap(15); + printedMappings = new ArrayList(15); + } + + /** + * Creates XmlWriter which prints to the Writer interface. + * @param out The writer to print the xml to. + */ + public XMLWriter(Writer out,String encoding) { + this(out,encoding,null,null); + } + + /** + * Creates XmlWriter which prints to the OutputStream interface. + * @param out The OutputStream to write to. + * @throws UnsupportedEncodingException Is thrown when UTF-8 can't we printed. + */ + public XMLWriter(OutputStream out,String encoding) throws UnsupportedEncodingException { + this(new OutputStreamWriter(out, encoding),encoding); + } + + /** + * Creates XmlWriter which prints to the Writer interface. + * @param out The writer to print the xml to. + */ + public XMLWriter(Writer out) { + this(out,null); } /** @@ -69,9 +120,11 @@ public class XMLWriter extends DefaultHandler2 { * @throws UnsupportedEncodingException Is thrown when UTF-8 can't we printed. */ public XMLWriter(OutputStream out) throws UnsupportedEncodingException { - this.out = new OutputStreamWriter(out, "UTF-8"); + this(new OutputStreamWriter(out, XMLConstants.XML_DEFAULT_ENCODING),XMLConstants.XML_DEFAULT_ENCODING); } + + /** * @see org.xml.sax.ContentHandler#startDocument() */ @@ -79,7 +132,7 @@ public class XMLWriter extends DefaultHandler2 { public void startDocument() throws SAXException { indent = 0; try { - out.write(""); + out.write(XMLConstants.getDocumentDeclaration(encoding)); } catch (IOException e) { throw new SAXException(e); } @@ -91,7 +144,7 @@ public class XMLWriter extends DefaultHandler2 { @Override public void endDocument() throws SAXException { try { - out.flush(); + out.flush(); } catch (IOException e) { throw new SAXException(e); } @@ -111,39 +164,37 @@ public class XMLWriter extends DefaultHandler2 { out.write(startElement.toString()); startElement=null; } - startElement = new StringBuffer(200); if (printedReturn==false) { - startElement.append("\r\n"); + startElement.append(charNewline); } printedReturn=false; for (int i = 0; i < indent; i++) { - startElement.append('\t'); + startElement.append(charTab); } - startElement.append("<"); + startElement.append(XMLConstants.TAG_OPEN); if (localName==null) { localName = "null"; } - if ("".equals(uri) | uri==null) { + if (XMLConstants.NULL_NS_URI.equals(uri) | uri==null) { startElement.append(localName); } else { String prefix = prefixMapping.get(uri); if (prefix==null) { throw new SAXException("preFixUri: "+uri+" is not started."); } - if ("".equals(prefix)==false) { + if (XMLConstants.NULL_NS_URI.equals(prefix)==false) { startElement.append(prefix); - startElement.append(':'); + startElement.append(XMLConstants.XMLNS_ASSIGN); } startElement.append(localName); } - - - if ((uri!=null & "".equals(uri)==false) && printedMappings.contains(uri)==false) { + + if ((uri!=null & XMLConstants.NULL_NS_URI.equals(uri)==false) && printedMappings.contains(uri)==false) { String prefix = prefixMapping.get(uri); if (prefix==null) { throw new SAXException("preFixUri: "+uri+" is not started."); @@ -151,7 +202,7 @@ public class XMLWriter extends DefaultHandler2 { printedMappings.add(uri); startElement.append(' '); - startElement.append("xmlns"); + startElement.append(XMLConstants.XMLNS_ATTRIBUTE); if ("".equals(prefix)==false) { startElement.append(':'); startElement.append(prefix); @@ -170,20 +221,20 @@ public class XMLWriter extends DefaultHandler2 { printedMappings.add(uri2); if (first) { - startElement.append('\n'); + startElement.append(charNewline); first = false; } startElement.append(' '); - startElement.append("xmlns"); + startElement.append(XMLConstants.XMLNS_ATTRIBUTE); if ("".equals(prefix)==false) { - startElement.append(':'); + startElement.append(XMLConstants.XMLNS_ASSIGN); startElement.append(prefix); } startElement.append("=\""); startElement.append(uri2); startElement.append('"'); - startElement.append('\n'); + startElement.append(charNewline); } } } @@ -196,34 +247,19 @@ public class XMLWriter extends DefaultHandler2 { attributeValue = "null"; } startElement.append(' '); - if ("".equals(attributeUri) | attributeUri ==null) { - startElement.append(attributeName); + if (XMLConstants.NULL_NS_URI.equals(attributeUri) | attributeUri ==null) { + startElement.append(attributeName); } else { startElement.append(attributeUri); - startElement.append(':'); + startElement.append(XMLConstants.XMLNS_ASSIGN); startElement.append(attributeName); } startElement.append("=\""); - - // TODO: xml escaping of attributes - if (attributeValue.contains("&")) { - attributeValue=attributeValue.replaceAll("&", "&"); - } - if (attributeValue.contains("\"")) { - attributeValue=attributeValue.replaceAll("\"", ""e;"); - } - if (attributeValue.contains("<")) { - attributeValue=attributeValue.replaceAll("<", "<"); - } - if (attributeValue.contains(">")) { - attributeValue=attributeValue.replaceAll(">", ">"); - } - - startElement.append(attributeValue); + startElement.append(XMLConstants.escapeAttributeValue(attributeValue)); startElement.append('"'); } - startElement.append(">"); + startElement.append(XMLConstants.TAG_CLOSE); } catch (IOException e) { throw new SAXException(e); } finally { @@ -243,41 +279,41 @@ public class XMLWriter extends DefaultHandler2 { if (startElement!=null) { String ss = startElement.toString(); out.write(ss,0,ss.length()-1); - out.write("/>"); + out.write(XMLConstants.TAG_CLOSE_EMPTY); startElement=null; indent--; return; } if (printedReturn==false) { - out.write("\r\n"); + out.write(charNewline); } printedReturn=false; indent--; - indent(); + writeIndent(); if (localName==null) { localName = "null"; } - out.write(""); + out.write(XMLConstants.TAG_CLOSE); } catch (IOException e) { throw new SAXException(e); - } + } } /** @@ -297,7 +333,7 @@ public class XMLWriter extends DefaultHandler2 { */ @Override public void endPrefixMapping(String prefix) throws SAXException { - Set> s=prefixMapping.entrySet(); + Set> s = prefixMapping.entrySet(); String uri = null; for (Map.Entry e:s) { if (e.getValue()==null) { @@ -329,16 +365,13 @@ public class XMLWriter extends DefaultHandler2 { out.write(startElement.toString()); startElement=null; } - /// mmm todo improve a bit for (int i=start;i<(start+length);i++) { char c = ch[i]; out.write(c); if (c=='\n') { printedReturn=true; - continue; } } - //out.write(ch, start, length); } catch (IOException e) { throw new SAXException(e); } @@ -376,8 +409,14 @@ public class XMLWriter extends DefaultHandler2 { @Override public void processingInstruction(String target, String data) throws SAXException { try { - indent(); - out.write("\r\n"); + writeIndent(); + out.write(XMLConstants.PROCESS_START); + out.write(target); + out.write(' '); + out.write(data); + out.write(XMLConstants.PROCESS_END); + out.write(charNewline); + out.flush(); } catch (IOException e) { throw new SAXException(e); } @@ -416,20 +455,20 @@ public class XMLWriter extends DefaultHandler2 { @Override public void comment(char[] ch, int start, int length) throws SAXException { try { - indent(); - out.write(""); + out.write(XMLConstants.COMMENT_END); } catch (IOException e) { throw new SAXException(e); } @@ -439,9 +478,9 @@ public class XMLWriter extends DefaultHandler2 { * Indent the output writer with tabs by indent count. * @throws IOException When prints gives exception. */ - private void indent() throws IOException { + private void writeIndent() throws IOException { for (int i = 0; i < indent; i++) { - out.write('\t'); + out.write(charTab); } } } diff --git a/x4o-core/src/main/java/org/x4o/xml/sax/package-info.java b/x4o-core/src/main/java/org/x4o/xml/io/sax/package-info.java similarity index 98% rename from x4o-core/src/main/java/org/x4o/xml/sax/package-info.java rename to x4o-core/src/main/java/org/x4o/xml/io/sax/package-info.java index 69bf3ce..473e52b 100644 --- a/x4o-core/src/main/java/org/x4o/xml/sax/package-info.java +++ b/x4o-core/src/main/java/org/x4o/xml/io/sax/package-info.java @@ -27,4 +27,4 @@ * @since 1.0 */ -package org.x4o.xml.sax; +package org.x4o.xml.io.sax; diff --git a/x4o-core/src/main/java/org/x4o/xml/package-info.java b/x4o-core/src/main/java/org/x4o/xml/package-info.java new file mode 100644 index 0000000..8338b0d --- /dev/null +++ b/x4o-core/src/main/java/org/x4o/xml/package-info.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Provides interfaces for two way object converters. + * + * + * @since 1.0 + * @author Willem Cazander + */ + +package org.x4o.xml; diff --git a/x4o-core/src/main/resources/META-INF/language/drivers-1.0.xsd b/x4o-core/src/main/resources/META-INF/language/drivers-1.0.xsd new file mode 100644 index 0000000..07d15d1 --- /dev/null +++ b/x4o-core/src/main/resources/META-INF/language/drivers-1.0.xsd @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/x4o-core/src/main/resources/META-INF/x4o-drivers.xml b/x4o-core/src/main/resources/META-INF/x4o-drivers.xml new file mode 100644 index 0000000..abd4e9c --- /dev/null +++ b/x4o-core/src/main/resources/META-INF/x4o-drivers.xml @@ -0,0 +1,33 @@ + + + + + + diff --git a/x4o-core/src/test/java/org/x4o/xml/core/X4OParserTest.java b/x4o-core/src/test/java/org/x4o/xml/X4ODriverManagerTest.java similarity index 68% rename from x4o-core/src/test/java/org/x4o/xml/core/X4OParserTest.java rename to x4o-core/src/test/java/org/x4o/xml/X4ODriverManagerTest.java index 8ad2c5d..bc62b0d 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/X4OParserTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/X4ODriverManagerTest.java @@ -21,27 +21,29 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package org.x4o.xml.core; +package org.x4o.xml; -import org.x4o.xml.core.config.X4OLanguageConfiguration; +import java.util.List; + +import org.x4o.xml.X4ODriverManager; import org.x4o.xml.core.config.X4OLanguageLoaderException; +import org.x4o.xml.core.phase.X4OPhaseException; import junit.framework.TestCase; /** - * X4OParserTest runs parser checks. + * X4ODriverManager * * @author Willem Cazander - * @version 1.0 Aug 26, 2012 + * @version 1.0 Jul 24, 2006 */ -public class X4OParserTest extends TestCase { - - +public class X4ODriverManagerTest extends TestCase { + public void testLanguageNull() throws Exception { String language = null; Exception e = null; try { - new X4OParser(language); + X4ODriverManager.getX4ODriver(language); } catch (Exception catchE) { e = catchE; } @@ -49,12 +51,12 @@ public class X4OParserTest extends TestCase { assertEquals(NullPointerException.class, e.getClass()); assertTrue(e.getMessage().contains("language")); } - + public void testLanguageEmpty() throws Exception { String language = ""; Exception e = null; try { - new X4OParser(language); + X4ODriverManager.getX4ODriver(language); } catch (Exception catchE) { e = catchE; } @@ -64,49 +66,48 @@ public class X4OParserTest extends TestCase { } public void testLanguageVersionNonExcisting() throws Exception { + String language = "test"; + String version = "99.9"; Exception e = null; try { - X4OParser p = new X4OParser("test","2.0"); - p.loadElementLanguageSupport(); + X4ODriver driver = X4ODriverManager.getX4ODriver(language); + driver.createLanguageContext(version); } catch (Exception catchE) { e = catchE; } + /* TODO assertNotNull(e); assertNotNull(e.getCause()); assertNotNull(e.getCause().getCause()); - assertEquals(X4OParserSupportException.class, e.getClass()); assertEquals(X4OPhaseException.class, e.getCause().getClass()); assertEquals(X4OLanguageLoaderException.class, e.getCause().getCause().getClass()); assertTrue("Error message string is missing language",e.getMessage().contains("language")); assertTrue("Error message string is missing test",e.getMessage().contains("test")); assertTrue("Error message string is missing modules",e.getMessage().contains("modules")); assertTrue("Error message string is missing 2.0",e.getMessage().contains("2.0")); + */ } - - public void testDriverConfig() throws Exception { - X4OLanguageConfiguration config = null; - Exception e = null; - try { - new X4OParser(config); - } catch (Exception catchE) { - e = catchE; - } - assertNotNull(e); - assertEquals(NullPointerException.class, e.getClass()); - assertTrue("Error message string is missing X4OLanguageConfiguration",e.getMessage().contains("X4OLanguageConfiguration")); + public void testLanguageCount() throws Exception { + List languages = X4ODriverManager.getX4OLanguages(); + assertNotNull(languages); + assertFalse(languages.isEmpty()); } - public void testDriverNull() throws Exception { - X4ODriver driver = null; - Exception e = null; - try { - new X4OParser(driver); - } catch (Exception catchE) { - e = catchE; + public void testLanguageNames() throws Exception { + List languages = X4ODriverManager.getX4OLanguages(); + assertNotNull(languages); + assertTrue("cel language is missing",languages.contains("cel")); + assertTrue("eld language is missing",languages.contains("eld")); + assertTrue("test language is missing",languages.contains("test")); + } + + public void testLanguagesLoopSpeed() throws Exception { + long startTime = System.currentTimeMillis(); + for (int i=0;i<100;i++) { + testLanguageCount(); } - assertNotNull(e); - assertEquals(NullPointerException.class, e.getClass()); - assertTrue("Error message string is missing X4ODriver",e.getMessage().contains("X4ODriver")); + long loopTime = System.currentTimeMillis() - startTime; + assertEquals("Language list loop is slow;"+loopTime,true, loopTime<500); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/conv/DefaultObjectConverterProviderTest.java b/x4o-core/src/test/java/org/x4o/xml/conv/DefaultObjectConverterProviderTest.java index a663391..3246f34 100644 --- a/x4o-core/src/test/java/org/x4o/xml/conv/DefaultObjectConverterProviderTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/conv/DefaultObjectConverterProviderTest.java @@ -30,7 +30,7 @@ import java.util.Locale; import org.x4o.xml.conv.text.ClassConverter; import org.x4o.xml.conv.text.EnumConverter; import org.x4o.xml.conv.text.URLConverter; -import org.x4o.xml.core.X4OPhase; +import org.x4o.xml.core.phase.X4OPhaseType; import junit.framework.TestCase; @@ -155,18 +155,18 @@ public class DefaultObjectConverterProviderTest extends TestCase { public void testConverterEnum() throws Exception { EnumConverter convOrg = new EnumConverter(); - convOrg.setEnumClass(X4OPhase.class.getName()); + convOrg.setEnumClass(X4OPhaseType.class.getName()); ObjectConverter conv = convOrg.clone(); - Object result = conv.convertTo("runAttributesPhase", locale); + Object result = conv.convertTo("XML_READ", locale); assertNotNull(result); - assertEquals("runAttributesPhase", result.toString()); + assertEquals("XML_READ", result.toString()); Object resultBack = conv.convertBack(result, locale); - assertEquals("runAttributesPhase", resultBack.toString()); + assertEquals("XML_READ", resultBack.toString()); } public void testConverterEnumError() throws Exception { EnumConverter convOrg = new EnumConverter(); - convOrg.setEnumClass(X4OPhase.class.getName()); + convOrg.setEnumClass(X4OPhaseType.class.getName()); ObjectConverter conv = convOrg.clone(); Exception e = null; diff --git a/x4o-core/src/test/java/org/x4o/xml/core/AttributeBeanTest.java b/x4o-core/src/test/java/org/x4o/xml/core/AttributeBeanTest.java index cf42bd4..8fb4fee 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/AttributeBeanTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/AttributeBeanTest.java @@ -23,9 +23,11 @@ package org.x4o.xml.core; -import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.TestDriver; import org.x4o.xml.test.models.TestBean; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -38,37 +40,37 @@ import junit.framework.TestCase; public class AttributeBeanTest extends TestCase { public void testBeanProperties() throws Exception { - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); - try { - parser.parseResource("tests/attributes/test-bean.xml"); - TestBean b = (TestBean)parser.getElementLanguage().getRootElement().getChilderen().get(1).getElementObject(); - - assertEquals(123 ,0+ b.getPrivateIntegerTypeField()); - assertEquals(123 ,0+ b.getPrivateIntegerObjectField()); - - assertEquals(123l ,0+ b.getPrivateLongTypeField()); - assertEquals(123l ,0+ b.getPrivateLongObjectField()); - - assertEquals(123.45d ,0+ b.getPrivateDoubleTypeField()); - assertEquals(123.45d ,0+ b.getPrivateDoubleObjectField()); - - assertEquals(123.45f ,0+ b.getPrivateFloatTypeField()); - assertEquals(123.45f ,0+ b.getPrivateFloatObjectField()); - - assertEquals(67 ,0+ b.getPrivateByteTypeField()); - assertEquals(67 ,0+ b.getPrivateByteObjectField()); - - assertEquals(true, b.isPrivateBooleanTypeField()); - assertEquals(new Boolean(true), b.getPrivateBooleanObjectField()); - - assertEquals('W' ,0+ b.getPrivateCharTypeField()); - assertEquals('C' ,0+ b.getPrivateCharObjectField()); - - assertEquals("x4o" ,b.getPrivateStringObjectField()); - //TODO: add again: assertEquals(true ,null!=b.getPrivateDateObjectField()); - } finally { - parser.doReleasePhaseManual(); - } + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + + TestObjectRoot root = reader.readResource("tests/attributes/test-bean.xml"); + assertNotNull(root); + assertNotNull(root.getTestBeans()); + assertEquals(2, root.getTestBeans().size()); + TestBean b = root.getTestBeans().get(0); + + assertEquals(123 ,0+ b.getPrivateIntegerTypeField()); + assertEquals(123 ,0+ b.getPrivateIntegerObjectField()); + + assertEquals(123l ,0+ b.getPrivateLongTypeField()); + assertEquals(123l ,0+ b.getPrivateLongObjectField()); + + assertEquals(123.45d ,0+ b.getPrivateDoubleTypeField()); + assertEquals(123.45d ,0+ b.getPrivateDoubleObjectField()); + + assertEquals(123.45f ,0+ b.getPrivateFloatTypeField()); + assertEquals(123.45f ,0+ b.getPrivateFloatObjectField()); + + assertEquals(67 ,0+ b.getPrivateByteTypeField()); + assertEquals(67 ,0+ b.getPrivateByteObjectField()); + + assertEquals(true, b.isPrivateBooleanTypeField()); + assertEquals(new Boolean(true), b.getPrivateBooleanObjectField()); + + assertEquals('W' ,0+ b.getPrivateCharTypeField()); + assertEquals('C' ,0+ b.getPrivateCharObjectField()); + + assertEquals("x4o" ,b.getPrivateStringObjectField()); + //TODO: add again: assertEquals(true ,null!=b.getPrivateDateObjectField()); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/core/EmptyXmlTest.java b/x4o-core/src/test/java/org/x4o/xml/core/EmptyXmlTest.java index cc68c5f..7a6e4b2 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/EmptyXmlTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/EmptyXmlTest.java @@ -25,8 +25,10 @@ package org.x4o.xml.core; import java.io.FileNotFoundException; -import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import junit.framework.TestCase; @@ -38,14 +40,12 @@ import junit.framework.TestCase; * @version 1.0 Jul 24, 2006 */ public class EmptyXmlTest extends TestCase { - - public void setUp() throws Exception { - } public void testFileNotFound() throws Exception { - TestParser parser = new TestParser(); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); try { - parser.parseFile("tests/empty-xml/non-excisting-file.xml"); + reader.readFile("tests/empty-xml/non-excisting-file.xml"); } catch (FileNotFoundException e) { assertEquals(true, e.getMessage().contains("non-excisting-file.xml")); return; @@ -54,9 +54,10 @@ public class EmptyXmlTest extends TestCase { } public void testResourceNotFound() throws Exception { - TestParser parser = new TestParser(); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); try { - parser.parseResource("tests/empty-xml/non-excisting-resource.xml"); + reader.readResource("tests/empty-xml/non-excisting-resource.xml"); } catch (NullPointerException e) { assertEquals(true,e.getMessage().contains("Could not find resource")); return; @@ -65,9 +66,10 @@ public class EmptyXmlTest extends TestCase { } public void testResourceParsing() throws Exception { - TestParser parser = new TestParser(); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); try { - parser.parseResource("tests/empty-xml/empty-test.xml"); + reader.readResource("tests/empty-xml/empty-test.xml"); } catch (SAXParseException e) { assertEquals("No ElementNamespaceContext found for empty namespace.", e.getMessage()); return; @@ -76,9 +78,10 @@ public class EmptyXmlTest extends TestCase { } public void testResourceEmptyReal() throws Exception { - TestParser parser = new TestParser(); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); try { - parser.parseResource("tests/empty-xml/empty-real.xml"); + reader.readResource("tests/empty-xml/empty-real.xml"); } catch (SAXException e) { assertEquals(true,e.getMessage().contains("Premature end of file.")); return; @@ -87,9 +90,10 @@ public class EmptyXmlTest extends TestCase { } public void testResourceEmptyXml() throws Exception { - TestParser parser = new TestParser(); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); try { - parser.parseResource("tests/empty-xml/empty-xml.xml"); + reader.readResource("tests/empty-xml/empty-xml.xml"); } catch (SAXException e) { boolean hasError = e.getMessage().contains("Premature end of file."); // java6+ sax message if (hasError==false) { @@ -102,13 +106,18 @@ public class EmptyXmlTest extends TestCase { } public void testEmptyX40() throws Exception { - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); - try { - parser.parseResource("tests/empty-xml/empty-x4o.xml"); - assertEquals(true,parser.getElementLanguage().getRootElement().getChilderen().isEmpty()); - } finally { - parser.doReleasePhaseManual(); - } + X4ODriver driver = TestDriver.getInstance(); + assertNotNull(driver); + + X4OReader reader = driver.createReader(); + assertNotNull(reader); + + TestObjectRoot root = reader.readResource("tests/empty-xml/empty-x4o.xml"); + assertNotNull(root); + + assertEquals(true,root.getTestBeans().isEmpty()); + assertEquals(true,root.getTestObjectChilds().isEmpty()); + assertEquals(true,root.getTestObjectParents().isEmpty()); + assertEquals(true,root.getTestObjects().isEmpty()); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/core/NamespaceUriTest.java b/x4o-core/src/test/java/org/x4o/xml/core/NamespaceUriTest.java index b72837b..1860cd0 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/NamespaceUriTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/NamespaceUriTest.java @@ -24,7 +24,10 @@ package org.x4o.xml.core; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.io.X4OReaderContext; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -37,36 +40,42 @@ import junit.framework.TestCase; public class NamespaceUriTest extends TestCase { public void testSimpleUri() throws Exception { - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + ElementLanguage context = null; + TestDriver driver = TestDriver.getInstance(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); try { - parser.parseResource("tests/namespace/uri-simple.xml"); - assertEquals(true,parser.getElementLanguage().getRootElement().getChilderen().size()==1); + context = reader.readResourceContext("tests/namespace/uri-simple.xml"); + assertEquals(true,context.getRootElement().getChilderen().size()==1); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } public void testEmptyUri() throws Exception { - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); - parser.setProperty(X4OLanguagePropertyKeys.INPUT_EMPTY_NAMESPACE_URI, "http://test.x4o.org/xml/ns/test-lang"); + ElementLanguage context = null; + TestDriver driver = TestDriver.getInstance(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + reader.setProperty(X4OLanguagePropertyKeys.INPUT_EMPTY_NAMESPACE_URI, "http://test.x4o.org/xml/ns/test-lang"); try { - parser.parseResource("tests/namespace/uri-empty.xml"); - assertEquals(true,parser.getElementLanguage().getRootElement().getChilderen().size()==1); + context = reader.readResourceContext("tests/namespace/uri-empty.xml"); + assertEquals(true,context.getRootElement().getChilderen().size()==1); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } public void testSchemaUri() throws Exception { - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + ElementLanguage context = null; + TestDriver driver = TestDriver.getInstance(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); try { - parser.parseResource("tests/namespace/uri-schema.xml"); - assertEquals(true,parser.getElementLanguage().getRootElement().getChilderen().size()==1); + context = reader.readResourceContext("tests/namespace/uri-schema.xml"); + assertEquals(true,context.getRootElement().getChilderen().size()==1); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } } diff --git a/x4o-core/src/test/java/org/x4o/xml/core/X4ODebugWriterTest.java b/x4o-core/src/test/java/org/x4o/xml/core/X4ODebugWriterTest.java index db70d27..c4427a8 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/X4ODebugWriterTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/X4ODebugWriterTest.java @@ -27,8 +27,11 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import org.x4o.xml.X4ODriver; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -49,20 +52,24 @@ public class X4ODebugWriterTest extends TestCase { public void testDebugOutput() throws Exception { File debugFile = createDebugFile(); - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(debugFile)); - parser.parseResource("tests/attributes/test-bean.xml"); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(debugFile)); + reader.readResource("tests/attributes/test-bean.xml"); assertTrue("Debug file does not exists.",debugFile.exists()); + debugFile.delete(); } public void testDebugOutputFull() throws Exception { File debugFile = createDebugFile(); - TestParser parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(debugFile)); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_ELD_PARSER, true); - parser.parseResource("tests/attributes/test-bean.xml"); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(debugFile)); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_ELD_PARSER, true); + reader.readResource("tests/attributes/test-bean.xml"); assertTrue("Debug file does not exists.",debugFile.exists()); + debugFile.delete(); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/core/X4OEntityResolverTest.java b/x4o-core/src/test/java/org/x4o/xml/core/X4OEntityResolverTest.java index fc37ad2..d519684 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/X4OEntityResolverTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/X4OEntityResolverTest.java @@ -25,9 +25,12 @@ package org.x4o.xml.core; import java.io.IOException; +import org.x4o.xml.X4ODriver; import org.x4o.xml.core.config.X4OLanguageProperty; -import org.x4o.xml.eld.EldParserSupportCore; +import org.x4o.xml.eld.CelDriver; import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -55,15 +58,15 @@ public class X4OEntityResolverTest extends TestCase { } public void testResolve() throws Exception { - EldParserSupportCore support = new EldParserSupportCore(); - X4OEntityResolver resolver = new X4OEntityResolver(support.loadElementLanguageSupport()); + X4ODriver driver = new CelDriver(); + X4OEntityResolver resolver = new X4OEntityResolver(driver.createLanguageContext()); InputSource input = resolver.resolveEntity("","http://cel.x4o.org/xml/ns/cel-root-1.0.xsd"); assertNotNull(input); } public void testResolveMissing() throws Exception { - EldParserSupportCore support = new EldParserSupportCore(); - X4OEntityResolver resolver = new X4OEntityResolver(support.loadElementLanguageSupport()); + X4ODriver driver = new TestDriver(); + X4OEntityResolver resolver = new X4OEntityResolver(driver.createLanguageContext()); Exception e = null; try { resolver.resolveEntity("","http://cel.x4o.org/xml/ns/cel-root-1.0.xsd-missing-resource"); @@ -76,9 +79,9 @@ public class X4OEntityResolverTest extends TestCase { } public void testResolveProperty() throws Exception { - EldParserSupportCore support = new EldParserSupportCore(); - ElementLanguage language = support.loadElementLanguageSupport(); - language.getLanguageConfiguration().setLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER, new TestEntityResolver()); + X4ODriver driver = new TestDriver(); + ElementLanguage language = driver.createLanguageContext(); + language.setLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER, new TestEntityResolver()); X4OEntityResolver resolver = new X4OEntityResolver(language); Exception e = null; InputSource input = null; @@ -92,9 +95,9 @@ public class X4OEntityResolverTest extends TestCase { } public void testResolvePropertyNull() throws Exception { - EldParserSupportCore support = new EldParserSupportCore(); - ElementLanguage language = support.loadElementLanguageSupport(); - language.getLanguageConfiguration().setLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER, new TestEntityResolver()); + X4ODriver driver = new TestDriver(); + ElementLanguage language = driver.createLanguageContext(); + language.setLanguageProperty(X4OLanguageProperty.CONFIG_ENTITY_RESOLVER, new TestEntityResolver()); X4OEntityResolver resolver = new X4OEntityResolver(language); Exception e = null; try { diff --git a/x4o-core/src/test/java/org/x4o/xml/core/X4OParserConfigurationTest.java b/x4o-core/src/test/java/org/x4o/xml/core/X4OParserConfigurationTest.java index 4422c4f..d03a46c 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/X4OParserConfigurationTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/X4OParserConfigurationTest.java @@ -24,11 +24,10 @@ package org.x4o.xml.core; import org.x4o.xml.core.config.X4OLanguageConfiguration; -import org.x4o.xml.core.config.X4OLanguagePropertyKeys; import org.x4o.xml.element.Element; import org.x4o.xml.element.ElementClass; import org.x4o.xml.element.ElementClassAttribute; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.test.TestDriver; import junit.framework.TestCase; @@ -40,22 +39,16 @@ import junit.framework.TestCase; */ public class X4OParserConfigurationTest extends TestCase { - TestParser parser; + TestDriver driver; X4OLanguageConfiguration config; public void setUp() throws Exception { - parser = new TestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); - try { - parser.parseResource("tests/namespace/uri-simple.xml"); - config = parser.getElementLanguage().getLanguageConfiguration(); - } finally { - parser.doReleasePhaseManual(); - } + driver = TestDriver.getInstance(); + config = driver.createLanguageContext().getLanguage().getLanguageConfiguration(); } public void testParserConfigurationLanguage() { - assertEquals("test",config.getLanguage()); + assertEquals("test",driver.getLanguageName()); assertEquals(X4OLanguageConfiguration.DEFAULT_LANG_MODULES_FILE,config.getLanguageResourceModulesFileName()); assertEquals(X4OLanguageConfiguration.DEFAULT_LANG_PATH_PREFIX,config.getLanguageResourcePathPrefix()); } diff --git a/x4o-core/src/test/java/org/x4o/xml/core/X4OPhaseManagerTest.java b/x4o-core/src/test/java/org/x4o/xml/core/X4OPhaseManagerTest.java index f585c13..bf9738b 100644 --- a/x4o-core/src/test/java/org/x4o/xml/core/X4OPhaseManagerTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/core/X4OPhaseManagerTest.java @@ -23,12 +23,14 @@ package org.x4o.xml.core; +import java.util.Collection; import java.util.List; -import org.x4o.xml.core.X4OPhase; -import org.x4o.xml.core.X4OPhaseHandler; -import org.x4o.xml.core.X4OPhaseManager; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.core.phase.X4OPhase; +import org.x4o.xml.core.phase.X4OPhaseManager; +import org.x4o.xml.core.phase.X4OPhaseType; +import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.test.TestDriver; import junit.framework.TestCase; @@ -47,26 +49,27 @@ public class X4OPhaseManagerTest extends TestCase { phaseRunned = false; } - public void testPhaseOrder() throws Exception { - TestParser parser = new TestParser(); - X4OPhaseManager manager = parser.getDriver().createX4OPhaseManager(); - - assertEquals(false,manager.getPhases().isEmpty()); - List phases = manager.getOrderedPhases(); - - int i = 0; - for (X4OPhase phase:X4OPhase.PHASE_ORDER) { - //if (X4OPhase.configOptionalPhase.equals(phase)) { - // continue; - //} - assertEquals(phase, phases.get(i).getX4OPhase()); - i++; + public void testPhases() throws Exception { + TestDriver driver = TestDriver.getInstance(); + ElementLanguage context = driver.createLanguageContext(); + X4OPhaseManager manager = context.getLanguage().getPhaseManager(); + Collection phasesAll = manager.getAllPhases(); + List phases = manager.getOrderedPhases(X4OPhaseType.XML_READ); + assertNotNull(phases); + assertFalse(phases.isEmpty()); + assertNotNull(phasesAll); + assertFalse(phasesAll.isEmpty()); + for (X4OPhase phase:phases) { + assertNotNull(phase); + assertNotNull(phase.getId()); } } + /* public void testPhaseManager() throws Exception { - TestParser parser = new TestParser(); - X4OPhaseManager manager = parser.getDriver().createX4OPhaseManager(); + TestDriver driver = TestDriver.getInstance(); + ElementLanguage context = driver.createLanguageContext(); + X4OPhaseManager manager = context.getLanguage().getPhaseManager(); Exception e = null; try { @@ -76,4 +79,5 @@ public class X4OPhaseManagerTest extends TestCase { } assertEquals(true, e!=null ); } + */ } diff --git a/x4o-core/src/test/java/org/x4o/xml/eld/EldParserTest.java b/x4o-core/src/test/java/org/x4o/xml/eld/EldParserTest.java index 7c320c1..082582e 100644 --- a/x4o-core/src/test/java/org/x4o/xml/eld/EldParserTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/eld/EldParserTest.java @@ -23,14 +23,24 @@ package org.x4o.xml.eld; +import java.io.File; import java.util.ArrayList; import java.util.List; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.eld.EldParser; +import org.x4o.xml.eld.EldDriver; import org.x4o.xml.element.Element; +import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.Element.ElementType; import org.x4o.xml.element.ElementClass; +import org.x4o.xml.element.ElementLanguageModule; +import org.x4o.xml.element.ElementNamespaceContext; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.io.X4OSchemaWriter; +import org.x4o.xml.io.X4OWriter; +import org.x4o.xml.test.TestDriver; import junit.framework.TestCase; @@ -42,12 +52,46 @@ import junit.framework.TestCase; */ public class EldParserTest extends TestCase { - public void testRunEldParserCore() throws Exception { - EldParser parser = new EldParser(true); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + public void testNone() { + /* + X4ODriver driver = X4ODriverManager.getX4ODriver(TestDriver.LANGUAGE); + driver.setGlobalProperty("", ""); + + ElementLanguage lang = driver.createLanguage(); + X4OSchemaWriter schemaWriter = driver.createSchemaWriter(); + schemaWriter.writeSchema(new File("/tmp")); + + X4OReader reader = driver.createReader(); + //reader.setProperty("", ""); + //reader.addELBeanInstance(name, bean) + Object rootTreeNode = (Object)reader.readResource("com/iets/foo/test.xml"); + + + X4OWriter writer = driver.createWriter(); + writer.writeFile(new File("/tmp/output.xml")); + try { - parser.parseResource("META-INF/eld/eld-lang.eld"); + read.readResource(""); + } catch (Exception e) { + e.printStackTrace(); + } + */ + } + + public void testRunEldParserCore() throws Exception { + + X4ODriver driver = (X4ODriver)X4ODriverManager.getX4ODriver(EldDriver.LANGUAGE_NAME); + + X4OReader reader = driver.createReader(); + //EldDriver parser = new EldDriver(true); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + try { + ElementLanguageModule module = reader.readResource("META-INF/eld/eld-lang.eld"); List resultTags = new ArrayList(50); + for (ElementNamespaceContext ns:module.getElementNamespaceContexts()) { + + } + /* for (Element e:parser.getDriver().getElementLanguage().getRootElement().getAllChilderen()) { //System.out.println("obj: "+e.getElementObject()); if (e.getElementType().equals(ElementType.element) && e.getElementObject() instanceof ElementClass) { @@ -55,6 +99,7 @@ public class EldParserTest extends TestCase { resultTags.add(ec.getTag()); } } + */ //TODO fix test /* assertTrue("No module tag found in core eld.", resultTags.contains("module")); @@ -63,13 +108,18 @@ public class EldParserTest extends TestCase { assertTrue("No bean tag found in core eld.", resultTags.contains("bean")); assertTrue("No elementConfigurator tag found in core eld.", resultTags.contains("elementConfigurator")); */ + } catch (Exception e) { + e.printStackTrace(); } finally { - parser.doReleasePhaseManual(); + // parser.doReleasePhaseManual(); } } public void testRunEldParser() throws Exception { - EldParser parser = new EldParser(false); - parser.parseResource("META-INF/test/test-lang.eld"); + //EldDriver parser = new EldDriver(false); + //parser.parseResource("META-INF/test/test-lang.eld"); + X4ODriver driver = (X4ODriver)X4ODriverManager.getX4ODriver(EldDriver.LANGUAGE_NAME); + X4OReader reader = driver.createReader(); + reader.readResource("META-INF/test/test-lang.eld"); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/eld/EldSchemaTest.java b/x4o-core/src/test/java/org/x4o/xml/eld/EldSchemaTest.java index 7b437c2..aa59b3e 100644 --- a/x4o-core/src/test/java/org/x4o/xml/eld/EldSchemaTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/eld/EldSchemaTest.java @@ -25,8 +25,8 @@ package org.x4o.xml.eld; import java.io.File; -import org.x4o.xml.eld.xsd.X4OLanguageEldXsdWriter; -import org.x4o.xml.test.swixml.SwiXmlParserSupport2; +import org.x4o.xml.eld.xsd.X4OSchemaWriterExecutor; +import org.x4o.xml.test.swixml.SwiXmlDriver; import junit.framework.TestCase; @@ -51,27 +51,27 @@ public class EldSchemaTest extends TestCase { } public void testEldSchema() throws Exception { - X4OLanguageEldXsdWriter writer = new X4OLanguageEldXsdWriter(); + X4OSchemaWriterExecutor writer = new X4OSchemaWriterExecutor(); writer.setBasePath(getTempPath("junit-xsd-eld")); - writer.setLanguageParserSupport(EldParserSupport.class); + writer.setLanguage(EldDriver.LANGUAGE_NAME); writer.execute(); } public void testEldCoreSchema() throws Exception { - X4OLanguageEldXsdWriter writer = new X4OLanguageEldXsdWriter(); + X4OSchemaWriterExecutor writer = new X4OSchemaWriterExecutor(); writer.setBasePath(getTempPath("junit-xsd-cel")); - writer.setLanguageParserSupport(EldParserSupportCore.class); + writer.setLanguage(CelDriver.LANGUAGE_NAME); writer.execute(); } public void testSwiXmlSchema() throws Exception { - X4OLanguageEldXsdWriter writer = new X4OLanguageEldXsdWriter(); + X4OSchemaWriterExecutor writer = new X4OSchemaWriterExecutor(); writer.setBasePath(getTempPath("junit-xsd-swixml2")); - writer.setLanguageParserSupport(SwiXmlParserSupport2.class); + writer.setLanguage(SwiXmlDriver.LANGUAGE_NAME); writer.execute(); } public void testEldDocMain() throws Exception { - X4OLanguageEldXsdWriter.main(new String[] {"-path",getTempPath("junit-xsd-main").getAbsolutePath(),"-class",EldParserSupport.class.getName()}); + X4OSchemaWriterExecutor.main(new String[] {"-p",getTempPath("junit-xsd-main").getAbsolutePath(),"-l",EldDriver.LANGUAGE_NAME}); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/eld/EldValidatingTest.java b/x4o-core/src/test/java/org/x4o/xml/eld/EldValidatingTest.java index 1727602..4658fbe 100644 --- a/x4o-core/src/test/java/org/x4o/xml/eld/EldValidatingTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/eld/EldValidatingTest.java @@ -23,8 +23,12 @@ package org.x4o.xml.eld; +import org.x4o.xml.X4ODriver; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.eld.EldParser; +import org.x4o.xml.eld.EldDriver; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -37,14 +41,15 @@ import junit.framework.TestCase; public class EldValidatingTest extends TestCase { public void testValidation() throws Exception { - EldParser parser = new EldParser(true); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); - parser.setProperty(X4OLanguagePropertyKeys.VALIDATION_INPUT, true); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + reader.setProperty(X4OLanguagePropertyKeys.VALIDATION_INPUT, true); //parser.setProperty(X4OLanguagePropertyKeys.VALIDATION_SCHEMA_PATH, "/tmp"); try { - parser.parseResource("META-INF/eld/eld-lang.eld"); + // TODO: reader.readResource("META-INF/eld/eld-lang.eld"); } finally { - parser.doReleasePhaseManual(); + } } } diff --git a/x4o-core/src/test/java/org/x4o/xml/impl/DefaultX4OLanguageLoaderTest.java b/x4o-core/src/test/java/org/x4o/xml/impl/DefaultX4OLanguageLoaderTest.java index 28a9296..181364f 100644 --- a/x4o-core/src/test/java/org/x4o/xml/impl/DefaultX4OLanguageLoaderTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/impl/DefaultX4OLanguageLoaderTest.java @@ -23,8 +23,14 @@ package org.x4o.xml.impl; -import org.x4o.xml.impl.config.DefaultX4OLanguageLoader; -import org.x4o.xml.test.TestParser; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.core.config.DefaultX4OLanguageLoader; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.config.X4OLanguageLoader; +import org.x4o.xml.core.config.X4OLanguageLocal; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -36,17 +42,20 @@ import junit.framework.TestCase; */ public class DefaultX4OLanguageLoaderTest extends TestCase { - TestParser parser; - DefaultX4OLanguageLoader loader; + X4OLanguage language; + X4OLanguageLoader loader; public void setUp() throws Exception { - parser = new TestParser(); - parser.parseResource("tests/namespace/uri-simple.xml"); - loader = new DefaultX4OLanguageLoader(); + X4ODriver driver = TestDriver.getInstance(); + //X4OReader reader = driver.createReader(); + //reader.readResource("tests/namespace/uri-simple.xml"); + language = driver.createLanguageContext().getLanguage(); + loader = (X4OLanguageLoader)language.getLanguageConfiguration().getDefaultX4OLanguageLoader().newInstance(); + } public void testLanguageURINameSpaceTest() throws Exception { - loader.loadLanguage(parser.getElementLanguage(), "test", "1.0"); + loader.loadLanguage((X4OLanguageLocal)language, "test", "1.0"); } /* diff --git a/x4o-core/src/test/java/org/x4o/xml/test/SwingTests.java b/x4o-core/src/test/java/org/x4o/xml/test/SwingTests.java index 2140f26..893c58c 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/SwingTests.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/SwingTests.java @@ -26,8 +26,9 @@ package org.x4o.xml.test; import java.io.File; import java.io.FileOutputStream; -import org.x4o.xml.core.X4OParser; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -46,12 +47,13 @@ public class SwingTests extends TestCase { public void testSwing() throws Exception { - X4OParser parser = new X4OParser("test"); + TestDriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); File f = File.createTempFile("test-swing", ".xml"); //f.deleteOnExit(); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(f)); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_ELD_PARSER, true); - parser.parseResource("tests/test-swing.xml"); - Thread.sleep(30000); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(f)); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_ELD_PARSER, true); + //reader.readResource("tests/test-swing.xml"); + //Thread.sleep(30000); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/TagHandlerTest.java b/x4o-core/src/test/java/org/x4o/xml/test/TagHandlerTest.java index a095c94..860f9d3 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/TagHandlerTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/TagHandlerTest.java @@ -26,8 +26,10 @@ package org.x4o.xml.test; import java.io.File; import java.io.FileOutputStream; -import org.x4o.xml.core.X4OParser; +import org.x4o.xml.X4ODriver; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.io.X4OReader; +import org.x4o.xml.test.models.TestObjectRoot; import junit.framework.TestCase; @@ -53,14 +55,17 @@ public class TagHandlerTest extends TestCase { } public void testTagHanders() throws Exception { - X4OParser parser = new X4OParser("test"); + X4ODriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + /* File f = File.createTempFile("test-taghandlers", ".xml"); f.deleteOnExit(); - parser.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(f)); + reader.setProperty(X4OLanguagePropertyKeys.DEBUG_OUTPUT_STREAM, new FileOutputStream(f)); try { - //parser.parseResource("tests/test-taghandlers.xml"); + reader.readResource("tests/test-taghandlers.xml"); } catch (Exception e) { printS(e); } + */ } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/TestParserSupport.java b/x4o-core/src/test/java/org/x4o/xml/test/TestDriver.java similarity index 64% rename from x4o-core/src/test/java/org/x4o/xml/test/TestParserSupport.java rename to x4o-core/src/test/java/org/x4o/xml/test/TestDriver.java index 07cd0c2..e86cd3e 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/TestParserSupport.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/TestDriver.java @@ -23,14 +23,29 @@ package org.x4o.xml.test; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.X4ODriverManager; +import org.x4o.xml.io.DefaultX4ODriver; +import org.x4o.xml.io.X4OReaderContext; +import org.x4o.xml.io.X4OWriterContext; +import org.x4o.xml.test.models.TestObjectRoot; -public class TestParserSupport implements X4OParserSupport { +public class TestDriver extends DefaultX4ODriver { - public ElementLanguage loadElementLanguageSupport() throws X4OParserSupportException { - TestParser parser = new TestParser(); - return parser.loadElementLanguageSupport(); + static final public String LANGUAGE_NAME = "test"; + + public TestDriver() { + super(LANGUAGE_NAME); + } + + static public TestDriver getInstance() { + return (TestDriver)X4ODriverManager.getX4ODriver(LANGUAGE_NAME); + } + + public X4OReaderContext createReaderContext() { + return (X4OReaderContext)super.createReader(); + } + + public X4OWriterContext createWriterContext() { + return (X4OWriterContext)super.createWriter(); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/XIncludeTest.java b/x4o-core/src/test/java/org/x4o/xml/test/XIncludeTest.java index eea40b3..32ca30d 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/XIncludeTest.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/XIncludeTest.java @@ -23,6 +23,7 @@ package org.x4o.xml.test; +import org.x4o.xml.io.X4OReader; import org.x4o.xml.test.models.TestObjectChild; import org.x4o.xml.test.models.TestObjectParent; import org.x4o.xml.test.models.TestObjectRoot; @@ -40,16 +41,16 @@ public class XIncludeTest extends TestCase { public void testXInclude() throws Exception { - TestParser parser = new TestParser(); - parser.parseResource("tests/xinclude/include-base.xml"); - Object root = parser.getDriver().getElementLanguage().getRootElement().getElementObject(); + TestDriver driver = TestDriver.getInstance(); + X4OReader reader = driver.createReader(); + TestObjectRoot root = reader.readResource("tests/xinclude/include-base.xml"); assertNotNull(root); TestObjectRoot parentRoot = (TestObjectRoot)root; - if (parentRoot.testObjectParents.size()==0) { + if (parentRoot.getTestObjectParents().size()==0) { return; // FIXME: don't fail, as on jdk7 it 'sometimes' fails ... } - assertEquals(1,parentRoot.testObjectParents.size()); - TestObjectParent parent = parentRoot.testObjectParents.get(0); + assertEquals(1,parentRoot.getTestObjectParents().size()); + TestObjectParent parent = parentRoot.getTestObjectParents().get(0); TestObjectChild child = parent.testObjectChilds.get(0); assertEquals("include-child.xml",child.getName()); } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/element/InlinePropertiesElement.java b/x4o-core/src/test/java/org/x4o/xml/test/element/InlinePropertiesElement.java index 6506dbd..50fb383 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/element/InlinePropertiesElement.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/element/InlinePropertiesElement.java @@ -27,7 +27,7 @@ import java.io.StringWriter; import org.x4o.xml.element.AbstractElement; import org.x4o.xml.element.ElementException; -import org.x4o.xml.sax.XMLWriter; +import org.x4o.xml.io.sax.XMLWriter; /** * InlinePropertiesElement to test diff --git a/x4o-core/src/test/java/org/x4o/xml/test/models/TestObjectRoot.java b/x4o-core/src/test/java/org/x4o/xml/test/models/TestObjectRoot.java index 86560bd..1fdbb9e 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/models/TestObjectRoot.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/models/TestObjectRoot.java @@ -28,10 +28,10 @@ import java.util.List; public class TestObjectRoot { - public List testObjectChilds = new ArrayList(2); - public List testObjectParents = new ArrayList(2); - public List testBeans = new ArrayList(2); - public List testObjects = new ArrayList(2); + private List testObjectChilds = new ArrayList(2); + private List testObjectParents = new ArrayList(2); + private List testBeans = new ArrayList(2); + private List testObjects = new ArrayList(2); public void addChild(TestObjectChild c) { testObjectChilds.add(c); @@ -48,4 +48,34 @@ public class TestObjectRoot { public void addObject(Object c) { testObjects.add(c); } + + /** + * @return the testObjectChilds + */ + public List getTestObjectChilds() { + return testObjectChilds; + } + + /** + * @return the testObjectParents + */ + public List getTestObjectParents() { + return testObjectParents; + } + + /** + * @return the testBeans + */ + public List getTestBeans() { + return testBeans; + } + + /** + * @return the testObjects + */ + public List getTestObjects() { + return testObjects; + } + + } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator2.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator2.java index 9599ecb..563a40f 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator2.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator2.java @@ -29,8 +29,6 @@ import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JOptionPane; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; - /** * Accelerator2 test demo. * @@ -47,7 +45,7 @@ public class Accelerator2 { public Accelerator2(boolean render) throws Exception { if (render) { - swix.render( Accelerator2.DESCRIPTOR, SwiXmlVersion.VERSION_2 ).setVisible( true ); + swix.render( Accelerator2.DESCRIPTOR, SwiXmlDriver.LANGUAGE_VERSION_2 ).setVisible( true ); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3.java index c7215e6..c181e7b 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3.java @@ -23,8 +23,6 @@ package org.x4o.xml.test.swixml; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; - /** * Accelerator3 test demo. * @@ -38,7 +36,7 @@ public class Accelerator3 extends Accelerator2 { public Accelerator3(boolean render) throws Exception { super(false); if (render) { - swix.render( Accelerator3.DESCRIPTOR, SwiXmlVersion.VERSION_3 ).setVisible( true ); + swix.render( Accelerator3.DESCRIPTOR, SwiXmlDriver.LANGUAGE_VERSION_3 ).setVisible( true ); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3Test.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3Test.java index f54eba3..c8f34fb 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3Test.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/Accelerator3Test.java @@ -29,7 +29,7 @@ import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuItem; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; +import org.x4o.xml.io.X4OReader; import junit.framework.TestCase; @@ -42,10 +42,12 @@ import junit.framework.TestCase; public class Accelerator3Test extends TestCase { public void testSwingMenuAbout() throws Exception { - Accelerator3 ac3 = new Accelerator3(false); - SwiXmlParser parser = new SwiXmlParser(ac3.swix,SwiXmlVersion.VERSION_3); - parser.parseResource(Accelerator3.DESCRIPTOR); - Component root = parser.getRootComponent(); + Accelerator3 ac3 = new Accelerator3(false); + SwingEngine engine = new SwingEngine(ac3); + SwiXmlDriver driver = SwiXmlDriver.getInstance(); + X4OReader reader = driver.createReader(SwiXmlDriver.LANGUAGE_VERSION_3); + reader.addELBeanInstance(SwiXmlDriver.LANGUAGE_EL_SWING_ENGINE, engine); + Component root = reader.readResource(Accelerator3.DESCRIPTOR); assertNotNull(root); JFrame frame = (JFrame)root; assertTrue(frame.getJMenuBar().getMenuCount()>0); diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlActionConfigurator.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlActionConfigurator.java index 0d25424..2df3f64 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlActionConfigurator.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlActionConfigurator.java @@ -43,7 +43,7 @@ public class SwiXmlActionConfigurator extends AbstractElementConfigurator { if (actionName==null) { return; } - SwingEngine se = SwiXmlParser.getSwingEngine(element.getElementLanguage()); + SwingEngine se = SwiXmlDriver.getSwingEngine(element.getElementLanguage()); Action action = se.getUIActionByName(actionName); Object object = element.getElementObject(); if (object instanceof JMenuItem) { diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParser.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlDriver.java similarity index 64% rename from x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParser.java rename to x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlDriver.java index 65c222f..0beb3b5 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlParser.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwiXmlDriver.java @@ -27,8 +27,13 @@ import java.awt.Component; import javax.el.ValueExpression; -import org.x4o.xml.core.X4OParser; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; +import org.x4o.xml.core.config.DefaultX4OLanguage; +import org.x4o.xml.core.config.DefaultX4OLanguageConfiguration; +import org.x4o.xml.core.config.X4OLanguage; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; +import org.x4o.xml.core.phase.X4OPhaseManagerFactory; import org.x4o.xml.element.ElementLanguage; /** @@ -37,33 +42,36 @@ import org.x4o.xml.element.ElementLanguage; * @author Willem Cazander * @version 1.0 Aug 15, 2012 */ -public class SwiXmlParser extends X4OParser { +public class SwiXmlDriver extends X4ODriver { - public static final String LANGUAGE = "swixml"; - public static final String VERSION_2_NS_URI = "http://swixml.x4o.org/xml/ns/swixml-lang"; - public static final String SWING_ENGINE_EL_NAME = "swingEngine"; + public static final String LANGUAGE_NAME = "swixml"; + public static final String LANGUAGE_VERSION_2 = "2.0"; + public static final String LANGUAGE_VERSION_2_NSURI = "http://swixml.x4o.org/xml/ns/swixml-lang"; + public static final String LANGUAGE_VERSION_3 = "3.0"; + public static final String[] LANGUAGE_VERSIONS = new String[]{LANGUAGE_VERSION_2,LANGUAGE_VERSION_3}; + public static final String LANGUAGE_EL_SWING_ENGINE = "swingEngine"; - /** + /* * Protected constructor for write schema api. * @param xmlVersion The xml version. - */ - protected SwiXmlParser(SwiXmlVersion xmlVersion) { + + protected SwiXmlDriver(SwiXmlVersion xmlVersion) { // Create language by version - super(LANGUAGE,xmlVersion.getLanguageVersion()); + super(LANGUAGE_NAME,xmlVersion.getLanguageVersion()); // Sets empty namespace uri for version 2 xml documents if (SwiXmlVersion.VERSION_2.equals(xmlVersion)) { setProperty(X4OLanguagePropertyKeys.INPUT_EMPTY_NAMESPACE_URI, VERSION_2_NS_URI); } - } + }*/ - /** + /* * Creates an SwiXmlParser with an SwingEngine and a xml version. * @param engine The SwingEngine to parse for. * @param xmlVersion The xml language version to parse. - */ - public SwiXmlParser(SwingEngine engine,SwiXmlVersion xmlVersion) { + + public SwiXmlDriver(SwingEngine engine,SwiXmlVersion xmlVersion) { // Create language this(xmlVersion); @@ -75,15 +83,8 @@ public class SwiXmlParser extends X4OParser { // Add engine for callback addELBeanInstance(SWING_ENGINE_EL_NAME,engine); - } + }*/ - /** - * Returns after parsing the root component. - * @return Returns the root component. - */ - public Component getRootComponent() { - return (Component)getDriver().getElementLanguage().getRootElement().getElementObject(); - } /** * Helper for while parsing to get the SwingEngine. @@ -91,24 +92,28 @@ public class SwiXmlParser extends X4OParser { * @return Returns the SwingEngine for this elementLanguage. */ static public SwingEngine getSwingEngine(ElementLanguage elementLanguage) { - ValueExpression ee = elementLanguage.getExpressionFactory().createValueExpression(elementLanguage.getELContext(),"${"+SwiXmlParser.SWING_ENGINE_EL_NAME+"}",Object.class); + ValueExpression ee = elementLanguage.getExpressionFactory().createValueExpression(elementLanguage.getELContext(),"${"+SwiXmlDriver.LANGUAGE_EL_SWING_ENGINE+"}",Object.class); SwingEngine se = (SwingEngine)ee.getValue(elementLanguage.getELContext()); return se; } - /** - * SwiXmlVersion defines the xml language version to parse. - */ - public enum SwiXmlVersion { - VERSION_2("2.0"), - VERSION_3("3.0"); - - final private String languageVersion; - private SwiXmlVersion(String languageVersion) { - this.languageVersion=languageVersion; - } - public String getLanguageVersion() { - return languageVersion; - } + + static public SwiXmlDriver getInstance() { + return (SwiXmlDriver)X4ODriverManager.getX4ODriver(LANGUAGE_NAME); + } + + @Override + public String getLanguageName() { + return LANGUAGE_NAME; + } + + @Override + public String[] getLanguageVersions() { + return LANGUAGE_VERSIONS; + } + + @Override + public X4OLanguage buildLanguage(String version) { + return new DefaultX4OLanguage(new DefaultX4OLanguageConfiguration(),X4OPhaseManagerFactory.createDefaultX4OPhaseManager(),getLanguageName(),getLanguageVersionDefault()); } } diff --git a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwingEngine.java b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwingEngine.java index 36fd830..cfdc0dc 100644 --- a/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwingEngine.java +++ b/x4o-core/src/test/java/org/x4o/xml/test/swixml/SwingEngine.java @@ -28,7 +28,7 @@ import java.lang.reflect.Field; import javax.swing.Action; -import org.x4o.xml.test.swixml.SwiXmlParser.SwiXmlVersion; +import org.x4o.xml.io.X4OReader; /** * SwingEngine demo. @@ -69,14 +69,15 @@ public class SwingEngine { return null; } - public Component render(String resource,SwiXmlVersion xmlVersion) { - SwiXmlParser parser = new SwiXmlParser(this,xmlVersion); + public Component render(String resource,String languageVersion) { + SwiXmlDriver driver = SwiXmlDriver.getInstance(); + X4OReader reader = driver.createReader(languageVersion); + reader.addELBeanInstance(SwiXmlDriver.LANGUAGE_EL_SWING_ENGINE, this); try { - parser.parseResource(resource); + rootComponent = reader.readResource(resource); } catch (Exception e) { throw new RuntimeException(e); } - rootComponent = parser.getRootComponent(); return getRootComponent(); } diff --git a/x4o-core/src/test/resources/META-INF/x4o-drivers.xml b/x4o-core/src/test/resources/META-INF/x4o-drivers.xml new file mode 100644 index 0000000..efdf25d --- /dev/null +++ b/x4o-core/src/test/resources/META-INF/x4o-drivers.xml @@ -0,0 +1,33 @@ + + + + + + diff --git a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocGenerator.java b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocGenerator.java index 997ed97..1f3674b 100644 --- a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocGenerator.java +++ b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocGenerator.java @@ -58,7 +58,7 @@ public class EldDocGenerator { writer.writeOverviewNamespace(basePath, context); writer.writeOverviewTree(basePath, context); - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:context.getLanguage().getElementLanguageModules()) { writer.writeOverviewModule(basePath, mod); diff --git a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocHtmlWriter.java b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocHtmlWriter.java index 8d3a36a..f32f4c4 100644 --- a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocHtmlWriter.java +++ b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/EldDocHtmlWriter.java @@ -139,7 +139,7 @@ public class EldDocHtmlWriter { public void writeIndex(File basePath,ElementLanguage context) throws IOException { PrintWriter pw = createPrintWriter(basePath,"index.html"); try { - String title = context.getLanguageConfiguration().getLanguage()+" "+context.getLanguageConfiguration().getLanguageVersion()+" ELD"; + String title = context.getLanguage().getLanguageName()+" "+context.getLanguage().getLanguageVersion()+" ELD"; printHeader(pw,"Index ("+title+")",""); printPageIndexTitle(pw,title,null,null); @@ -149,7 +149,7 @@ public class EldDocHtmlWriter { int eleConfigs = 0; int elements = 0; int namespaces = 0; - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:context.getLanguage().getElementLanguageModules()) { attrHandlers += mod.getElementAttributeHandlers().size(); bindHandlers += mod.getElementBindingHandlers().size(); interFaces += mod.getElementInterfaces().size(); @@ -162,9 +162,9 @@ public class EldDocHtmlWriter { pw.print("

Welcome to the EldDocs

"); printTableStart(pw,"Language Stats"); - printTableRowSummary(pw,"Language:",""+context.getLanguageConfiguration().getLanguage()); - printTableRowSummary(pw,"LanguageVersion:",""+context.getLanguageConfiguration().getLanguageVersion()); - printTableRowSummary(pw,"Modules:",""+context.getElementLanguageModules().size()); + printTableRowSummary(pw,"Language:",""+context.getLanguage().getLanguageName()); + printTableRowSummary(pw,"LanguageVersion:",""+context.getLanguage().getLanguageVersion()); + printTableRowSummary(pw,"Modules:",""+context.getLanguage().getElementLanguageModules().size()); printTableRowSummary(pw,"Namespaces:",""+namespaces); printTableRowSummary(pw,"Elements:",""+elements); printTableRowSummary(pw,"ElementInterfaces:",""+interFaces); @@ -184,11 +184,11 @@ public class EldDocHtmlWriter { public void writeOverviewModule(File basePath,ElementLanguage context) throws IOException { PrintWriter pw = createPrintWriter(basePath,"module-overview.html"); try { - String title = context.getLanguageConfiguration().getLanguage()+" "+context.getLanguageConfiguration().getLanguageVersion()+" ELD"; + String title = context.getLanguage().getLanguageName()+" "+context.getLanguage().getLanguageVersion()+" ELD"; printHeader(pw,"Overview Modules ("+title+")",""); printPageIndexTitle(pw,title,null,null); printTableStart(pw,"Modules"); - List mods = context.getElementLanguageModules(); + List mods = context.getLanguage().getElementLanguageModules(); Collections.sort(mods,new ElementLanguageModuleComparator()); for (ElementLanguageModule mod:mods) { printTableRowOverview(pw,toSafeUri(mod.getId())+"/index.html",mod.getId(),mod.getName()); @@ -206,10 +206,10 @@ public class EldDocHtmlWriter { PrintWriter pw = createPrintWriter(basePath,"namespace-overview.html"); String pathPrefix = ""; try { - String title = context.getLanguageConfiguration().getLanguage()+" "+context.getLanguageConfiguration().getLanguageVersion()+" ELD"; + String title = context.getLanguage().getLanguageName()+" "+context.getLanguage().getLanguageVersion()+" ELD"; printHeader(pw,"Overview Namespace("+title+")",pathPrefix); printPageIndexTitle(pw,title,null,null); - List mods = context.getElementLanguageModules(); + List mods = context.getLanguage().getElementLanguageModules(); Collections.sort(mods,new ElementLanguageModuleComparator()); for (ElementLanguageModule mod:mods) { printNamespaces(pw,mod.getElementNamespaceContexts(),pathPrefix,mod); @@ -226,12 +226,12 @@ public class EldDocHtmlWriter { PrintWriter pw = createPrintWriter(basePath,"tree-overview.html"); String pathPrefix = ""; try { - String title = context.getLanguageConfiguration().getLanguage()+" "+context.getLanguageConfiguration().getLanguageVersion()+" ELD"; + String title = context.getLanguage().getLanguageName()+" "+context.getLanguage().getLanguageVersion()+" ELD"; printHeader(pw,"Overview Tree ("+title+")",pathPrefix); printPageIndexTitle(pw,title,null,null); List rootNodes = new ArrayList(3); - for (ElementLanguageModule mod:context.getElementLanguageModules()) { + for (ElementLanguageModule mod:context.getLanguage().getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { if (ns.getLanguageRoot()!=null && ns.getLanguageRoot()) { // found language root elements. @@ -298,7 +298,7 @@ public class EldDocHtmlWriter { if (node.indent>20) { return result; // hard fail limit } - for (ElementLanguageModule mod:node.context.getElementLanguageModules()) { + for (ElementLanguageModule mod:node.context.getLanguage().getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { for (ElementClass ec:ns.getElementClasses()) { TreeNode n=null; @@ -316,7 +316,7 @@ public class EldDocHtmlWriter { continue; } // Check interfaces of parent , and see if child tag is there. - for (ElementInterface ei:node.context.findElementInterfaces(ec.getObjectClass())) { + for (ElementInterface ei:node.context.getLanguage().findElementInterfaces(ec.getObjectClass())) { List eiTags = ei.getElementParents(node.namespace.getUri()); if (eiTags!=null && eiTags.contains(node.elementClass.getTag())) { n = new TreeNode(); @@ -333,7 +333,7 @@ public class EldDocHtmlWriter { if (node.elementClass.getObjectClass()==null) { continue; } - List binds = node.context.findElementBindingHandlers(node.elementClass.getObjectClass(), ec.getObjectClass()); + List binds = node.context.getLanguage().findElementBindingHandlers(node.elementClass.getObjectClass(), ec.getObjectClass()); if (binds.isEmpty()==false) { n = new TreeNode(); n.context=node.context; @@ -370,7 +370,7 @@ public class EldDocHtmlWriter { private List findParents(TreeNode node) { List result = new ArrayList(10); TreeNode n=null; - for (ElementLanguageModule mod:node.context.getElementLanguageModules()) { + for (ElementLanguageModule mod:node.context.getLanguage().getElementLanguageModules()) { for (ElementNamespaceContext ns:mod.getElementNamespaceContexts()) { List tags = node.elementClass.getElementParents(ns.getUri()); @@ -392,7 +392,7 @@ public class EldDocHtmlWriter { // Check interfaces of parent , and see if child tag is there. if (node.elementClass.getObjectClass()!=null) { - for (ElementInterface ei:node.context.findElementInterfaces(node.elementClass.getObjectClass())) { + for (ElementInterface ei:node.context.getLanguage().findElementInterfaces(node.elementClass.getObjectClass())) { List eiTags = ei.getElementParents(ns.getUri()); if (eiTags!=null && eiTags.contains(ec.getTag())) { n = new TreeNode(); @@ -413,7 +413,7 @@ public class EldDocHtmlWriter { if (node.elementClass.getObjectClass()==null) { continue; } - List binds = node.context.findElementBindingHandlers(ec.getObjectClass(),node.elementClass.getObjectClass()); + List binds = node.context.getLanguage().findElementBindingHandlers(ec.getObjectClass(),node.elementClass.getObjectClass()); if (binds.isEmpty()==false) { n = new TreeNode(); n.context=node.context; diff --git a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4OLanguageEldDocWriter.java b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4ODocWriterExecutor.java similarity index 61% rename from x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4OLanguageEldDocWriter.java rename to x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4ODocWriterExecutor.java index bdfd63e..6d1869f 100644 --- a/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4OLanguageEldDocWriter.java +++ b/x4o-elddoc/src/main/java/org/x4o/xml/eld/doc/X4ODocWriterExecutor.java @@ -28,9 +28,8 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import org.x4o.xml.core.X4OParserSupport; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.core.config.X4OLanguageClassLoader; +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; import org.x4o.xml.element.ElementLanguage; import org.x4o.xml.element.ElementException; @@ -40,21 +39,21 @@ import org.x4o.xml.element.ElementException; * @author Willem Cazander * @version 1.0 Aug 22, 2012 */ -public class X4OLanguageEldDocWriter { +public class X4ODocWriterExecutor { - private Class languageParserSupport = null; + private String language = null; + private String languageVersion = null; private File basePath; - @SuppressWarnings("unchecked") static public void main(String argu[]) { - X4OLanguageEldDocWriter languageSchema = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor languageSchema = new X4ODocWriterExecutor(); List arguList = Arrays.asList(argu); Iterator arguIterator = arguList.iterator(); while (arguIterator.hasNext()) { String arg = arguIterator.next(); - if ("-path".equals(arg)) { + if ("-path".equals(arg) || "-p".equals(arg)) { if (arguIterator.hasNext()==false) { - System.out.println("No argument for -path given."); + System.out.println("No argument for "+arg+" given."); System.exit(1); return; } @@ -67,26 +66,20 @@ public class X4OLanguageEldDocWriter { languageSchema.setBasePath(schemaBasePath); continue; } - if ("-class".equals(arg)) { + if ("-language".equals(arg) || "-l".equals(arg)) { if (arguIterator.hasNext()==false) { - System.out.println("No argument for -class given."); - System.exit(1); - return; - } - String apiClass = arguIterator.next(); - try { - languageSchema.setLanguageParserSupport((Class) X4OLanguageClassLoader.loadClass(apiClass)); - } catch (ClassNotFoundException e) { - System.out.println("Schema api class is not found: "+apiClass); + System.out.println("No argument for "+arg+" given."); System.exit(1); return; } + String languageName = arguIterator.next(); + languageSchema.setLanguage(languageName); continue; } } try { languageSchema.execute(); - } catch (X4OParserSupportException e) { + } catch (ElementException e) { System.out.println("Error while schema writing: "+e.getMessage()); e.printStackTrace(); System.exit(1); @@ -94,37 +87,41 @@ public class X4OLanguageEldDocWriter { } } - public void execute() throws X4OParserSupportException { - try { - // Load the support language context - X4OParserSupport languageSupport = (X4OParserSupport)getLanguageParserSupport().newInstance(); - ElementLanguage context = languageSupport.loadElementLanguageSupport(); + public void execute() throws ElementException { + X4ODriver driver = X4ODriverManager.getX4ODriver(getLanguage()); + ElementLanguage context = driver.createLanguageContext(getLanguageVersion()); - // Start doc generator - EldDocGenerator generator = new EldDocGenerator(context); - generator.writeDoc(getBasePath()); - - } catch (InstantiationException e) { - throw new X4OParserSupportException(e); - } catch (IllegalAccessException e) { - throw new X4OParserSupportException(e); - } catch (ElementException e) { - throw new X4OParserSupportException(e); - } + // Start doc generator + EldDocGenerator generator = new EldDocGenerator(context); + generator.writeDoc(getBasePath()); } /** - * @return the languageParserSupport + * @return the languageVersion */ - public Class getLanguageParserSupport() { - return languageParserSupport; + public String getLanguageVersion() { + return languageVersion; } /** - * @param languageParserSupport the languageParserSupport to set + * @param languageVersion the languageVersion to set */ - public void setLanguageParserSupport(Class languageParserSupport) { - this.languageParserSupport = languageParserSupport; + public void setLanguageVersion(String languageVersion) { + this.languageVersion = languageVersion; + } + + /** + * @return the language + */ + public String getLanguage() { + return language; + } + + /** + * @param language the language to set + */ + public void setLanguage(String language) { + this.language = language; } /** diff --git a/x4o-elddoc/src/test/java/org/x4o/xml/eld/doc/EldDocTest.java b/x4o-elddoc/src/test/java/org/x4o/xml/eld/doc/EldDocTest.java index 7c9465e..7332276 100644 --- a/x4o-elddoc/src/test/java/org/x4o/xml/eld/doc/EldDocTest.java +++ b/x4o-elddoc/src/test/java/org/x4o/xml/eld/doc/EldDocTest.java @@ -25,11 +25,11 @@ package org.x4o.xml.eld.doc; import java.io.File; -import org.x4o.xml.eld.EldParserSupport; -import org.x4o.xml.eld.EldParserSupportCore; -import org.x4o.xml.test.TestParserSupport; -import org.x4o.xml.test.swixml.SwiXmlParserSupport2; -import org.x4o.xml.test.swixml.SwiXmlParserSupport3; +import org.x4o.xml.eld.CelDriver; +import org.x4o.xml.eld.EldDriver; +import org.x4o.xml.test.TestDriver; +import org.x4o.xml.test.swixml.SwiXmlDriver; + import junit.framework.TestCase; @@ -54,42 +54,44 @@ public class EldDocTest extends TestCase { } public void testCelDoc() throws Exception { - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(getTempPath("junit-cel")); - writer.setLanguageParserSupport(EldParserSupportCore.class); + writer.setLanguage(CelDriver.LANGUAGE_NAME); writer.execute(); } public void testEldDoc() throws Exception { - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(getTempPath("junit-eld")); - writer.setLanguageParserSupport(EldParserSupport.class); + writer.setLanguage(EldDriver.LANGUAGE_NAME); writer.execute(); } public void testUnitDoc() throws Exception { - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(getTempPath("junit-test")); - writer.setLanguageParserSupport(TestParserSupport.class); + writer.setLanguage(TestDriver.LANGUAGE_NAME); writer.execute(); } public void testSwiXml2Doc() throws Exception { - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(getTempPath("junit-swixml2")); - writer.setLanguageParserSupport(SwiXmlParserSupport2.class); + writer.setLanguage(SwiXmlDriver.LANGUAGE_NAME); + writer.setLanguageVersion(SwiXmlDriver.LANGUAGE_VERSION_2); writer.execute(); } public void testSwiXml3Doc() throws Exception { - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(getTempPath("junit-swixml3")); - writer.setLanguageParserSupport(SwiXmlParserSupport3.class); + writer.setLanguage(SwiXmlDriver.LANGUAGE_NAME); + writer.setLanguageVersion(SwiXmlDriver.LANGUAGE_VERSION_3); writer.execute(); } public void testEldDocMain() throws Exception { - X4OLanguageEldDocWriter.main(new String[] {"-path",getTempPath("junit-test-main").getAbsolutePath(),"-class",EldParserSupport.class.getName()}); + X4ODocWriterExecutor.main(new String[] {"-p",getTempPath("junit-test-main").getAbsolutePath(),"-l",EldDriver.LANGUAGE_NAME}); } } diff --git a/x4o-meta/src/main/java/org/x4o/xml/meta/MetaLanguageSiblingLoader.java b/x4o-meta/src/main/java/org/x4o/xml/meta/MetaLanguageSiblingLoader.java index 6cf4c26..45703b1 100644 --- a/x4o-meta/src/main/java/org/x4o/xml/meta/MetaLanguageSiblingLoader.java +++ b/x4o-meta/src/main/java/org/x4o/xml/meta/MetaLanguageSiblingLoader.java @@ -25,7 +25,7 @@ package org.x4o.xml.meta; import org.x4o.xml.core.config.X4OLanguageLoader; import org.x4o.xml.core.config.X4OLanguageLoaderException; -import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.core.config.X4OLanguageLocal; import org.x4o.xml.element.ElementLanguageModule; import org.x4o.xml.element.ElementLanguageModuleLoaderException; import org.x4o.xml.element.ElementLanguageModuleLoaderSibling; @@ -46,12 +46,12 @@ public class MetaLanguageSiblingLoader implements ElementLanguageModuleLoaderSib /** * Loads an ElementLanguageModule. - * @param elementLanguage The ElementLanguage to load for. + * @param language The ElementLanguage to load for. * @param elementLanguageModule The ElementLanguageModule to load into. * @throws ElementLanguageModuleLoaderException Is thrown when meta language could not be loaded. * @see org.x4o.xml.element.ElementLanguageModuleLoader#loadLanguageModule(org.x4o.xml.element.ElementLanguage, org.x4o.xml.element.ElementLanguageModule) */ - public void loadLanguageModule(ElementLanguage elementLanguage,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { + public void loadLanguageModule(X4OLanguageLocal languageLocal,ElementLanguageModule elementLanguageModule) throws ElementLanguageModuleLoaderException { elementLanguageModule.setId(META_LANGUAGE); elementLanguageModule.setName(META_LANGUAGE); elementLanguageModule.setProviderName(MetaLanguageSiblingLoader.class.getSimpleName()); @@ -65,9 +65,9 @@ public class MetaLanguageSiblingLoader implements ElementLanguageModuleLoaderSib * @throws X4OLanguageLoaderException * @see org.x4o.xml.element.ElementLanguageModuleLoaderSibling#loadLanguageSibling(org.x4o.xml.element.ElementLanguage, org.x4o.xml.core.config.X4OLanguageLoader) */ - public void loadLanguageSibling(ElementLanguage elementLanguage,X4OLanguageLoader loader) throws X4OLanguageLoaderException { + public void loadLanguageSibling(X4OLanguageLocal languageLocal,X4OLanguageLoader loader) throws X4OLanguageLoaderException { // Load the meta language. - loader.loadLanguage(elementLanguage, META_LANGUAGE, META_LANGUAGE_VERSION); + loader.loadLanguage(languageLocal, META_LANGUAGE, META_LANGUAGE_VERSION); } } diff --git a/x4o-meta/src/test/java/org/x4o/xml/meta/ReferenceStoreTest.java b/x4o-meta/src/test/java/org/x4o/xml/meta/ReferenceStoreTest.java index 0cc76f0..33ccefd 100644 --- a/x4o-meta/src/test/java/org/x4o/xml/meta/ReferenceStoreTest.java +++ b/x4o-meta/src/test/java/org/x4o/xml/meta/ReferenceStoreTest.java @@ -26,7 +26,9 @@ package org.x4o.xml.meta; import java.util.Date; import org.x4o.xml.core.config.X4OLanguagePropertyKeys; -import org.x4o.xml.meta.test.MTestParser; +import org.x4o.xml.element.ElementLanguage; +import org.x4o.xml.io.X4OReaderContext; +import org.x4o.xml.meta.test.MTestDriver; import junit.framework.TestCase; @@ -39,38 +41,44 @@ import junit.framework.TestCase; public class ReferenceStoreTest extends TestCase { public void testMetaGeneric() throws Exception { - MTestParser parser = new MTestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + ElementLanguage context = null; + MTestDriver driver = new MTestDriver(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); try { - parser.parseResource("tests/meta-generic.xml"); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); + context = reader.readResourceContext("tests/meta-generic.xml"); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } public void testLoadClass() throws Exception { - MTestParser parser = new MTestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + ElementLanguage context = null; + MTestDriver driver = new MTestDriver(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); try { - parser.parseResource("tests/reference/store-ref.xml"); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); + context = reader.readResourceContext("tests/reference/store-ref.xml"); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } public void testStoreRef() throws Exception { - MTestParser parser = new MTestParser(); - parser.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); + ElementLanguage context = null; + MTestDriver driver = new MTestDriver(); + X4OReaderContext reader = driver.createReaderContext(); + reader.setProperty(X4OLanguagePropertyKeys.PHASE_SKIP_RELEASE, true); try { - parser.parseResource("tests/reference/store-ref.xml"); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(1).getElementObject().getClass().getName()); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(2).getElementObject().getClass().getName()); - assertEquals(Date.class.getName(),parser.getElementLanguage().getRootElement().getChilderen().get(3).getElementObject().getClass().getName()); + context = reader.readResourceContext("tests/reference/store-ref.xml"); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(0).getElementObject().getClass().getName()); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(1).getElementObject().getClass().getName()); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(2).getElementObject().getClass().getName()); + assertEquals(Date.class.getName(),context.getRootElement().getChilderen().get(3).getElementObject().getClass().getName()); } finally { - parser.doReleasePhaseManual(); + reader.releaseContext(context); } } diff --git a/x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestDriver.java b/x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestDriver.java new file mode 100644 index 0000000..2405774 --- /dev/null +++ b/x4o-meta/src/test/java/org/x4o/xml/meta/test/MTestDriver.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2004-2012, Willem Cazander + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided + * that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this list of conditions and the + * following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and + * the following disclaimer in the documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package org.x4o.xml.meta.test; + +import org.x4o.xml.X4ODriver; +import org.x4o.xml.X4ODriverManager; +import org.x4o.xml.core.config.DefaultX4OLanguage; +import org.x4o.xml.core.config.DefaultX4OLanguageConfiguration; +import org.x4o.xml.core.config.X4OLanguage; +import org.x4o.xml.core.phase.X4OPhaseManagerFactory; +import org.x4o.xml.io.X4OReaderContext; +import org.x4o.xml.io.X4OWriterContext; + +public class MTestDriver extends X4ODriver { + + public static final String LANGUAGE_NAME = "mtest"; + public static final String[] LANGUAGE_VERSIONS = new String[]{X4ODriver.DEFAULT_LANGUAGE_VERSION}; + + @Override + public String getLanguageName() { + return LANGUAGE_NAME; + } + + @Override + public String[] getLanguageVersions() { + return LANGUAGE_VERSIONS; + } + + @Override + public X4OLanguage buildLanguage(String version) { + return new DefaultX4OLanguage(new DefaultX4OLanguageConfiguration(),X4OPhaseManagerFactory.createDefaultX4OPhaseManager(),getLanguageName(),getLanguageVersionDefault()); + } + + static public MTestDriver getInstance() { + return (MTestDriver)X4ODriverManager.getX4ODriver(LANGUAGE_NAME); + } + + public X4OReaderContext createReaderContext() { + return (X4OReaderContext)super.createReader(); + } + + public X4OWriterContext createWriterContext() { + return (X4OWriterContext)super.createWriter(); + } +} diff --git a/x4o-plugin/x4o-plugin-ant-elddoc/src/main/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTask.java b/x4o-plugin/x4o-plugin-ant-elddoc/src/main/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTask.java index baf4fba..de90733 100644 --- a/x4o-plugin/x4o-plugin-ant-elddoc/src/main/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTask.java +++ b/x4o-plugin/x4o-plugin-ant-elddoc/src/main/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTask.java @@ -28,9 +28,9 @@ import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.core.config.X4OLanguageClassLoader; -import org.x4o.xml.eld.doc.X4OLanguageEldDocWriter; + +import org.x4o.xml.eld.doc.X4ODocWriterExecutor; +import org.x4o.xml.element.ElementException; /** * EldDocWriterTask creates schema for language. @@ -40,7 +40,7 @@ import org.x4o.xml.eld.doc.X4OLanguageEldDocWriter; */ public class EldDocWriterTask extends Task { - private String supportclass = null; + private String language = null; private String destdir = null; private boolean verbose = false; private boolean failonerror = true; @@ -63,16 +63,16 @@ public class EldDocWriterTask extends Task { } private void executeTask() throws BuildException { - if (getSupportclass()==null) { - throw new BuildException("supportclass attribute is not set."); + if (getLanguage()==null) { + throw new BuildException("language attribute is not set."); } if (getDestdir()==null) { throw new BuildException("basePath attribute is not set."); } if (isVerbose()) { log("Execute task from: "+getLocation()); + log("language:"+getLanguage()); log("destdir:"+getDestdir()); - log("supportclass:"+getSupportclass()); log("verbose:"+isVerbose()); log("failonerror:"+isFailonerror()); } @@ -80,17 +80,11 @@ public class EldDocWriterTask extends Task { if (basePathFile.exists()==false) { throw new BuildException("destdir does not exists: "+basePathFile); } - Class parserSupport = null; - try { - parserSupport = X4OLanguageClassLoader.loadClass(getSupportclass()); - } catch (ClassNotFoundException e) { - throw new BuildException("Could not load class: "+getSupportclass(),e); - } // Config and start schema writer - X4OLanguageEldDocWriter writer = new X4OLanguageEldDocWriter(); + X4ODocWriterExecutor writer = new X4ODocWriterExecutor(); writer.setBasePath(basePathFile); - writer.setLanguageParserSupport(parserSupport); + writer.setLanguage(getLanguage()); try { if (isVerbose()) { log("Starting writing."); @@ -99,23 +93,23 @@ public class EldDocWriterTask extends Task { writer.execute(); long stopTime = System.currentTimeMillis(); log("Done writing elddoc in "+(stopTime-startTime)+" ms."); - } catch (X4OParserSupportException e) { + } catch (ElementException e) { throw new BuildException(e); } } - + /** - * @return the supportclass + * @return the language */ - public String getSupportclass() { - return supportclass; + public String getLanguage() { + return language; } /** - * @param supportclass the supportclass to set + * @param language the language to set */ - public void setSupportclass(String supportclass) { - this.supportclass = supportclass; + public void setLanguage(String language) { + this.language = language; } /** diff --git a/x4o-plugin/x4o-plugin-ant-elddoc/src/test/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTaskTest.java b/x4o-plugin/x4o-plugin-ant-elddoc/src/test/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTaskTest.java index 44a4448..c0e3f2c 100644 --- a/x4o-plugin/x4o-plugin-ant-elddoc/src/test/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTaskTest.java +++ b/x4o-plugin/x4o-plugin-ant-elddoc/src/test/java/org/x4o/plugin/ant/eld/doc/EldDocWriterTaskTest.java @@ -61,27 +61,20 @@ public class EldDocWriterTaskTest extends BuildFileTest { executeTarget("test-elddoc-cel-verbose"); assertLogContaining("verbose:"); } - + + public void testFailAllMissing() { + expectBuildException("test-fail-all", "Should get exception with no attributes."); + } public void testFailBasePath() { expectBuildException("test-fail-destdir", "Should get exception id destdir is not set."); } public void testFailBasePathError() { expectBuildException("test-fail-destdir-error", "Should get exception id destdir does not exists."); } - public void testFailSupportClass() { - expectBuildException("test-fail-supportclass", "Should get exception id supportclass is not set."); + public void testFailLanguage() { + expectBuildException("test-fail-language", "Should get exception id language is not set."); } - public void testFailSupportClassError() { - expectBuildException("test-fail-supportclass-error", "Should get exception id supportclass throws error."); - } - public void testFailAllMissing() { - expectBuildException("test-fail-all", "Should get exception with no attributes."); - } - public void testFailClassError() { - expectBuildException("test-fail-class-error", "No build exception while class is missing."); - } - public void testFailClassErrorNo() { - executeTarget("test-fail-class-error-no"); - assertLogContaining("Could not load class:"); + public void testFailLanguageError() { + expectBuildException("test-fail-language-error", "Should get exception id language throws error."); } } diff --git a/x4o-plugin/x4o-plugin-ant-elddoc/src/test/resources/tests/ant-elddoc-task.xml b/x4o-plugin/x4o-plugin-ant-elddoc/src/test/resources/tests/ant-elddoc-task.xml index e7c0b8f..8ef58d2 100644 --- a/x4o-plugin/x4o-plugin-ant-elddoc/src/test/resources/tests/ant-elddoc-task.xml +++ b/x4o-plugin/x4o-plugin-ant-elddoc/src/test/resources/tests/ant-elddoc-task.xml @@ -37,7 +37,7 @@ @@ -46,7 +46,7 @@ @@ -54,7 +54,7 @@ @@ -62,22 +62,16 @@ - + - + - + - - - - - - - - + + \ No newline at end of file diff --git a/x4o-plugin/x4o-plugin-ant-schema/src/main/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTask.java b/x4o-plugin/x4o-plugin-ant-schema/src/main/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTask.java index d734b11..addcafa 100644 --- a/x4o-plugin/x4o-plugin-ant-schema/src/main/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTask.java +++ b/x4o-plugin/x4o-plugin-ant-schema/src/main/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTask.java @@ -28,9 +28,8 @@ import java.io.File; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; -import org.x4o.xml.core.X4OParserSupportException; -import org.x4o.xml.core.config.X4OLanguageClassLoader; -import org.x4o.xml.eld.xsd.X4OLanguageEldXsdWriter; +import org.x4o.xml.eld.xsd.X4OSchemaWriterExecutor; +import org.x4o.xml.element.ElementException; /** * SchemaWriterTask creates schema for language. @@ -40,8 +39,8 @@ import org.x4o.xml.eld.xsd.X4OLanguageEldXsdWriter; */ public class EldXsdWriterTask extends Task { + private String language = null; private String nsuri = null; - private String supportclass = null; private String destdir = null; private boolean verbose = false; private boolean failonerror = true; @@ -64,35 +63,29 @@ public class EldXsdWriterTask extends Task { } private void executeTask() throws BuildException { - if (getSupportclass()==null) { - throw new BuildException("supportclass attribute is not set."); + if (getLanguage()==null) { + throw new BuildException("langauge attribute is not set."); } if (getDestdir()==null) { throw new BuildException("destdir attribute is not set."); } if (isVerbose()) { log("Execute task from: "+getLocation()); - log("destdir:"+getDestdir()); - log("supportclass:"+getSupportclass()); - log("nsuri:"+getNsuri()); - log("verbose:"+isVerbose()); - log("failonerror:"+isFailonerror()); + log("language: "+getLanguage()); + log("destdir: "+getDestdir()); + log("nsuri: "+getNsuri()); + log("verbose: "+isVerbose()); + log("failonerror: "+isFailonerror()); } File basePathFile = new File(getDestdir()); if (basePathFile.exists()==false) { throw new BuildException("destdir does not exists: "+basePathFile); } - Class parserSupport = null; - try { - parserSupport = X4OLanguageClassLoader.loadClass(getSupportclass()); - } catch (ClassNotFoundException e) { - throw new BuildException("Could not load class: "+getSupportclass(),e); - } - + // Config and start schema writer - X4OLanguageEldXsdWriter writer = new X4OLanguageEldXsdWriter(); + X4OSchemaWriterExecutor writer = new X4OSchemaWriterExecutor(); writer.setBasePath(basePathFile); - writer.setLanguageParserSupport(parserSupport); + writer.setLanguage(getLanguage()); writer.setLanguageNamespaceUri(getNsuri()); try { if (isVerbose()) { @@ -102,7 +95,11 @@ public class EldXsdWriterTask extends Task { writer.execute(); long stopTime = System.currentTimeMillis(); log("Done writing schema in "+(stopTime-startTime)+" ms."); - } catch (X4OParserSupportException e) { + } catch (ElementException e) { + throw new BuildException(e); + } catch (InstantiationException e) { + throw new BuildException(e); + } catch (IllegalAccessException e) { throw new BuildException(e); } } @@ -120,19 +117,19 @@ public class EldXsdWriterTask extends Task { public void setNsuri(String nsuri) { this.nsuri = nsuri; } - + /** - * @return the supportclass + * @return the language */ - public String getSupportclass() { - return supportclass; + public String getLanguage() { + return language; } /** - * @param supportclass the supportclass to set + * @param language the language to set */ - public void setSupportclass(String supportclass) { - this.supportclass = supportclass; + public void setLanguage(String language) { + this.language = language; } /** diff --git a/x4o-plugin/x4o-plugin-ant-schema/src/test/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTaskTest.java b/x4o-plugin/x4o-plugin-ant-schema/src/test/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTaskTest.java index df79339..9343705 100644 --- a/x4o-plugin/x4o-plugin-ant-schema/src/test/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTaskTest.java +++ b/x4o-plugin/x4o-plugin-ant-schema/src/test/java/org/x4o/plugin/ant/eld/xsd/EldXsdWriterTaskTest.java @@ -43,7 +43,7 @@ public class EldXsdWriterTaskTest extends BuildFileTest { executeTarget("test-cel-schema-full"); File testDir = new File("target/test-schemas/cel-full"); int files = testDir.listFiles().length; - assertEquals("Should created only two files", 2, files); + assertEquals("Should created only 3 files", 3, files); } public void testCelSchemaSingle() { @@ -61,27 +61,20 @@ public class EldXsdWriterTaskTest extends BuildFileTest { executeTarget("test-cel-schema-verbose"); assertLogContaining("verbose:"); } - + + public void testFailAllMissing() { + expectBuildException("test-fail-all", "Should get exception if no attributes are set."); + } public void testFailBasePath() { expectBuildException("test-fail-destdir", "Should get exception id destdir is not set."); } public void testFailBasePathError() { expectBuildException("test-fail-destdir-error", "Should get exception id destdir does not exists."); } - public void testFailSupportClass() { - expectBuildException("test-fail-supportclass", "Should get exception id supportclass is not set."); + public void testFailLanguage() { + expectBuildException("test-fail-language", "Should get exception id language is not set."); } - public void testFailSupportClassError() { - expectBuildException("test-fail-supportclass-error", "Should get exception id supportclass throws error."); - } - public void testFailAllMissing() { - expectBuildException("test-fail-all", "Should get exception if no attributes are set."); - } - public void testFailClassError() { - expectBuildException("test-fail-class-error", "No build exception while class is missing."); - } - public void testFailClassErrorNo() { - executeTarget("test-fail-class-error-no"); - assertLogContaining("Could not load class:"); + public void testFailLanguageError() { + expectBuildException("test-fail-language-error", "Should get exception id language throws error."); } } diff --git a/x4o-plugin/x4o-plugin-ant-schema/src/test/resources/tests/ant-schema-task.xml b/x4o-plugin/x4o-plugin-ant-schema/src/test/resources/tests/ant-schema-task.xml index 29c874d..e8ee6ed 100644 --- a/x4o-plugin/x4o-plugin-ant-schema/src/test/resources/tests/ant-schema-task.xml +++ b/x4o-plugin/x4o-plugin-ant-schema/src/test/resources/tests/ant-schema-task.xml @@ -37,7 +37,7 @@ @@ -45,7 +45,7 @@ @@ -55,7 +55,7 @@ @@ -64,22 +64,16 @@ - + - + - + - - - - - - - - + + \ No newline at end of file