From: luukkainen Date: Tue, 24 Jan 2017 12:25:59 +0000 (+0000) Subject: Initial support for XML export (order of Elements is not kept) X-Git-Tag: v1.31.0~49 X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=commitdiff_plain;h=dd3b2c7ecd5f4b60734f2602b16637aa8be2a263;p=simantics%2Finterop.git Initial support for XML export (order of Elements is not kept) Ability to rename Elements refs #6985 git-svn-id: https://www.simantics.org/svn/simantics/interoperability/trunk@33434 ac1ea38d-2e2b-0410-8846-a27921b304fc --- diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/AbstractExporter.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/AbstractExporter.java new file mode 100644 index 0000000..14a3fca --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/AbstractExporter.java @@ -0,0 +1,79 @@ +package org.simantics.xml.sax.base; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Session; +import org.simantics.db.common.request.ReadRequest; +import org.simantics.db.exception.DatabaseException; +import org.simantics.message.ILogger; +import org.simantics.message.MessageService; + +public class AbstractExporter { + + private Session session; + private File file; + private ILogger logger; + private Resource root; + private XMLWriter xmlWriter; + + public AbstractExporter(Session session, File file , Resource root, XMLWriter xmlWriter) { + this.session = session; + this.file = file; + this.root = root; + this.xmlWriter = xmlWriter; + } + + public AbstractExporter(Session session, File file , Resource root) { + this.session = session; + this.file = file; + this.root = root; + } + + public void setXmlWriter(XMLWriter xmlWriter) { + this.xmlWriter = xmlWriter; + } + + public void doExport() throws DatabaseException { + doExport(MessageService.getDefault()); + } + + public void doExport(ILogger logger) throws DatabaseException { + ExportRequest req = new ExportRequest(); + session.syncRequest(req); + } + + + private class ExportRequest extends ReadRequest { + @Override + public void run(ReadGraph graph) throws DatabaseException { + XMLStreamWriter writer = null; + try { + XMLOutputFactory output = XMLOutputFactory.newInstance(); + writer = output.createXMLStreamWriter(new FileOutputStream(file),"UTF-8"); + writer.writeStartDocument("UTF-8", "1.0"); + xmlWriter.write(root, writer); + + writer.writeEndDocument(); + writer.close(); + } catch (IOException|XMLStreamException e) { + try { + writer.close(); + } catch (XMLStreamException err) { + + } + throw new DatabaseException(e); + } + + + } + } + +} diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/IDReferenceParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/IDReferenceParser.java index fb74fd3..abaf7f2 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/IDReferenceParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/IDReferenceParser.java @@ -7,6 +7,6 @@ import org.simantics.db.exception.DatabaseException; public interface IDReferenceParser extends XMLElementParser{ - public boolean connectReferences(WriteGraph graph, Element element, Map map) throws DatabaseException; + public boolean connectReferences(WriteGraph graph, ParserElement element, Map map) throws DatabaseException; } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/Element.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ParserElement.java similarity index 83% rename from org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/Element.java rename to org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ParserElement.java index 62f1597..e3298e3 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/Element.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ParserElement.java @@ -8,7 +8,7 @@ import java.util.Map; import org.simantics.db.Resource; import org.xml.sax.Attributes; -public class Element implements Serializable { +public class ParserElement implements Serializable { private static final long serialVersionUID = -5207502156942818875L; String uri; String localName; @@ -18,7 +18,7 @@ public class Element implements Serializable { XMLElementParser elementParser; XMLParser xmlParser; - public Element(String uri, String localName, String qName, Attributes attributes) { + public ParserElement(String uri, String localName, String qName, Attributes attributes) { this.uri = uri; this.localName = localName; this.qName = qName; @@ -27,7 +27,7 @@ public class Element implements Serializable { } } - public Element(String uri, String localName, String qName, Collection attributes) { + public ParserElement(String uri, String localName, String qName, Collection attributes) { this.uri = uri; this.localName = localName; this.qName = qName; diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/UnrecognizedElementParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/UnrecognizedElementParser.java index d21918b..48c0f8f 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/UnrecognizedElementParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/UnrecognizedElementParser.java @@ -7,5 +7,5 @@ import org.simantics.db.exception.DatabaseException; public interface UnrecognizedElementParser { - public void configureChild(WriteGraph graph, Deque parents, Element element, Element child) throws DatabaseException; + public void configureChild(WriteGraph graph, Deque parents, ParserElement element, ParserElement child) throws DatabaseException; } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementParser.java index 718c8b0..8a13918 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementParser.java @@ -27,29 +27,29 @@ public class ValueElementParser extends XMLElementParserBase{ } @Override - public Resource create(WriteGraph graph, Element element) + public Resource create(WriteGraph graph, ParserElement element) throws DatabaseException { Resource res = graph.newResource(); return res; } @Override - public void configure(WriteGraph graph, Deque parents, Element element) throws DatabaseException { + public void configure(WriteGraph graph, Deque parents, ParserElement element) throws DatabaseException { } @Override - public boolean connectParent(WriteGraph graph, Element parent, Element element)throws DatabaseException { + public boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element)throws DatabaseException { graph.claim(parent.getData(), graph.getResource(relationURI), element.getData()); return true; } @Override - public boolean connectChild(WriteGraph graph, Element element, Element child) throws DatabaseException { + public boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException { return false; } @Override - public void configure(WriteGraph graph, Element element, String string) throws DatabaseException { + public void configure(WriteGraph graph, ParserElement element, String string) throws DatabaseException { Layer0 l0 = Layer0.getInstance(graph); if (binding == Bindings.STRING) { graph.claim(element.getData(), l0.InstanceOf, l0.String); diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementWriter.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementWriter.java new file mode 100644 index 0000000..bcc7c95 --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/ValueElementWriter.java @@ -0,0 +1,95 @@ +package org.simantics.xml.sax.base; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.simantics.databoard.binding.Binding; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Statement; +import org.simantics.db.exception.DatabaseException; +import org.simantics.layer0.Layer0; + +public class ValueElementWriter implements XMLElementWriter{ + + String name; + Binding binding; + String typeURI; + + public ValueElementWriter(String name, String typeURI,Binding binding) { + this.name = name; + this.typeURI = typeURI; + this.binding = binding; + } + + @Override + public String getElementId() { + return name; + } + + @Override + public Resource getType(ReadGraph graph) throws DatabaseException { + return graph.getResource(typeURI); + } + + @Override + public void start(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + writer.writeStartElement(getElementId()); + } + + @Override + public List children(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + return Collections.EMPTY_LIST; + } + + @Override + public void end(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + writer.writeEndElement(); + } + + @Override + public void attributes(ReadGraph graph, WriterElement instance, Collection attributes, + XMLStreamWriter writer) throws XMLStreamException, DatabaseException { + + } + + @Override + public void characters(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + Layer0 l0 = Layer0.getInstance(graph); + Object value = graph.getValue(instance.getResource(), binding); + writer.writeCharacters(value.toString()); +// if (binding == Bindings.STRING) { +// graph.claim(element.getData(), l0.InstanceOf, l0.String); +// graph.claimValue(element.getData(), string, binding); +// } else if (binding == Bindings.INTEGER) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Integer); +// graph.claimValue(element.getData(), Integer.parseInt(string), binding); +// } else if (binding == Bindings.FLOAT) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Float); +// graph.claimValue(element.getData(), Float.parseFloat(string), binding); +// } else if (binding == Bindings.DOUBLE) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Double); +// graph.claimValue(element.getData(), Double.parseDouble(string), binding); +// } else if (binding == Bindings.BOOLEAN) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Boolean); +// graph.claimValue(element.getData(), Boolean.parseBoolean(string), binding); +// } else if (binding == Bindings.LONG) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Long); +// graph.claimValue(element.getData(), Long.parseLong(string), binding); +// } else if (binding == Bindings.BYTE) { +// graph.claim(element.getData(), l0.InstanceOf, l0.Byte); +// graph.claimValue(element.getData(), Byte.parseByte(string), binding); +// } else { +// throw new DatabaseException("Unknown datatype " + binding); +// } + } + +} diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/WriterElement.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/WriterElement.java new file mode 100644 index 0000000..62a2ded --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/WriterElement.java @@ -0,0 +1,33 @@ +package org.simantics.xml.sax.base; + +import org.simantics.db.Resource; +import org.simantics.db.Statement; + +public class WriterElement { + public WriterElement parent; + public Resource instance; + public Statement statement; + public XMLElementWriter writer; + + public WriterElement(Resource instance) { + this.instance = instance; + } + + public WriterElement(WriterElement parent, Statement statement) { + this.statement = statement; + this.instance = statement.getObject(); + this.parent = parent; + } + + public Resource getResource() { + return instance; + } + + public XMLElementWriter getWriter() { + return writer; + } + + public WriterElement getParent() { + return parent; + } +} \ No newline at end of file diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParser.java index 9085c6b..544c906 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParser.java @@ -3,5 +3,5 @@ package org.simantics.xml.sax.base; import java.util.Map; public interface XMLElementNamedChildParser extends XMLElementParser{ - Class getParser(Map parsers, Element element, Element child); + Class getParser(Map parsers, ParserElement element, ParserElement child); } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParserBase.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParserBase.java index c0a2172..f1bbdf3 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParserBase.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildParserBase.java @@ -14,7 +14,7 @@ public abstract class XMLElementNamedChildParserBase implements XMLElementNamedC private Set> parsers = new HashSet>(); @Override - public Class getParser(Map parsers, Element element, Element child) { + public Class getParser(Map parsers, ParserElement element, ParserElement child) { Class parserClass = namedParsers.get(child.qName); if (parserClass != null) return parserClass; @@ -44,7 +44,7 @@ public abstract class XMLElementNamedChildParserBase implements XMLElementNamedC // } @Override - public void configure(WriteGraph graph, Element element, String string) throws DatabaseException { + public void configure(WriteGraph graph, ParserElement element, String string) throws DatabaseException { } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriter.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriter.java new file mode 100644 index 0000000..97f4d3a --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriter.java @@ -0,0 +1,13 @@ +package org.simantics.xml.sax.base; + +import java.util.Map; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; + +public interface XMLElementNamedChildWriter extends XMLElementWriter{ + + public Class getWriter(ReadGraph graph, Map writers, WriterElement element) throws DatabaseException; + +} diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriterBase.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriterBase.java new file mode 100644 index 0000000..69b6c8d --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementNamedChildWriterBase.java @@ -0,0 +1,94 @@ +package org.simantics.xml.sax.base; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.exception.DatabaseException; +import org.simantics.scl.compiler.elaboration.errors.ElabNode; + +public abstract class XMLElementNamedChildWriterBase implements XMLElementNamedChildWriter{ + + private Map> typeWriters = new HashMap>(); + private Map> relationWriters = new HashMap>(); + private Set> writers = new HashSet>(); + + + public XMLElementNamedChildWriterBase() { + + } + + public XMLElementNamedChildWriterBase(ReadGraph graph) { + + } + + @Override + public Resource getType(ReadGraph graph) throws DatabaseException { + return null; + } + + @Override + public void start(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException { + writer.writeStartElement(getElementId()); + } + + @Override + public void characters(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + + } + + @Override + public void end(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException { + writer.writeEndElement(); + } + + @Override + public List children(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) + throws XMLStreamException, DatabaseException { + return Collections.EMPTY_LIST; + } + + @Override + public Class getWriter(ReadGraph graph, Map writers, WriterElement child) throws DatabaseException{ + Resource type = graph.getSingleType(child.instance); + Class writerClass = typeWriters.get(type); + if (writerClass != null) + return writerClass; + if (child.statement != null) { + writerClass = relationWriters.get(child.statement.getPredicate()); + if (writerClass != null) + return writerClass; + } + XMLElementWriter writer = writers.get(type); + if (writer == null) + return null; + writerClass = writer.getClass(); + if (this.writers.contains(writerClass)) + return writerClass; + for (Class c : this.writers) + if (c.isAssignableFrom(writerClass)) + return writerClass; + return null; + } + + public void addTypeWriter(Resource type, Class writer) { + typeWriters.put(type, writer); + } + + public void addRelationWriter(Resource relation, Class writer) { + relationWriters.put(relation, writer); + } + + public void addWriter(Class writer) { + writers.add(writer); + } +} diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParser.java index c3b3804..27c0ac7 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParser.java @@ -28,7 +28,7 @@ public interface XMLElementParser { * @return * @throws DatabaseException */ - public Resource create(WriteGraph graph, Element element) throws DatabaseException; + public Resource create(WriteGraph graph, ParserElement element) throws DatabaseException; /** * Configures the element. * @@ -38,7 +38,7 @@ public interface XMLElementParser { * @param element * @throws DatabaseException */ - public void configure(WriteGraph graph, Deque parents, Element element) throws DatabaseException; + public void configure(WriteGraph graph, Deque parents, ParserElement element) throws DatabaseException; /** * Configures element with characters content * @@ -48,7 +48,7 @@ public interface XMLElementParser { * @param string * @throws DatabaseException */ - public void configure(WriteGraph graph, Element element, String string) throws DatabaseException; + public void configure(WriteGraph graph, ParserElement element, String string) throws DatabaseException; /** * Adds child element. Primary method for connecting elements. @@ -58,7 +58,7 @@ public interface XMLElementParser { * @return true, if connection was done, otherwise return false. * @throws DatabaseException */ - public abstract boolean connectChild(WriteGraph graph, Element element, Element child) throws DatabaseException; + public abstract boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException; /** * Adds element to a parent. Secondary method for connecting elements. Called only if primary method fails. * @param graph @@ -67,7 +67,7 @@ public interface XMLElementParser { * @return true, if connection was done, otherwise return false. * @throws DatabaseException */ - public abstract boolean connectParent(WriteGraph graph, Element parent, Element element) throws DatabaseException; + public abstract boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element) throws DatabaseException; //public void configureChild(WriteGraph graph, Stack parents, Element element, Element child) throws DatabaseException; diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParserBase.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParserBase.java index 000d25b..7a5abf5 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParserBase.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementParserBase.java @@ -7,7 +7,7 @@ public abstract class XMLElementParserBase implements XMLElementParser{ @Override - public void configure(WriteGraph graph, Element element, String string) throws DatabaseException { + public void configure(WriteGraph graph, ParserElement element, String string) throws DatabaseException { } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementWriter.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementWriter.java new file mode 100644 index 0000000..cde7809 --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLElementWriter.java @@ -0,0 +1,25 @@ +package org.simantics.xml.sax.base; + +import java.util.Collection; +import java.util.List; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Statement; +import org.simantics.db.exception.DatabaseException; + +public interface XMLElementWriter { + + public java.lang.String getElementId(); + public Resource getType(ReadGraph graph) throws DatabaseException; + //public int idPriority(); + public void start(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException; + public void attributes(ReadGraph graph, WriterElement instance, Collection attributes, XMLStreamWriter writer) throws XMLStreamException, DatabaseException; + public void characters(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException; + public List children(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException; + public void end(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException; + +} diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLParser.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLParser.java index 43a07c5..992b98a 100644 --- a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLParser.java +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLParser.java @@ -28,17 +28,18 @@ import org.xml.sax.helpers.DefaultHandler; public class XMLParser extends DefaultHandler implements Serializable { + public static String PLUGIN_ID = "org.simantics.xml.sax.base"; + private static final long serialVersionUID = 7360740940824360338L; private static final boolean debug = false; private static String XML_SCHEMA_REF = "xmlns"; private ILogger logger; + private WriteGraph graph; private Resource root; private String schemaURI; - private Deque current = new ArrayDeque(); + private Deque current = new ArrayDeque(); private Map parsers = new HashMap(); - private WriteGraph graph; private Map, XMLElementParser> namedParsers = new HashMap, XMLElementParser>(); - private Map subParsers = new HashMap(); public XMLParser() { @@ -73,10 +74,10 @@ public class XMLParser extends DefaultHandler implements Serializable { subParsers.put(parser.getSchemaURI(), parser); } - private List idReferenceElements = new ArrayList(); - private void loadElement(Deque parents, Element element) throws SAXException{ + private List idReferenceElements = new ArrayList(); + private void loadElement(Deque parents, ParserElement element) throws SAXException{ XMLElementParser parser = null; - Element parent = null; + ParserElement parent = null; if (parents.size() > 0) { parent = parents.peek(); // check for assigned subparser @@ -139,15 +140,15 @@ public class XMLParser extends DefaultHandler implements Serializable { } } - private Map idMap = new HashMap(); + private Map idMap = new HashMap(); - private void handleElement(Deque parents, Element element) throws SAXException{ + private void handleElement(Deque parents, ParserElement element) throws SAXException{ XMLElementParser parser = element.getElementParser(); if (parser != null) { try { parser.configure(graph, parents, element); if (parents.size() > 0) { - Element parent = parents.peek(); + ParserElement parent = parents.peek(); if (parent.getElementParser() != null) { if (!parent.getElementParser().connectChild(graph, parent, element)) if (!parser.connectParent(graph, parent, element)) { @@ -163,7 +164,7 @@ public class XMLParser extends DefaultHandler implements Serializable { } String id = parser.getID(); if (id != null) { - Element existing = idMap.put(id, element); + ParserElement existing = idMap.put(id, element); if (existing != null) { // report error + use id priorities to select the kept element. boolean useExt = existing.elementParser.idPriority() > element.elementParser.idPriority(); @@ -178,7 +179,7 @@ public class XMLParser extends DefaultHandler implements Serializable { throw new SAXException(e); } } else { - Element parent = parents.peek(); + ParserElement parent = parents.peek(); if (parent != null) { parser = parent.getElementParser(); if (parser != null && parser instanceof UnrecognizedElementParser) { @@ -192,7 +193,7 @@ public class XMLParser extends DefaultHandler implements Serializable { } } - private void handleCharacters(Element element, String string) throws SAXException{ + private void handleCharacters(ParserElement element, String string) throws SAXException{ XMLElementParser parser = element.getElementParser(); if (parser != null) { try { @@ -204,11 +205,11 @@ public class XMLParser extends DefaultHandler implements Serializable { } } - private static String PLUGIN_ID = "org.simantics.xml.sax.base"; + public void done() throws SAXException{ try { - for (Element e : idReferenceElements) { + for (ParserElement e : idReferenceElements) { IDReferenceParser parser = (IDReferenceParser)parsers.get(e.qName); if (!parser.connectReferences(graph, e, idMap)) { String err ="Could not resolve ID references for " + e.getQName() + " " + e.getUri(); @@ -229,7 +230,7 @@ public class XMLParser extends DefaultHandler implements Serializable { @Override public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { - Element e = new Element(uri,localName,name,attributes); + ParserElement e = new ParserElement(uri,localName,name,attributes); loadElement(current,e); current.push(e); @@ -240,7 +241,7 @@ public class XMLParser extends DefaultHandler implements Serializable { @Override public void endElement(String uri, String localName, String name) throws SAXException { - Element e = null; + ParserElement e = null; if (!current.isEmpty()) { e = current.pop(); } diff --git a/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLWriter.java b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLWriter.java new file mode 100644 index 0000000..3fd881b --- /dev/null +++ b/org.simantics.xml.sax.base/src/org/simantics/xml/sax/base/XMLWriter.java @@ -0,0 +1,183 @@ +package org.simantics.xml.sax.base; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.simantics.db.ReadGraph; +import org.simantics.db.Resource; +import org.simantics.db.Statement; +import org.simantics.db.common.utils.ListUtils; +import org.simantics.db.common.utils.NameUtils; +import org.simantics.db.exception.DatabaseException; +import org.simantics.message.ILogger; +import org.simantics.xml.sax.ontology.XMLResource; + +public class XMLWriter { + + private ReadGraph graph; + private Map subWriters = new HashMap(); + private Map, XMLElementWriter> namedWriters = new HashMap, XMLElementWriter>(); + private Map writers = new HashMap<>(); + private String schemaURI; + + private ILogger logger; + + public ReadGraph getGraph() { + return graph; + } + + public void setGraph(ReadGraph graph) { + this.graph = graph; + for (XMLWriter p : subWriters.values()) + p.setGraph(graph); + } + + public String getSchemaURI() { + return schemaURI; + } + + public void setSchemaURI(String schemaURI) { + this.schemaURI = schemaURI; + } + + public void add(XMLElementWriter writer) throws DatabaseException { + Resource type = writer.getType(graph); + if (type != null) + writers.put(type, writer); + namedWriters.put(writer.getClass(), writer); + } + + public void add(XMLWriter writer) { + subWriters.put(writer.getSchemaURI(), writer); + } + + public void write(Resource root, XMLStreamWriter writer) throws DatabaseException, XMLStreamException { + WriterElement element = new WriterElement(root); + loadElement(element); + write(element, writer); + } + + + protected void write(WriterElement instance, XMLStreamWriter writer) throws DatabaseException, XMLStreamException { + XMLResource XML = XMLResource.getInstance(graph); + + XMLElementWriter elementWriter = instance.writer; + elementWriter.start(graph, instance, writer); + elementWriter.attributes(graph, instance, graph.getStatements(instance.instance, XML.hasAttribute), writer); + if (graph.hasValue(instance.instance)) + elementWriter.characters(graph, instance, writer); + // get all child elements + Collection childElements = graph.getStatements(instance.instance, XML.hasElement); + // load elements, assign writers + Map elementMap = new HashMap<>(); + for (Statement s : childElements) { + WriterElement c = new WriterElement(instance,s); + loadElement(c); + elementMap.put(s.getObject(), c); + } + List sorted = elementWriter.children(graph, instance, writer); + + for (Resource r : sorted) { + WriterElement child = elementMap.get(r); + write(child, writer); + } + //write the rest of the elements (in random order) + for (Statement stm : childElements) { + if (sorted.contains(stm.getObject())) + continue; + WriterElement child = elementMap.get(stm.getObject()); + write(child, writer); + } + + elementWriter.end(graph, instance, writer); + + } + +// public void write(Resource root, XMLStreamWriter writer) throws DatabaseException, XMLStreamException { +// XMLResource XML = XMLResource.getInstance(graph); +// +// Deque stack = new ArrayDeque<>(); +// Element rootElement = new Element(root); +// loadElement(rootElement); +// stack.push(rootElement); +// while (!stack.isEmpty()) { +// +// Element instance = stack.pop(); +// XMLElementWriter elementWriter = instance.writer; +// elementWriter.start(graph, instance.instance, writer); +// elementWriter.attributes(graph, graph.getStatements(instance.instance, XML.hasAttribute), writer); +// // get all child elements +// Collection childElements = graph.getStatements(instance.instance, XML.hasElement); +// // get original element order, if available +// Resource originalElementList = graph.getPossibleObject(instance.instance, XML.hasOriginalElementList); +// List originalList = null; +// if (originalElementList != null) { +// originalList = ListUtils.toList(graph, originalElementList); +// } +// if (originalList != null) { +// // check for elements that are missing form the original list (should be empty). +// for (Statement stm : childElements) { +// if (originalList.contains(stm.getObject())) +// continue; +// Element child = new Element(instance,stm.getObject()); +// loadElement(child); +// stack.push(child); +// } +// // process the list in reverse order so that the stack processing processes the items in correct order. +// for (int i = originalList.size()-1; i >= 0; i--) { +// Resource r = originalList.get(i); +// Element child = new Element(instance, r); +// loadElement(child); +// stack.push(child); +// } +// } else { +// for (Statement stm : childElements) { +// Element child = new Element(instance, stm.getObject()); +// loadElement(child); +// stack.push(child); +// } +// } +// } +// } + + private void loadElement(WriterElement child) throws DatabaseException { + XMLElementWriter childWriter = null; + if (child.parent != null && child.parent.writer instanceof XMLElementNamedChildWriter) { + XMLElementNamedChildWriter namedParentWriter = (XMLElementNamedChildWriter)child.parent.writer; + Class childWriterClass = namedParentWriter.getWriter(graph, writers, child); + if (childWriterClass != null) { + childWriter = this.writers.get(childWriterClass); + if (childWriter == null) { + try { + Constructor c = childWriterClass.getConstructor(ReadGraph.class); + //childWriter = childWriterClass.newInstance(); + childWriter = c.newInstance(graph); + namedWriters.put(childWriterClass, childWriter); + } catch (IllegalAccessException|InstantiationException|NoSuchMethodException|SecurityException|InvocationTargetException e) { + String err = "Error processing " + childWriterClass.getName() + " : element writers must have accessible constructor with ReadGraph parameter"; + logger.log(new Status(IStatus.ERROR, XMLParser.PLUGIN_ID, err)); + } + } + } + } else { + Resource type = graph.getSingleType(child.instance); + childWriter = writers.get(type); + } + if (childWriter == null) { + throw new DatabaseException("Cannot locate writer for " + NameUtils.getSafeName(graph, child.instance) + ", " + child.instance); + } + child.writer = childWriter; + + } + +} diff --git a/org.simantics.xml.sax.ontology/graph.tg b/org.simantics.xml.sax.ontology/graph.tg index 82dd4f2..f19a643 100644 Binary files a/org.simantics.xml.sax.ontology/graph.tg and b/org.simantics.xml.sax.ontology/graph.tg differ diff --git a/org.simantics.xml.sax.ontology/graph/XML.pgraph b/org.simantics.xml.sax.ontology/graph/XML.pgraph index 000f292..b0526a2 100644 --- a/org.simantics.xml.sax.ontology/graph/XML.pgraph +++ b/org.simantics.xml.sax.ontology/graph/XML.pgraph @@ -6,14 +6,14 @@ XML = : L0.Ontology // Built-in types - +XML.Entity L0.String -XML.ComplexType + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/org.simantics.xml.sax/schema/gen.bat b/org.simantics.xml.sax/schema/gen.bat index ce18e92..549d0cc 100644 --- a/org.simantics.xml.sax/schema/gen.bat +++ b/org.simantics.xml.sax/schema/gen.bat @@ -1 +1 @@ -"c:\Program Files\Java\jdk1.8.0_60\bin\xjc" -d ../src configuration.xsd +"c:\Program Files\Java\jdk1.8.0_112\bin\xjc" -d ../src configuration.xsd diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/ExporterGenerator.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/ExporterGenerator.java new file mode 100644 index 0000000..1d97259 --- /dev/null +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/ExporterGenerator.java @@ -0,0 +1,846 @@ +package org.simantics.xml.sax; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.simantics.utils.datastructures.BijectionMap; +import org.simantics.xml.sax.configuration.AttributeComposition; +import org.simantics.xml.sax.configuration.Configuration; +import org.simantics.xml.sax.configuration.IDProvider; +import org.simantics.xml.sax.configuration.IDReference; +import org.simantics.xml.sax.configuration.Rename; +import org.simantics.xml.sax.configuration.UnrecognizedChildElement; +import org.w3._2001.xmlschema.Annotated; +import org.w3._2001.xmlschema.Attribute; +import org.w3._2001.xmlschema.AttributeGroup; +import org.w3._2001.xmlschema.ComplexType; +import org.w3._2001.xmlschema.Element; +import org.w3._2001.xmlschema.LocalComplexType; +import org.w3._2001.xmlschema.LocalSimpleType; +import org.w3._2001.xmlschema.NamedAttributeGroup; +import org.w3._2001.xmlschema.OpenAttrs; +import org.w3._2001.xmlschema.Restriction; +import org.w3._2001.xmlschema.Schema; +import org.w3._2001.xmlschema.SimpleType; +import org.w3._2001.xmlschema.TopLevelAttribute; + +public class ExporterGenerator extends JavaGenerator{ + + public ExporterGenerator(Configuration configuration) { + super(configuration); + } + + + + public void createParser(Schema schema,String className, SchemaConverter converter) throws IOException { + this.schema = schema; + this.ontologyClassName = className; + this.converter = converter; + + + String packageParts[] = className.split("\\."); + String name = packageParts[packageParts.length-1]; + + + ontShort = name.substring(0, 3).toUpperCase(); + ontShort +="."; + String parserPackagePostfix = "_exp"; + String importerClassPostfix = "Exporter"; + String parserClassPostfix = "Writer"; + elementPackageName = name+parserPackagePostfix; + + importParserDir= new File(converter.getParserDir().getAbsolutePath()+"/"+elementPackageName); + if (!importParserDir.exists()) + importParserDir.mkdirs(); + + handle(schema); + // Create Importer class + File importerFile = new File(converter.getParserDir().getAbsolutePath()+"/"+name+importerClassPostfix+".java"); + PrintWriter mainWriter = createFile(importerFile); + mainWriter.println("package " + converter.getPluginName() +";"); + mainWriter.println(); + mainWriter.println("import java.io.File;"); + mainWriter.println("import org.simantics.db.Resource;"); + mainWriter.println("import org.simantics.db.Session;"); + mainWriter.println("import org.simantics.db.exception.DatabaseException;"); + mainWriter.println("import org.simantics.xml.sax.base.AbstractExporter;"); + mainWriter.println(); + mainWriter.println("public class " + name + importerClassPostfix+" extends AbstractExporter {"); + mainWriter.println(); + mainWriter.println(" public " + name + importerClassPostfix+"(Session session, File file, Resource root) throws DatabaseException {"); + mainWriter.println(" super(session, file, root);"); + mainWriter.println(" setXmlWriter(new "+name + parserClassPostfix+"(session));"); + mainWriter.println(" }"); + mainWriter.println(); + mainWriter.println("}"); + + mainWriter.println(); + mainWriter.flush(); + mainWriter.close(); + + // Create Parser class + File parserFile = new File(converter.getParserDir().getAbsolutePath()+"/"+name+parserClassPostfix+".java"); + mainWriter = createFile(parserFile); + mainWriter.println("package " + converter.getPluginName() +";"); + mainWriter.println(); + mainWriter.println("import org.simantics.xml.sax.base.XMLWriter;"); + mainWriter.println("import org.simantics.db.ReadGraph;"); + mainWriter.println("import org.simantics.db.Session;"); + mainWriter.println("import org.simantics.db.exception.DatabaseException;"); + mainWriter.println("import org.simantics.db.common.request.ReadRequest;"); + mainWriter.println(); + mainWriter.println("public class " + name + parserClassPostfix+" extends XMLWriter {"); + mainWriter.println(); + mainWriter.println(" public " + name + parserClassPostfix+"(Session session) throws DatabaseException {"); + if (schema.getTargetNamespace() != null) + mainWriter.println(" setSchemaURI(\""+schema.getTargetNamespace()+"\");"); + mainWriter.println(" session.syncRequest(new ReadRequest() {"); + mainWriter.println(" @Override"); + mainWriter.println(" public void run(ReadGraph graph) throws DatabaseException {"); + mainWriter.println(" setGraph(graph);"); + for (String s : ruleClassNames) { + mainWriter.println(" add(new "+s+"(graph));"); + } + mainWriter.println(" }"); + mainWriter.println(" });"); + mainWriter.println(" }"); + mainWriter.println("}"); + + mainWriter.println(); + mainWriter.flush(); + mainWriter.close(); + } + + protected void handle(TopLevelAttribute topLevelAttribute) { + + } + + @Override + protected String getBaseClass() { + return "org.simantics.xml.sax.base.XMLElementNamedChildWriterBase"; + } + + + @Override + protected void handleComplexType(SchemaObject complexTypeObj) { + ComplexType topLevelComplexType = complexTypeObj.getComplexType(); + + String name = getName(complexTypeObj);//topLevelComplexType.getName(); + + String className = name;//"_"+name; + + FileWriter fw = new FileWriter(); + try { + fw.writer = createFile(new File(importParserDir.getAbsolutePath()+"/"+className+".java")); + } catch (IOException e) { + throw new RuntimeException(e); + } + writers.put(complexTypeObj, fw); + + boolean isList = false; + + String baseClass = "org.simantics.xml.sax.base.XMLElementNamedChildWriterBase"; + + boolean inherited = false; + + QName type = getComplexTypeBase(topLevelComplexType); + if (type != null && !type.getNamespaceURI().equals("http://www.w3.org/2001/XMLSchema")) { + baseClass = getName(complexTypeName.get(type.getLocalPart())); + inherited = true; + } + + provider = getIDProvider(topLevelComplexType); + List references = getIDReferences(topLevelComplexType); + UnrecognizedChildElement unknownChildElement = getUnknown(topLevelComplexType); + +// List intrerfaces = new ArrayList(); +// if (references.size() > 0) +// intrerfaces.add("org.simantics.xml.sax.base.IDReferenceParser"); +// if (unknownChildElement != null) +// intrerfaces.add("org.simantics.xml.sax.base.UnrecognizedElementParser"); + + createClassHeader(fw.writer); + writeClass(fw.writer,false, null, className, baseClass, Collections.EMPTY_LIST); + +// writeIDProvider(fw.writer); + + fw.writer.println(" @Override"); + fw.writer.println(" public Resource getType(ReadGraph graph) throws DatabaseException {"); + fw.writer.println(" "+getOntologyImport()); + fw.writer.println(" return "+ontShort+name+";"); + fw.writer.println(" }"); + fw.writer.println(); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public Resource create(WriteGraph graph, ParserElement element) throws DatabaseException{"); +// fw.writer.println(" Layer0 L0 = Layer0.getInstance(graph);"); +// fw.writer.println(" "+getOntologyImport()); +// if (!isList) { +// fw.writer.println(" Resource res = graph.newResource();"); +// fw.writer.println(" graph.claim(res, L0.InstanceOf, "+ontShort+name+");"); +// } else { +// fw.writer.println(" Resource res = ListUtils.create(graph, "+ontShort+name+", Collections.EMPTY_LIST);"); +// } +// fw.writer.println(" return res;"); +// fw.writer.println(" }"); +// fw.writer.println(); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element) throws DatabaseException{"); +// fw.writer.println(" "+getOntologyImport()); +// fw.writer.println(" graph.claim(parent.getData(), "+this.ontShort+getName(complexTypeObj,"has")+", element.getData());"); +// fw.writer.println(" return true;"); +// fw.writer.println(" }"); +// fw.writer.println(); + + StringWriter stringWriter = new StringWriter(); + fw.delayedWriter = new PrintWriter(stringWriter); + StringWriter stringWriter2 = new StringWriter(); + fw.delayedWriter2 = new PrintWriter(stringWriter2); + + fw.writer.println(" public " + className + "(ReadGraph graph) {"); + fw.writer.println(" super(graph);"); + fw.writer.println(" "+getOntologyImport()); + + handleComplexTypeExtension(complexTypeObj); + + fw.writer.println(" }"); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException{"); +// fw.writer.println(" "+getOntologyImport()); +// +// if (stringWriter.getBuffer().length() > 0) { +// fw.writer.write(stringWriter.toString()); +// } +// +// +// fw.writer.println(" return false;"); +// fw.writer.println(" }"); +// fw.writer.println(); + + if (stringWriter2.getBuffer().length() > 0) { + fw.writer.write(stringWriter2.toString()); + } + + stringWriter = null; + fw.delayedWriter.close(); + fw.delayedWriter=null; + stringWriter2 = null; + fw.delayedWriter2.close(); + fw.delayedWriter2 = null; + + fw.writer.println(" @Override"); + fw.writer.println(" public void attributes(ReadGraph graph, WriterElement instance, Collection attributes, XMLStreamWriter writer) throws XMLStreamException, DatabaseException{"); + if (inherited) { + fw.writer.println(" super.attributes(graph,instance,attributes,writer);"); + } + fw.writer.println(" "+getOntologyImport()); + fw.writer.println(" for (Statement attribute : attributes) {"); + handleComplexTypeAttributes(complexTypeObj); + handleExtensionAttributes(complexTypeObj); + fw.writer.println(" }"); + fw.writer.println(" }"); + +// writeIDReferences(fw.writer,name, references); +// writeUnknownChild(fw.writer,name,unknownChildElement); + + fw.writer.println("}"); + fw.writer.println(); + fw.writer.flush(); + fw.writer.close(); + fw.writer = null; + writers.remove(complexTypeObj); + provider = null; + } + + + + @Override + protected void handleIndicator(SchemaObject parent, SchemaElement indicator, SchemaElement element, boolean reference, String ref, QName refType) { + FileWriter fw = getWriter(parent); + String binding = getBindingFromPrimitiveType(refType); + if (binding == null) { + SchemaObject refElement = elementName.get(refType.getLocalPart()); + SchemaObject refComplexType = complexTypeName.get(refType.getLocalPart()); + + String className = null; + String refClassName = null; + if (refElement != null) + className = getName(refElement); + else + className = getName(refComplexType); + + if (refComplexType != null) { + refClassName = getName(refComplexType); + } else { + refClassName = getName(refElement); + } + + if (!reference) + fw.writer.println(" addTypeWriter("+ontShort+ className +", "+className+".class);"); + else + fw.writer.println(" addWriter("+className+".class);"); + if (!className.equals(refClassName)) + fw.writer.println(" addWriter("+refClassName+".class);"); + +// fw.delayedWriter.println(" if (child.getElementParser() instanceof "+refClassName+"){"); +// fw.delayedWriter.println(" graph.claim(element.getData(), "+ontShort+getName(parent)+"_has"+ref + ", child.getData());"); +// if (useElementList(parent, indicator,element, reference, ref, refType)) { +// +// // element type specific list +// fw.delayedWriter.println(" {"); +// fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(),"+ontShort+getName(parent)+"_has"+ref + "List);"); +// fw.delayedWriter.println(" if (list == null) {"); +// fw.delayedWriter.println(" list = org.simantics.db.common.utils.ListUtils.create(graph, java.util.Collections.singletonList(child.getData()));"); +// fw.delayedWriter.println(" graph.claim(element.getData(),"+ontShort+getName(parent)+"_has"+ref + "List,list);"); +// fw.delayedWriter.println(" } else {"); +// fw.delayedWriter.println(" org.simantics.db.common.utils.ListUtils.insertBack(graph, list, java.util.Collections.singletonList(child.getData()));"); +// fw.delayedWriter.println(" }"); +// fw.delayedWriter.println(" }"); +// } +// if (useOriginalList(parent, indicator,element, reference, ref, refType)) { +// // generic list +// fw.delayedWriter.println(" {"); +// fw.delayedWriter.println(" XMLResource XML = XMLResource.getInstance(graph);"); +// fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(), XML.hasOriginalElementList);"); +// fw.delayedWriter.println(" if (list == null) {"); +// fw.delayedWriter.println(" list = org.simantics.db.common.utils.ListUtils.create(graph, java.util.Collections.singletonList(child.getData()));"); +// fw.delayedWriter.println(" graph.claim(element.getData(), XML.hasOriginalElementList,list);"); +// fw.delayedWriter.println(" } else {"); +// fw.delayedWriter.println(" org.simantics.db.common.utils.ListUtils.insertBack(graph, list, java.util.Collections.singletonList(child.getData()));"); +// fw.delayedWriter.println(" }"); +// fw.delayedWriter.println(" }"); +// } +// +// fw.delayedWriter.println(" return true;"); +// fw.delayedWriter.println(" }"); + } else { + SchemaObject refElement = elementName.get(refType.getLocalPart()); + //writer.println(commentTag+ontShort+"."+parent+".has"+ref + " getWriter(ReadGraph graph, java.util.Map writers, WriterElement child) throws DatabaseException{"); + fw.delayedWriter2.println(" Class writerClass = super.getWriter(graph, writers, child);"); + fw.delayedWriter2.println(" if (writerClass != null) return writerClass;"); + fw.delayedWriter2.println(" Resource type = graph.getSingleType(child.instance);"); + fw.delayedWriter2.println(" org.simantics.xml.sax.base.XMLElementWriter writer = writers.get(type);"); + fw.delayedWriter2.println(" if (writer != null) return writer.getClass();"); + fw.delayedWriter2.println(" return null;"); + fw.delayedWriter2.println(" }"); + } + + + + + @Override + protected void handle(SchemaObject parent, Attribute attribute) { + String name = attribute.getName(); + QName primitiveType = attribute.getType(); + SimpleType simpleType = attribute.getSimpleType(); + QName ref = attribute.getRef(); + + String relationName; + String attrName; + if (name != null) { + attrName = name; + relationName = ontShort+"has"+name; + if (parent != null) + relationName = ontShort+getName(parent)+"_has"+name; + } + else if (ref != null && parent != null) { + attrName = ref.getLocalPart(); + relationName = ontShort+getName(parent)+"_has"+ref.getLocalPart(); + + Attribute referred = getRefAttribute(ref); + if (referred != null) { + primitiveType = referred.getType(); + simpleType = referred.getSimpleType(); + } + + } else { + throw new RuntimeException(); + } + boolean isReference = false; + if (provider!= null && provider.getAttribute().getName().equals(attrName)) + isReference = true; + + FileWriter fw = getWriter(parent); + if (primitiveType != null) { + + //String binding = getBindingFromPrimitiveType(primitiveType); + TypeEntry binding = getTypeEntry(primitiveType); + + if (binding != null) { + writeAttribute(fw, attrName, relationName, binding, isReference); + return; + } else { + if (simpleType == null) { + SchemaObject simpleTypeObj = simpleTypeName.get(primitiveType.getLocalPart()); + if (simpleTypeObj != null) + simpleType = simpleTypeObj.getSimpleType(); + } + } + } + if (simpleType != null) { + org.w3._2001.xmlschema.List list = simpleType.getList(); + if (list != null) { + TypeEntry binding = getTypeEntry(new QName(SCHEMA_NS, "string")); + writeAttribute(fw, attrName, relationName, binding, isReference); + } else { + Restriction restriction = simpleType.getRestriction(); + if (restriction == null) + throw new RuntimeException("Cannot resolve type for Attribute " + attrName + " -> " + primitiveType.getLocalPart()+ ", SimpleType restriction is unset"); + QName base = restriction.getBase(); + + + //String binding = getBindingFromPrimitiveType(base); + TypeEntry binding = getTypeEntry(base); + writeAttribute(fw, attrName, relationName, binding, isReference); + } + } else { + // TODO : using default String attribute should be configured with rules. + //throw new RuntimeException("Cannot resolve type for Attribute " + attrName + " -> " + primitiveType.getLocalPart()); + fw.writer.println(" //FIXME: Cannot resolve type for Attribute " + attrName + " Using default type String"); + //writeAttribute(fw, attrName, relationName, "STRING", isReference); + writeAttribute(fw, attrName, relationName, getTypeEntry("string"), isReference); + } + } + + //private void writeAttribute(FileWriter fw, String attrName, String relationName, String binding, boolean isReference) { + private void writeAttribute(FileWriter fw, String attrName, String relationName, TypeEntry binding, boolean isReference) { + fw.writer.println(" {"); + fw.writer.println(" if (attribute.getPredicate().equals("+relationName+")) {"); + fw.writer.println(" writer.writeAttribute(\""+attrName+"\", " + binding.getToString("graph.getValue(attribute.getObject(),"+binding.binding+")")+");"); + // fw.writer.println(" graph.claimLiteral(element.getData(),"+relationName+","+getValueGetterMethod(binding,"a")+", "+binding.binding+");"); + // if (isReference) + // fw.writer.println(" idProviderValue = a.getValue();"); + fw.writer.println(" }"); + fw.writer.println(" }"); + } + + @Override + protected void handleAttributes(SchemaObject simpleTypeObj) { + SchemaObject parent = simpleTypeObj.getParent(); + FileWriter fw = getWriter(parent); + + SimpleType simpleType = simpleTypeObj.getSimpleType(); + Restriction restriction = simpleType.getRestriction(); + if (restriction == null) + throw new RuntimeException("Cannot resolve type for Element " + getName(parent)); + QName base = restriction.getBase(); + + + //String binding = getBindingFromPrimitiveType(base); + TypeEntry binding = getTypeEntry(base); + + fw.writer.println(" @Override"); + fw.writer.println(" public void characters(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException {"); + fw.writer.println(" writer.writeCharacters("+ binding.getToString("graph.getValue(attribute.getObject(),"+binding.binding+")")+");"); +// fw.writer.println(" graph.claimValue(element.getData(),"+getValueGetter(binding)+", "+binding.binding +");"); + fw.writer.println(" }"); + } + + @Override + protected void handle(SchemaObject parent, AttributeGroup attribute) { + if (parent != null) { + FileWriter fw = getWriter(parent); + NamedAttributeGroup group = getAttributeGroup(attribute.getRef().getLocalPart()); + fw.writer.println(commentTag+" AttributeGroup " + group.getName()); + SchemaObject obj = new SchemaObject(parent,attribute); + for (Annotated annotated : group.getAttributeOrAttributeGroup()) { + if (annotated instanceof Attribute) { + //handle("AttributeGroups_"+group.getName(),(Attribute)annotated); + handle(obj,(Attribute)annotated); + } else if (annotated instanceof AttributeGroup) { + //handle("AttributeGroups_"+group.getName(),(AttributeGroup)annotated); + handle(obj,(AttributeGroup)annotated); + } + } + fw.writer.println(commentTag+" End of AttributeGroup " + group.getName()); + } + + } + + @Override + protected void handleAttributeComposition(SchemaObject parent, AttributeComposition composition, BijectionMap attributes) { + FileWriter fw = getWriter(parent); + QName type = new QName(CONVERSION_NS, composition.getType()); + TypeEntry typeEntry = getTypeEntry(type); + String arrayBinding = typeEntry.binding;//getBindingFromPrimitiveType(type); + String javaType = typeEntry.javaType;//getJavaTypeFromPrimitiveType(type); + String name = composition.getName(); + + String relationName; + if (name != null) { + relationName = ontShort+"has"+name; + if (parent != null) + relationName = ontShort+getName(parent)+"_has"+name; + } else { + throw new RuntimeException(); + } + fw.writer.println(" if (attribute.getPredicate().equals("+relationName+")) {"); + fw.writer.println(" "+javaType+" value = ("+javaType+")graph.getValue(attribute.getObject(),"+arrayBinding+");"); + //fw.writer.println(" writer.writeAttribute("+attrName+", graph.getValue(attribute.getObject(),"+binding.binding+").toString());"); + + int i = 0; + for (org.simantics.xml.sax.configuration.Attribute a : composition.getAttribute()) + fw.writer.println(" writer.writeAttribute(\""+a.getName()+"\","+typeEntry.getElementToString("value["+(i++)+"]")+");"); + //fw.writer.println(" writer.writeAttribute(\""+a.getName()+"\",value["+(i++)+"].toString());"); +// fw.writer.println(" Attribute a"+(i++)+" = element.getAttribute(\"" +a.getName()+"\");"); +// fw.writer.print (" "+javaType + " value = new "+javaType+"{"); + i = 0; + // FIXME : handle optional attributes properly. +// for (org.simantics.xml.sax.configuration.Attribute a : composition.getAttribute()) { +// Attribute attribute = ((Attribute)attributes.getRight(a)); +// //QName atype = getBaseType(attribute); +// QName atype = getPrimitiveType(attribute); +// String defaultValue = attribute.getDefault(); +// if (defaultValue == null) +// defaultValue = getDefaultValue(atype); +// +// //String binding = getBindingFromPrimitiveType(atype); +// TypeEntry binding = getTypeEntry(atype); +// if (i > 0) +// fw.writer.print(","); +// if (defaultValue != null) +// fw.writer.print("a"+(i)+"!= null ? "+ getValueGetterMethod(binding,"a"+(i++)) + " : " +defaultValue); +// else +// fw.writer.print(getValueGetterMethod(binding,"a"+(i++))); +// } +// fw.writer.println("};"); +// fw.writer.println(" graph.claimLiteral(element.getData(),"+relationName+", value, "+arrayBinding+");"); + fw.writer.println(" }"); + + } + + protected String getDefaultValue(QName atype) { + Map types = typeMap.get(atype.getNamespaceURI()); + if (types == null) + return null; + TypeEntry entry = types.get(atype.getLocalPart()); + if (entry == null) + return null; + return entry.defaultValue; + } + + + @Override + protected void handleSimpleType(SchemaObject parent, SchemaObject simpleType) { + + } + + + + IDProvider provider; + @Override + protected void handleElement(SchemaObject elementObj) { + Element element = elementObj.getElement(); + + String name = getName(elementObj);//topLevelElement.getName(); + String className = name; + + FileWriter fw = new FileWriter(); + try { + fw.writer = createFile(new File(importParserDir.getAbsolutePath()+"/"+className+".java")); + } catch (IOException e) { + throw new RuntimeException(e); + } + writers.put(elementObj, fw); + boolean isList = false; + + Inheritance inhertiance = getElementInheritance(elementObj); + + provider = getIDProvider(element); + List references = getIDReferences(element); + UnrecognizedChildElement unknownChildElement = getUnknown(element); + +// List intrerfaces = new ArrayList(); +// if (references.size() > 0) +// intrerfaces.add("org.simantics.xml.sax.base.IDReferenceParser"); +// if (unknownChildElement != null) +// intrerfaces.add("org.simantics.xml.sax.base.UnrecognizedElementParser"); + + createClassHeader(fw.writer); + writeClass(fw.writer,false, element.getName(), className, inhertiance.baseClass, Collections.EMPTY_LIST); +// writeIDProvider(fw.writer); + fw.writer.println(" @Override"); + fw.writer.println(" public Resource getType(ReadGraph graph) throws DatabaseException {"); + fw.writer.println(" "+getOntologyImport()); + fw.writer.println(" return "+ontShort+name+";"); +// if (!isList) { +// fw.writer.println(" Resource res = graph.newResource();"); +// fw.writer.println(" graph.claim(res, L0.InstanceOf, "+ontShort+name+");"); +// } else { +// fw.writer.println(" Resource res = ListUtils.create(graph, "+ontShort+name+", Collections.EMPTY_LIST);"); +// } +// fw.writer.println(" return res;"); + fw.writer.println(" }"); + fw.writer.println(); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element) throws DatabaseException{"); +// fw.writer.println(" "+getOntologyImport()); +// fw.writer.println(" graph.claim(parent.getData(), "+this.ontShort+getName(elementObj,"has")+", element.getData());"); +// fw.writer.println(" return true;"); +// fw.writer.println(" }"); +// fw.writer.println(); + LocalComplexType complexType = element.getComplexType(); + LocalSimpleType simpleType = element.getSimpleType(); + + fw.writer.println(" @Override"); + fw.writer.println(" public void attributes(ReadGraph graph, WriterElement instance, Collection attributes, XMLStreamWriter writer) throws XMLStreamException, DatabaseException{"); + if (inhertiance.type == InheritanceType.ComplexType) { + fw.writer.println(" super.attributes(graph,instance,attributes,writer);"); + } + fw.writer.println(" "+getOntologyImport()); + fw.writer.println(" for (Statement attribute : attributes) {"); + if (complexType != null) { + SchemaObject obj = complexTypes.get(complexType); + handleElementComplexTypeAttributes(obj); + } + fw.writer.println(" }"); + fw.writer.println(" }"); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public void configure(WriteGraph graph, Deque parents, ParserElement element) throws DatabaseException {"); +// if (inhertiance.type == InheritanceType.ComplexType) { +// fw.writer.println(" super.configure(graph,parents,element);"); +// } +// fw.writer.println(" "+getOntologyImport()); +// +// LocalComplexType complexType = element.getComplexType(); +// LocalSimpleType simpleType = element.getSimpleType(); +// +// if (complexType != null) { +// SchemaObject obj = complexTypes.get(complexType); +// handleElementComplexTypeAttributes(obj); +// } +// fw.writer.println(" }"); + + if (inhertiance.type == InheritanceType.AtomicType) { + fw.writer.println(); +// fw.writer.println(" @Override"); +// fw.writer.println(" public void configure(WriteGraph graph, ParserElement element, java.lang.String string) throws DatabaseException {"); +// fw.writer.println(" graph.claimValue(element.getData(), "+getValueGetter(inhertiance.atomicType,"string")+", "+inhertiance.atomicType.binding+");"); +// fw.writer.println(" }"); + fw.writer.println(" @Override"); + fw.writer.println(" public void characters(ReadGraph graph, WriterElement instance, XMLStreamWriter writer) throws XMLStreamException, DatabaseException {"); + fw.writer.println(" writer.writeCharacters("+inhertiance.atomicType.getToString("graph.getValue(instance.getResource(),"+inhertiance.atomicType.binding+")")+");"); +// fw.writer.println(" graph.claimValue(element.getData(),"+getValueGetter(binding)+", "+binding.binding +");"); + fw.writer.println(" }"); + } +// if (simpleType != null) { +// SchemaObject obj = simpleTypes.get(simpleType); +// handleElementSimpleTypeAttributes(obj); +// } + + + StringWriter stringWriter = new StringWriter(); + fw.delayedWriter = new PrintWriter(stringWriter); + StringWriter stringWriter2 = new StringWriter(); + fw.delayedWriter2 = new PrintWriter(stringWriter2); + + fw.writer.println(" public " + className + "(ReadGraph graph) {"); + fw.writer.println(" super(graph);"); + fw.writer.println(" "+getOntologyImport()); + if (complexType != null) { + SchemaObject obj = complexTypes.get(complexType); + handleComplexTypeExtension(obj); + } else if (simpleType != null) { + + } + + fw.writer.println(" }"); + +// fw.writer.println(" @Override"); +// fw.writer.println(" public boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException{"); +// fw.writer.println(" "+getOntologyImport()); +// +// if (stringWriter.getBuffer().length() > 0) { +// fw.writer.write(stringWriter.toString()); +// } +// if (inhertiance.type == InheritanceType.ComplexType) { +// fw.writer.println(" return super.connectChild(graph,element,child);"); +// } else { +// fw.writer.println(" return false;"); +// } +// fw.writer.println(" }"); +// fw.writer.println(); + + if (stringWriter2.getBuffer().length() > 0) { + fw.writer.write(stringWriter2.toString()); + } + + stringWriter = null; + fw.delayedWriter.close(); + fw.delayedWriter = null; + stringWriter2 = null; + fw.delayedWriter2.close(); + fw.delayedWriter2 = null; + +// writeIDReferences(fw.writer,name, references); +// writeUnknownChild(fw.writer,name,unknownChildElement); + + fw.writer.println("}"); + fw.writer.println(); + fw.writer.flush(); + fw.writer.close(); + fw.writer = null; + writers.remove(elementObj); + provider = null; + + ruleClassNames.add(converter.getPluginName()+"."+elementPackageName+"."+name); + } + + +// private void writeIDProvider(PrintWriter writer) { +// if (provider != null) { +// writer.println(" java.lang.String idProviderValue = null;"); +// writer.println(); +// writer.println(" @Override"); +// writer.println(" public java.lang.String getID() {"); +// writer.println(" java.lang.String s = idProviderValue;"); +// writer.println(" idProviderValue = null;"); +// writer.println(" return s;"); +// writer.println(" }"); +// writer.println(); +// if (provider.getPriority() != null) { +// writer.println(" @Override"); +// writer.println(" public int idPriority() {"); +// writer.println(" return " + provider.getPriority().intValue()+";"); +// writer.println(" }"); +// } +// } +// } +// +// private void writeIDReferences(PrintWriter writer,String name, List references) { +// if (references.size() > 0) { +// writer.println(" @Override"); +// writer.println(" public boolean connectReferences(WriteGraph graph, ParserElement element, java.util.Map map) throws DatabaseException {"); +// writer.println(" "+getOntologyImport()); +// writer.println(" boolean result = true;"); +// for (IDReference ref : references) { +// writer.println(" {"); +// writer.println(" Attribute a = element.getAttribute(\"" + ref.getIDSource().getName() +"\");"); +// writer.println(" if (a != null) {"); +// writer.println(" ParserElement refEle = map.get(a.value);"); +// writer.println(" if (refEle != null) {"); +// writer.println(" Resource ref = refEle.getData();"); +// writer.println(" graph.claim(element.getData(), "+ontShort+name+"_"+ref.getReference().getName()+", ref);"); +// writer.println(" } else {"); +// writer.println(" result = false;"); +// writer.println(" }"); +// writer.println(" }"); +// writer.println(" }"); +// } +// writer.println(" return result;"); +// writer.println(" }"); +// writer.println(); +// } +// } + +// private void writeUnknownChild(PrintWriter writer,String name, UnrecognizedChildElement unknownChildElement) { +// if (unknownChildElement == null) +// return; +// +// writer.println(" @Override"); +// writer.println(" public void configureChild(WriteGraph graph, Deque parents, ParserElement element, ParserElement child) throws DatabaseException {"); +// writer.println(" " + unknownChildElement.getJavaMethod()); +// writer.println(" }"); +// writer.println(); +// +// } + + protected void createClassHeader(PrintWriter writer) { + writer.println("package " + converter.getPluginName() +"."+elementPackageName+";"); + writer.println(); + writer.println("import org.simantics.databoard.Bindings;"); + writer.println("import org.simantics.db.Resource;"); + writer.println("import org.simantics.db.ReadGraph;"); + writer.println("import org.simantics.db.Statement;"); + writer.println("import org.simantics.db.exception.DatabaseException;"); + writer.println("import org.simantics.xml.sax.base.WriterElement;"); + writer.println("import org.simantics.xml.sax.ontology.XMLResource;"); + writer.println("import java.util.Collection;"); + writer.println("import javax.xml.stream.XMLStreamException;"); + writer.println("import javax.xml.stream.XMLStreamWriter;"); +// if (!isList) { +// writer.println("import org.simantics.layer0.Layer0;"); +// } else { +// writer.println("import java.util.Collections;"); +// writer.println("import org.simantics.db.common.utils.ListUtils;"); +// } + writer.println(); + } + + + +} diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/ImporterGenerator.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/ImporterGenerator.java index 4245e3e..cff6e92 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/ImporterGenerator.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/ImporterGenerator.java @@ -16,6 +16,7 @@ import org.simantics.xml.sax.configuration.AttributeComposition; import org.simantics.xml.sax.configuration.Configuration; import org.simantics.xml.sax.configuration.IDProvider; import org.simantics.xml.sax.configuration.IDReference; +import org.simantics.xml.sax.configuration.Rename; import org.simantics.xml.sax.configuration.UnrecognizedChildElement; import org.w3._2001.xmlschema.Annotated; import org.w3._2001.xmlschema.Attribute; @@ -32,24 +33,11 @@ import org.w3._2001.xmlschema.Schema; import org.w3._2001.xmlschema.SimpleType; import org.w3._2001.xmlschema.TopLevelAttribute; -public class ImporterGenerator extends SchemaConversionBase{ +public class ImporterGenerator extends JavaGenerator{ public ImporterGenerator(Configuration configuration) { super(configuration); } - - String commentTag = "//"; - - Schema schema; - String ontologyClassName; - SchemaConverter converter; - - List ruleClassNames = new ArrayList(); - - String ontShort = "ONT"; - - File importParserDir; - String elementPackageName; public void createParser(Schema schema,String className, SchemaConverter converter) throws IOException { this.schema = schema; @@ -88,12 +76,6 @@ public class ImporterGenerator extends SchemaConversionBase{ mainWriter.println(" super(session, file, new "+name + parserClassPostfix+"());"); mainWriter.println(" }"); mainWriter.println(); -// mainWriter.println(" @Override"); -// mainWriter.println(" public void configure(XMLParser parser) {"); -// for (String s : ruleClassNames) { -// mainWriter.println(" parser.add(new "+s+"());"); -// } -// mainWriter.println(" }"); mainWriter.println("}"); mainWriter.println(); @@ -122,80 +104,12 @@ public class ImporterGenerator extends SchemaConversionBase{ mainWriter.flush(); mainWriter.close(); } - - protected PrintWriter createFile(File file) throws IOException { - if (!file.exists()) - file.createNewFile(); - PrintWriter writer = new PrintWriter(file); - for (String s : converter.getHeader()) { - writer.println(commentTag + " " + s); - } - writer.println(); - return writer; - } - -// protected String getValueGetter(String binding,String name) { -// if (binding == null) -// return name+".getValue()"; -// if ("STRING".equals(binding)) -// return name+".getValue()"; -// if ("BOOLEAN".equals(binding)) -// return "Boolean.parseBoolean("+name+".getValue())"; -// if ("INTEGER".equals(binding)) -// return "Integer.parseInt("+name+".getValue())"; -// if ("DOUBLE".equals(binding)) -// return "Double.parseDouble("+name+".getValue())"; -// if ("FLOAT".equals(binding)) -// return "Float.parseFloat("+name+".getValue())"; -// return name+".getValue()"; -// } -// protected String getValueGetter(String binding) { -// if (binding == null) -// return "value"; -// if ("STRING".equals(binding)) -// return "value"; -// if ("BOOLEAN".equals(binding)) -// return "Boolean.parseBoolean(value)"; -// if ("INTEGER".equals(binding)) -// return "Integer.parseInt(value)"; -// if ("DOUBLE".equals(binding)) -// return "Double.parseDouble(value)"; -// if ("FLOAT".equals(binding)) -// return "Float.parseFloat(value)"; -// return "value"; -// } - protected String getValueGetterMethod(TypeEntry binding,String name) { - if (binding == null) - return name+".getValue()"; - return binding.getValueGetterMethod(name); - } - - protected String getValueGetter(TypeEntry binding,String name) { - if (binding == null) - return name; - return binding.getValueGetter(name); - } - protected String getValueGetter(TypeEntry binding) { - if (binding == null) - return "value"; - return binding.getValueGetter(); - } - + protected void handle(TopLevelAttribute topLevelAttribute) { } - - - public static String getComplexTypePrefix() { - return "ComplexTypes_"; - } - public static String getAttributeGroupPrefix() { - return "AttributeGroups_"; - } - - private Map writers = new HashMap(); @Override protected void handleComplexType(SchemaObject complexTypeObj) { ComplexType topLevelComplexType = complexTypeObj.getComplexType(); @@ -240,7 +154,7 @@ public class ImporterGenerator extends SchemaConversionBase{ writeIDProvider(fw.writer); fw.writer.println(" @Override"); - fw.writer.println(" public Resource create(WriteGraph graph, Element element) throws DatabaseException{"); + fw.writer.println(" public Resource create(WriteGraph graph, ParserElement element) throws DatabaseException{"); fw.writer.println(" Layer0 L0 = Layer0.getInstance(graph);"); fw.writer.println(" "+getOntologyImport()); if (!isList) { @@ -254,7 +168,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.writer.println(); fw.writer.println(" @Override"); - fw.writer.println(" public boolean connectParent(WriteGraph graph, Element parent, Element element) throws DatabaseException{"); + fw.writer.println(" public boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element) throws DatabaseException{"); fw.writer.println(" "+getOntologyImport()); fw.writer.println(" graph.claim(parent.getData(), "+this.ontShort+getName(complexTypeObj,"has")+", element.getData());"); fw.writer.println(" return true;"); @@ -274,7 +188,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.writer.println(" }"); fw.writer.println(" @Override"); - fw.writer.println(" public boolean connectChild(WriteGraph graph, Element element, Element child) throws DatabaseException{"); + fw.writer.println(" public boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException{"); fw.writer.println(" "+getOntologyImport()); if (stringWriter.getBuffer().length() > 0) { @@ -298,7 +212,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.delayedWriter2 = null; fw.writer.println(" @Override"); - fw.writer.println(" public void configure(WriteGraph graph, Deque parents, Element element) throws DatabaseException {"); + fw.writer.println(" public void configure(WriteGraph graph, Deque parents, ParserElement element) throws DatabaseException {"); if (inherited) { fw.writer.println(" super.configure(graph,parents,element);"); } @@ -321,30 +235,6 @@ public class ImporterGenerator extends SchemaConversionBase{ provider = null; } - @Override - protected void handle(SchemaObject parent, SchemaElement indicator, List elements) { - if (indicator.getType() == SchemaElement.ElementType.SEQUENCE || (indicator.getType() == SchemaElement.ElementType.CHOICE && indicator.getRestriction().many())) { - for (SchemaElement e : elements) { - handle(parent, indicator, e); - } - } else if (indicator.getType() == SchemaElement.ElementType.CHOICE) { - String name = getChoiceName(elements); - - for (SchemaElement e : elements) { - Element localElement = e.getElement(); - if (localElement.getName() != null) { - QName refType = localElement.getType(); - if (refType != null) - handleIndicator(parent, indicator, e, false, name, refType); - } else if (localElement.getRef() != null) { - QName refType = localElement.getRef(); - handleIndicator(parent, indicator, e, true, name, refType); - } - } - } - - } - @Override protected void handleIndicator(SchemaObject parent, SchemaElement indicator, SchemaElement element, boolean reference, String ref, QName refType) { FileWriter fw = getWriter(parent); @@ -352,15 +242,7 @@ public class ImporterGenerator extends SchemaConversionBase{ if (binding == null) { SchemaObject refElement = elementName.get(refType.getLocalPart()); SchemaObject refComplexType = complexTypeName.get(refType.getLocalPart()); -// String className = refType.getLocalPart(); -// if (!isElementRef(refType.getLocalPart())) { -// className = "_"+className; -// } -// -// String refClassName = refType.getLocalPart(); -// if (isComplexTypeRef(refClassName)) { -// refClassName = "_"+refClassName; -// } + String className = null; String refClassName = null; if (refElement != null) @@ -399,12 +281,10 @@ public class ImporterGenerator extends SchemaConversionBase{ if (useOriginalList(parent, indicator,element, reference, ref, refType)) { // generic list fw.delayedWriter.println(" {"); - //fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(),"+ontShort+"XML_hasOriginalElementList);"); fw.delayedWriter.println(" XMLResource XML = XMLResource.getInstance(graph);"); fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(), XML.hasOriginalElementList);"); fw.delayedWriter.println(" if (list == null) {"); fw.delayedWriter.println(" list = org.simantics.db.common.utils.ListUtils.create(graph, java.util.Collections.singletonList(child.getData()));"); - //fw.delayedWriter.println(" graph.claim(element.getData(),"+ontShort+"XML_hasOriginalElementList,list);"); fw.delayedWriter.println(" graph.claim(element.getData(), XML.hasOriginalElementList,list);"); fw.delayedWriter.println(" } else {"); fw.delayedWriter.println(" org.simantics.db.common.utils.ListUtils.insertBack(graph, list, java.util.Collections.singletonList(child.getData()));"); @@ -431,18 +311,8 @@ public class ImporterGenerator extends SchemaConversionBase{ FileWriter fw = getWriter(parent); SchemaObject obj = getWithObj(parent, attrs); -// String className = refType.getLocalPart(); -// if (!isElementRef(refType.getLocalPart())) { -// className = "_"+className; -// } -// -// String refClassName = refType.getLocalPart(); -// if (isComplexTypeRef(refClassName)) { -// refClassName = "_"+refClassName; -// } String className = getName(obj); - - + if (!reference) fw.writer.println(" addParser(\""+ ref +"\", "+className+".class);"); else @@ -466,12 +336,10 @@ public class ImporterGenerator extends SchemaConversionBase{ if (useOriginalList(parent, indicator,element, reference, ref, new QName(obj.getName()))) { // generic list fw.delayedWriter.println(" {"); - //fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(),"+ontShort+"XML_hasOriginalElementList);"); fw.delayedWriter.println(" XMLResource XML = XMLResource.getInstance(graph);"); fw.delayedWriter.println(" Resource list = graph.getPossibleObject(element.getData(), XML.hasOriginalElementList);"); fw.delayedWriter.println(" if (list == null) {"); fw.delayedWriter.println(" list = org.simantics.db.common.utils.ListUtils.create(graph, java.util.Collections.singletonList(child.getData()));"); - //fw.delayedWriter.println(" graph.claim(element.getData(),"+ontShort+"XML_hasOriginalElementList,list);"); fw.delayedWriter.println(" graph.claim(element.getData(), XML.hasOriginalElementList,list);"); fw.delayedWriter.println(" } else {"); fw.delayedWriter.println(" org.simantics.db.common.utils.ListUtils.insertBack(graph, list, java.util.Collections.singletonList(child.getData()));"); @@ -486,9 +354,10 @@ public class ImporterGenerator extends SchemaConversionBase{ @Override protected void handleIndicator(SchemaObject parent, SchemaElement indicator, SchemaElement any) { + // generates overriding method that allows parsing any element FileWriter fw = getWriter(parent); fw.delayedWriter2.println(" @Override"); - fw.delayedWriter2.println(" public Class getParser(java.util.Map parsers, Element element, Element child) {"); + fw.delayedWriter2.println(" public Class getParser(java.util.Map parsers, ParserElement element, ParserElement child) {"); fw.delayedWriter2.println(" Class parserClass = super.getParser(parsers, element, child);"); fw.delayedWriter2.println(" if (parserClass != null) return parserClass;"); fw.delayedWriter2.println(" org.simantics.xml.sax.base.XMLElementParser parser = parsers.get(child.getQName());"); @@ -496,19 +365,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.delayedWriter2.println(" return null;"); fw.delayedWriter2.println(" }"); } - - private FileWriter getWriter(SchemaObject obj) { - SchemaObject s = obj; - while (s != null) { - FileWriter fw = writers.get(s); - if (fw != null) - return fw; - s = s.getParent(); - } - return null; - } - - + @Override protected void handle(SchemaObject parent, Attribute attribute) { String name = attribute.getName(); @@ -610,7 +467,7 @@ public class ImporterGenerator extends SchemaConversionBase{ //String binding = getBindingFromPrimitiveType(base); TypeEntry binding = getTypeEntry(base); fw.writer.println(" @Override"); - fw.writer.println(" public void configure(WriteGraph graph, Element element, java.lang.String value) throws DatabaseException {"); + fw.writer.println(" public void configure(WriteGraph graph, ParserElement element, java.lang.String value) throws DatabaseException {"); //fw.writer.println(" graph.claimValue(element.getData(),"+getValueGetter(binding)+", Bindings."+binding+");"); fw.writer.println(" graph.claimValue(element.getData(),"+getValueGetter(binding)+", "+binding.binding +");"); fw.writer.println(" }"); @@ -700,8 +557,7 @@ public class ImporterGenerator extends SchemaConversionBase{ protected void handleSimpleType(SchemaObject parent, SchemaObject simpleType) { } - - + IDProvider provider; @Override @@ -736,7 +592,7 @@ public class ImporterGenerator extends SchemaConversionBase{ writeClass(fw.writer,false, element.getName(), className, inhertiance.baseClass, intrerfaces); writeIDProvider(fw.writer); fw.writer.println(" @Override"); - fw.writer.println(" public Resource create(WriteGraph graph, Element element) throws DatabaseException{"); + fw.writer.println(" public Resource create(WriteGraph graph, ParserElement element) throws DatabaseException{"); fw.writer.println(" Layer0 L0 = Layer0.getInstance(graph);"); fw.writer.println(" "+getOntologyImport()); if (!isList) { @@ -750,7 +606,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.writer.println(); fw.writer.println(" @Override"); - fw.writer.println(" public boolean connectParent(WriteGraph graph, Element parent, Element element) throws DatabaseException{"); + fw.writer.println(" public boolean connectParent(WriteGraph graph, ParserElement parent, ParserElement element) throws DatabaseException{"); fw.writer.println(" "+getOntologyImport()); fw.writer.println(" graph.claim(parent.getData(), "+this.ontShort+getName(elementObj,"has")+", element.getData());"); fw.writer.println(" return true;"); @@ -758,7 +614,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.writer.println(); fw.writer.println(" @Override"); - fw.writer.println(" public void configure(WriteGraph graph, Deque parents, Element element) throws DatabaseException {"); + fw.writer.println(" public void configure(WriteGraph graph, Deque parents, ParserElement element) throws DatabaseException {"); if (inhertiance.type == InheritanceType.ComplexType) { fw.writer.println(" super.configure(graph,parents,element);"); } @@ -776,14 +632,14 @@ public class ImporterGenerator extends SchemaConversionBase{ if (inhertiance.type == InheritanceType.AtomicType) { fw.writer.println(); fw.writer.println(" @Override"); - fw.writer.println(" public void configure(WriteGraph graph, Element element, java.lang.String string) throws DatabaseException {"); + fw.writer.println(" public void configure(WriteGraph graph, ParserElement element, java.lang.String string) throws DatabaseException {"); fw.writer.println(" graph.claimValue(element.getData(), "+getValueGetter(inhertiance.atomicType,"string")+", "+inhertiance.atomicType.binding+");"); fw.writer.println(" }"); } - if (simpleType != null) { - SchemaObject obj = simpleTypes.get(simpleType); - handleElementSimpleTypeAttributes(obj); - } +// if (simpleType != null) { +// SchemaObject obj = simpleTypes.get(simpleType); +// handleElementSimpleTypeAttributes(obj); +// } StringWriter stringWriter = new StringWriter(); @@ -804,7 +660,7 @@ public class ImporterGenerator extends SchemaConversionBase{ fw.writer.println(" }"); fw.writer.println(" @Override"); - fw.writer.println(" public boolean connectChild(WriteGraph graph, Element element, Element child) throws DatabaseException{"); + fw.writer.println(" public boolean connectChild(WriteGraph graph, ParserElement element, ParserElement child) throws DatabaseException{"); fw.writer.println(" "+getOntologyImport()); if (stringWriter.getBuffer().length() > 0) { @@ -842,99 +698,7 @@ public class ImporterGenerator extends SchemaConversionBase{ ruleClassNames.add(converter.getPluginName()+"."+elementPackageName+"."+name); } - - private enum InheritanceType{ComplexType,AtomicType,None}; - - private class Inheritance { - public String baseClass; - public InheritanceType type; - public TypeEntry atomicType; - - public Inheritance() { - baseClass = "org.simantics.xml.sax.base.XMLElementNamedChildParserBase"; - type = InheritanceType.None; - } - } - - private Inheritance getElementInheritance(SchemaObject topLevelElementObj) { - Element topLevelElement = topLevelElementObj.getElement(); - Inheritance inheritance = new Inheritance(); - if (topLevelElement.getType() != null) { - QName type = topLevelElement.getType(); - if (!type.getNamespaceURI().equals(SCHEMA_NS)) { - SchemaObject obj = complexTypeName.get(type.getLocalPart()); -// if (obj == null) -// obj = simpleTypeName.get(type.getLocalPart()); - if (obj != null) { - inheritance.baseClass = getName(obj); - inheritance.type = InheritanceType.ComplexType; - } - } else { - TypeEntry entry = getTypeEntry(type); - if (entry != null) { - inheritance.type = InheritanceType.AtomicType; - inheritance.atomicType = entry; - } - } - } - if (inheritance.type == InheritanceType.None) { - QName type = getElementBase(topLevelElement); - if (type != null) { - if (!type.getNamespaceURI().equals(SCHEMA_NS)) { - SchemaObject obj = getWithName(topLevelElementObj, type.getLocalPart()); - inheritance.baseClass = getName(obj); - inheritance.type = InheritanceType.ComplexType; - } else { - TypeEntry entry = getTypeEntry(type); - if (entry != null) { - inheritance.type = InheritanceType.AtomicType; - inheritance.atomicType = entry; - } - } - } - } - if (inheritance.type == InheritanceType.None) { - QName type = topLevelElement.getSubstitutionGroup(); - if (type != null) { - if (!type.getNamespaceURI().equals(SCHEMA_NS)) { - SchemaObject obj = getWithName(topLevelElementObj, type.getLocalPart()); - inheritance.baseClass = getName(obj); - inheritance.type = InheritanceType.ComplexType; - } else { - TypeEntry entry = getTypeEntry(type); - if (entry != null) { - inheritance.type = InheritanceType.AtomicType; - inheritance.atomicType = entry; - } - } - } - } - - return inheritance; - } - - private void writeClass(PrintWriter writer,boolean abst, String name, String className, String baseClass, List interfaces) { - writer.println("@SuppressWarnings(\"unused\")"); - writer.print("public " +(abst ? "abstract " : "") + "class " + className + " extends "+baseClass); - if (interfaces.size() > 0) { - writer.print(" implements "); - for (int i = 0; i < interfaces.size(); i++) { - writer.print(interfaces.get(i)); - if (i < interfaces.size() -1 ) - writer.print(","); - } - } - writer.println("{"); - writer.println(); - writer.println(" @Override"); - writer.println(" public java.lang.String getElementId() {"); - if (name != null) - writer.println(" return \""+name+"\";"); - else // complex types cannot be parsed directly with name/id reference. - writer.println(" return null;"); - writer.println(" }"); - writer.println(); - } + private void writeIDProvider(PrintWriter writer) { if (provider != null) { @@ -959,14 +723,14 @@ public class ImporterGenerator extends SchemaConversionBase{ private void writeIDReferences(PrintWriter writer,String name, List references) { if (references.size() > 0) { writer.println(" @Override"); - writer.println(" public boolean connectReferences(WriteGraph graph, Element element, java.util.Map map) throws DatabaseException {"); + writer.println(" public boolean connectReferences(WriteGraph graph, ParserElement element, java.util.Map map) throws DatabaseException {"); writer.println(" "+getOntologyImport()); writer.println(" boolean result = true;"); for (IDReference ref : references) { writer.println(" {"); writer.println(" Attribute a = element.getAttribute(\"" + ref.getIDSource().getName() +"\");"); writer.println(" if (a != null) {"); - writer.println(" Element refEle = map.get(a.value);"); + writer.println(" ParserElement refEle = map.get(a.value);"); writer.println(" if (refEle != null) {"); writer.println(" Resource ref = refEle.getData();"); writer.println(" graph.claim(element.getData(), "+ontShort+name+"_"+ref.getReference().getName()+", ref);"); @@ -987,13 +751,18 @@ public class ImporterGenerator extends SchemaConversionBase{ return; writer.println(" @Override"); - writer.println(" public void configureChild(WriteGraph graph, Deque parents, Element element, Element child) throws DatabaseException {"); + writer.println(" public void configureChild(WriteGraph graph, Deque parents, ParserElement element, ParserElement child) throws DatabaseException {"); writer.println(" " + unknownChildElement.getJavaMethod()); writer.println(" }"); writer.println(); } + @Override + protected String getBaseClass() { + return "org.simantics.xml.sax.base.XMLElementNamedChildParserBase"; + } + protected void createClassHeader(PrintWriter writer, boolean isList) { writer.println("package " + converter.getPluginName() +"."+elementPackageName+";"); writer.println(); @@ -1003,7 +772,7 @@ public class ImporterGenerator extends SchemaConversionBase{ writer.println("import org.simantics.db.WriteGraph;"); writer.println("import org.simantics.db.exception.DatabaseException;"); writer.println("import org.simantics.xml.sax.base.Attribute;"); - writer.println("import org.simantics.xml.sax.base.Element;"); + writer.println("import org.simantics.xml.sax.base.ParserElement;"); writer.println("import org.simantics.xml.sax.ontology.XMLResource;"); if (!isList) { writer.println("import org.simantics.layer0.Layer0;"); @@ -1014,93 +783,4 @@ public class ImporterGenerator extends SchemaConversionBase{ writer.println(); } - private String getOntologyImport() { - return this.ontologyClassName+" " +ontShort.substring(0, 3)+" = "+this.ontologyClassName+".getInstance(graph);"; - } - - - private static class FileWriter { - public PrintWriter writer; - - public PrintWriter delayedWriter; - public PrintWriter delayedWriter2; - } - - public static String getName(SchemaObject obj) { - if (obj.getParent() == null) { - switch (obj.getType()) { - case COMPLEX_TYPE: - return getComplexTypePrefix()+obj.getName(); - case ELEMENT: - return obj.getName(); - case ATTRIBUTE_GROUP: - return getAttributeGroupPrefix()+obj.getName(); - case SIMPLE_TYPE: - return obj.getName(); - } - } else { - SchemaObject o = obj; - SchemaObject prev = null; - String name = ""; - while (o != null){ - if (o.getName() != null) - name = o.getName()+"_"+name; - prev = o; - o = o.getParent(); - if (prev.getObj() instanceof AttributeGroupRef) - o = null; - } - name = name.substring(0, name.length()-1); - switch (prev.getType()) { - case COMPLEX_TYPE: - return getComplexTypePrefix()+name; - case ELEMENT: - return name; - case ATTRIBUTE_GROUP: - return getAttributeGroupPrefix()+name; - case SIMPLE_TYPE: - return name; - } - } - throw new RuntimeException(); - - } - - public static String getName(SchemaObject obj, String rel) { - if (obj.getParent() == null) { - switch (obj.getType()) { - case COMPLEX_TYPE: - return getComplexTypePrefix()+rel+obj.getName(); - case ELEMENT: - return rel+obj.getName(); - case ATTRIBUTE_GROUP: - return getAttributeGroupPrefix()+rel+obj.getName(); - case SIMPLE_TYPE: - return rel+obj.getName(); - } - } else { - SchemaObject o = obj; - SchemaObject prev = null; - String name = ""; - while (o != null){ - if (o.getName() != null) - name = o.getName()+"_"+name; - prev = o; - o = o.getParent(); - } - name = name.substring(0, name.length()-1); - switch (prev.getType()) { - case COMPLEX_TYPE: - return getComplexTypePrefix()+rel+name; - case ELEMENT: - return rel+name; - case ATTRIBUTE_GROUP: - return getAttributeGroupPrefix()+rel+name; - case SIMPLE_TYPE: - return rel+name; - } - } - throw new RuntimeException(); - - } } diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/JavaGenerator.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/JavaGenerator.java new file mode 100644 index 0000000..6467734 --- /dev/null +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/JavaGenerator.java @@ -0,0 +1,314 @@ +package org.simantics.xml.sax; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.simantics.xml.sax.configuration.Configuration; +import org.w3._2001.xmlschema.AttributeGroupRef; +import org.w3._2001.xmlschema.Element; +import org.w3._2001.xmlschema.Schema; + +public abstract class JavaGenerator extends SchemaConversionBase{ + + String commentTag = "//"; + + Schema schema; + String ontologyClassName; + SchemaConverter converter; + + List ruleClassNames = new ArrayList(); + + String ontShort = "ONT"; + + File importParserDir; + String elementPackageName; + + Map writers = new HashMap(); + + public JavaGenerator(Configuration configuration) { + super(configuration); + } + + + protected PrintWriter createFile(File file) throws IOException { + if (!file.exists()) + file.createNewFile(); + PrintWriter writer = new PrintWriter(file); + for (String s : converter.getHeader()) { + writer.println(commentTag + " " + s); + } + writer.println(); + return writer; + } + + protected String getValueGetterMethod(TypeEntry binding,String name) { + if (binding == null) + return name+".getValue()"; + return binding.getValueGetterMethod(name); + } + + protected String getValueGetter(TypeEntry binding,String name) { + if (binding == null) + return name; + return binding.getValueGetter(name); + } + protected String getValueGetter(TypeEntry binding) { + if (binding == null) + return "value"; + return binding.getValueGetter(); + } + + public static String getComplexTypePrefix() { + return "ComplexTypes_"; + } + + public static String getAttributeGroupPrefix() { + return "AttributeGroups_"; + } + + @Override + protected void handle(SchemaObject parent, SchemaElement indicator, SchemaElement element) { + Element localElement = element.getElement(); + if (localElement.getName() != null) { + SchemaObject eObj = elements.get(localElement); + String refName = localElement.getName(); + QName refType = localElement.getType(); + if (refType != null) + handleIndicator(parent, indicator, element, false, refName, refType); + else { + handleElement(eObj); + handleIndicator(parent, indicator, element, false, refName, localElement); + } + } else if (localElement.getRef() != null) { + QName refType = localElement.getRef(); + handleIndicator(parent, indicator,element, true, refType.getLocalPart(), refType); + } + } + + @Override + protected void handle(SchemaObject parent, SchemaElement indicator, List elements) { + if (indicator.getType() == SchemaElement.ElementType.SEQUENCE || (indicator.getType() == SchemaElement.ElementType.CHOICE && indicator.getRestriction().many())) { + for (SchemaElement e : elements) { + handle(parent, indicator, e); + } + } else if (indicator.getType() == SchemaElement.ElementType.CHOICE) { + String name = getChoiceName(elements); + + for (SchemaElement e : elements) { + Element localElement = e.getElement(); + if (localElement.getName() != null) { + QName refType = localElement.getType(); + if (refType != null) + handleIndicator(parent, indicator, e, false, name, refType); + } else if (localElement.getRef() != null) { + QName refType = localElement.getRef(); + handleIndicator(parent, indicator, e, true, name, refType); + } + } + } + + } + + protected String getOntologyImport() { + return this.ontologyClassName+" " +ontShort.substring(0, 3)+" = "+this.ontologyClassName+".getInstance(graph);"; + } + + protected static class FileWriter { + public PrintWriter writer; + + public PrintWriter delayedWriter; + public PrintWriter delayedWriter2; + } + + protected FileWriter getWriter(SchemaObject obj) { + SchemaObject s = obj; + while (s != null) { + FileWriter fw = writers.get(s); + if (fw != null) + return fw; + s = s.getParent(); + } + return null; + } + + + public static String getName(SchemaObject obj) { + if (obj.getParent() == null) { + switch (obj.getType()) { + case COMPLEX_TYPE: + return getComplexTypePrefix()+obj.getName(); + case ELEMENT: + return obj.getName(); + case ATTRIBUTE_GROUP: + return getAttributeGroupPrefix()+obj.getName(); + case SIMPLE_TYPE: + return obj.getName(); + } + } else { + SchemaObject o = obj; + SchemaObject prev = null; + String name = ""; + while (o != null){ + if (o.getName() != null) + name = o.getName()+"_"+name; + prev = o; + o = o.getParent(); + if (prev.getObj() instanceof AttributeGroupRef) + o = null; + } + name = name.substring(0, name.length()-1); + switch (prev.getType()) { + case COMPLEX_TYPE: + return getComplexTypePrefix()+name; + case ELEMENT: + return name; + case ATTRIBUTE_GROUP: + return getAttributeGroupPrefix()+name; + case SIMPLE_TYPE: + return name; + } + } + throw new RuntimeException(); + + } + + public static String getName(SchemaObject obj, String rel) { + if (obj.getParent() == null) { + switch (obj.getType()) { + case COMPLEX_TYPE: + return getComplexTypePrefix()+rel+obj.getName(); + case ELEMENT: + return rel+obj.getName(); + case ATTRIBUTE_GROUP: + return getAttributeGroupPrefix()+rel+obj.getName(); + case SIMPLE_TYPE: + return rel+obj.getName(); + } + } else { + SchemaObject o = obj; + SchemaObject prev = null; + String name = ""; + while (o != null){ + if (o.getName() != null) + name = o.getName()+"_"+name; + prev = o; + o = o.getParent(); + } + name = name.substring(0, name.length()-1); + switch (prev.getType()) { + case COMPLEX_TYPE: + return getComplexTypePrefix()+rel+name; + case ELEMENT: + return rel+name; + case ATTRIBUTE_GROUP: + return getAttributeGroupPrefix()+rel+name; + case SIMPLE_TYPE: + return rel+name; + } + } + throw new RuntimeException(); + } + + protected enum InheritanceType{ComplexType,AtomicType,None}; + + protected class Inheritance { + public String baseClass; + public InheritanceType type; + public TypeEntry atomicType; + + public Inheritance(String baseClass) { + this.baseClass = baseClass; + this.type = InheritanceType.None; + } + } + + protected void writeClass(PrintWriter writer,boolean abst, String name, String className, String baseClass, List interfaces) { + writer.println("@SuppressWarnings(\"unused\")"); + writer.print("public " +(abst ? "abstract " : "") + "class " + className + " extends "+baseClass); + if (interfaces.size() > 0) { + writer.print(" implements "); + for (int i = 0; i < interfaces.size(); i++) { + writer.print(interfaces.get(i)); + if (i < interfaces.size() -1 ) + writer.print(","); + } + } + writer.println("{"); + writer.println(); + writer.println(" @Override"); + writer.println(" public java.lang.String getElementId() {"); + if (name != null) + writer.println(" return \""+name+"\";"); + else // complex types cannot be parsed directly with name/id reference. + writer.println(" return null;"); + writer.println(" }"); + writer.println(); + } + + protected abstract String getBaseClass(); + + protected Inheritance getElementInheritance(SchemaObject topLevelElementObj) { + Element topLevelElement = topLevelElementObj.getElement(); + Inheritance inheritance = new Inheritance(getBaseClass()); + if (topLevelElement.getType() != null) { + QName type = topLevelElement.getType(); + if (!type.getNamespaceURI().equals(SCHEMA_NS)) { + SchemaObject obj = complexTypeName.get(type.getLocalPart()); +// if (obj == null) +// obj = simpleTypeName.get(type.getLocalPart()); + if (obj != null) { + inheritance.baseClass = getName(obj); + inheritance.type = InheritanceType.ComplexType; + } + } else { + TypeEntry entry = getTypeEntry(type); + if (entry != null) { + inheritance.type = InheritanceType.AtomicType; + inheritance.atomicType = entry; + } + } + } + if (inheritance.type == InheritanceType.None) { + QName type = getElementBase(topLevelElement); + if (type != null) { + if (!type.getNamespaceURI().equals(SCHEMA_NS)) { + SchemaObject obj = getWithName(topLevelElementObj, type.getLocalPart()); + inheritance.baseClass = getName(obj); + inheritance.type = InheritanceType.ComplexType; + } else { + TypeEntry entry = getTypeEntry(type); + if (entry != null) { + inheritance.type = InheritanceType.AtomicType; + inheritance.atomicType = entry; + } + } + } + } + if (inheritance.type == InheritanceType.None) { + QName type = topLevelElement.getSubstitutionGroup(); + if (type != null) { + if (!type.getNamespaceURI().equals(SCHEMA_NS)) { + SchemaObject obj = getWithName(topLevelElementObj, type.getLocalPart()); + inheritance.baseClass = getName(obj); + inheritance.type = InheritanceType.ComplexType; + } else { + TypeEntry entry = getTypeEntry(type); + if (entry != null) { + inheritance.type = InheritanceType.AtomicType; + inheritance.atomicType = entry; + } + } + } + } + + return inheritance; + } + +} diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/OntologyGenerator.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/OntologyGenerator.java index 095de9d..2871562 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/OntologyGenerator.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/OntologyGenerator.java @@ -37,20 +37,22 @@ public class OntologyGenerator extends SchemaConversionBase { String commentTag = "//"; Schema schema; - + String ontologyName; String className; SchemaConverter converter; PrintWriter writer = null; - public String getClassName() { - return className; - } - public void createOntology(Schema schema, SchemaConverter converter) throws FileNotFoundException { + + + + public void createOntology(Schema schema, String ontologyName, String className, SchemaConverter converter) throws FileNotFoundException { this.schema = schema; this.converter = converter; + this.ontologyName = ontologyName; + this.className = className; // for (OpenAttrs attrs : schema.getIncludeOrImportOrRedefine()) { // if (attrs instanceof Annotation) { @@ -83,26 +85,13 @@ public class OntologyGenerator extends SchemaConversionBase { } protected void handle(Schema schema) { - String ontologyName = schema.getTargetNamespace(); - if (ontologyName == null) { - ontologyName = converter.getSchemaFile().getName(); - - int index = ontologyName.lastIndexOf("."); - if (index > 0) - ontologyName = ontologyName.substring(0, index); - } - if (!ontologyName.startsWith("http")) - ontologyName = "http://" + ontologyName; String parts[] = ontologyName.split("/"); String name = parts[parts.length-1]; ontRoot = name.substring(0, Math.min(3, name.length())).toUpperCase(); String version = schema.getVersion(); if (version == null) version = "1.0"; - - name = name.replaceAll("\\.", "_"); - name = name.replaceAll(" ", "_"); - className = converter.getPluginName() + "." + name; + for (String s : converter.getHeader()) { writer.println(commentTag + " " + s); @@ -467,11 +456,8 @@ public class OntologyGenerator extends SchemaConversionBase { Element element = elementObj.getElement(); String name = getName(elementObj);//element.getName(); -// if ("Presentation".equals(name)) -// System.out.println(); - -// if (parent != null) -// name = parent +"_"+name; + if ("Text".equals(name)) + System.out.println(); String type = "XML.Element"; Set types = new LinkedHashSet(); diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConversionBase.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConversionBase.java index bcff698..600d13f 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConversionBase.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConversionBase.java @@ -2,7 +2,6 @@ package org.simantics.xml.sax; import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Base64; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -21,6 +20,7 @@ import org.simantics.xml.sax.configuration.Configuration; import org.simantics.xml.sax.configuration.IDProvider; import org.simantics.xml.sax.configuration.IDReference; import org.simantics.xml.sax.configuration.OrderedChild; +import org.simantics.xml.sax.configuration.Rename; import org.simantics.xml.sax.configuration.UnrecognizedChildElement; import org.w3._2001.xmlschema.All; import org.w3._2001.xmlschema.Annotated; @@ -63,38 +63,38 @@ public abstract class SchemaConversionBase { Map l0Types = new HashMap(); typeMap.put(CONVERSION_NS, l0Types); - schemaTypes.put("string", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","")); - schemaTypes.put("NMTOKEN", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","")); - schemaTypes.put("token", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","")); - schemaTypes.put("ID", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","",true)); - schemaTypes.put("IDREF", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","")); - schemaTypes.put("date", new TypeEntry("XML.Date", "org.simantics.xml.sax.base.datatypes.literal.Date.BINDING", "org.simantics.xml.sax.base.datatypes.literal.Date", "","org.simantics.xml.sax.base.datatypes.literal.Date.parseDate(",")")); - schemaTypes.put("time", new TypeEntry("XML.Time", "org.simantics.xml.sax.base.datatypes.literal.Time.BINDING", "org.simantics.xml.sax.base.datatypes.literal.Time", "","org.simantics.xml.sax.base.datatypes.literal.Time.parseTime(",")")); - schemaTypes.put("dateTime", new TypeEntry("XML.DateTime", "org.simantics.xml.sax.base.datatypes.literal.DateTime.BINDING", "org.simantics.xml.sax.base.datatypes.literal.DateTime", "","org.simantics.xml.sax.base.datatypes.literal.DateTime.parseDateTime(",")")); - schemaTypes.put("anyURI", new TypeEntry("L0.URI", "Bindings.STRING", "java.lang.String", "","","")); - schemaTypes.put("double", new TypeEntry("L0.Double", "Bindings.DOUBLE", "double", "java.lang.Double.NaN","java.lang.Double.parseDouble(",")")); - schemaTypes.put("float", new TypeEntry("L0.Float", "Bindings.FLOAT", "float", "java.lang.Float.NaN","java.lang.Float.parseFloat(",")")); - schemaTypes.put("decimal", new TypeEntry("L0.Double", "Bindings.DOUBLE", "double", "java.lang.Double.NaN","java.lang.Double.parseDouble(",")")); - schemaTypes.put("boolean", new TypeEntry("L0.Boolean", "Bindings.BOOLEAN", "boolean", "false","java.lang.Boolean.parseBoolean(",")")); - schemaTypes.put("integer", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("positiveInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("nonPositiveInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("nonNegativeInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("negativeInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("unsignedInt", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("int", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("short", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("unsignedShort",new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")")); - schemaTypes.put("byte", new TypeEntry("L0.Byte", "Bindings.BYTE", "byte", "0","java.lang.Byte.parseByte(",")")); - schemaTypes.put("unsignedByte", new TypeEntry("L0.Byte", "Bindings.BYTE", "byte", "0","java.lang.Byte.parseByte(",")")); - schemaTypes.put("long", new TypeEntry("L0.Long", "Bindings.LONG", "long", "0","java.lang.Long.parseLong(",")")); - schemaTypes.put("unsignedLong", new TypeEntry("L0.Long", "Bindings.LONG", "long", "0","java.lang.Long.parseLong(",")")); - schemaTypes.put("base64Binary", new TypeEntry("L0.ByteArray", "Bindings.BYTE_ARRAY", "byte[]", "new byte[0]","",".getBytes(org.simantics.databoard.util.binary.UTF8.CHARSET)")); + schemaTypes.put("string", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","","","")); + schemaTypes.put("NMTOKEN", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","","","")); + schemaTypes.put("token", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","","","")); + schemaTypes.put("ID", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","","","",true)); + schemaTypes.put("IDREF", new TypeEntry("L0.String", "Bindings.STRING", "java.lang.String", "","","","","")); + schemaTypes.put("date", new TypeEntry("XML.Date", "org.simantics.xml.sax.base.datatypes.literal.Date.BINDING", "org.simantics.xml.sax.base.datatypes.literal.Date", "","org.simantics.xml.sax.base.datatypes.literal.Date.parseDate(",")","(",").toString()")); + schemaTypes.put("time", new TypeEntry("XML.Time", "org.simantics.xml.sax.base.datatypes.literal.Time.BINDING", "org.simantics.xml.sax.base.datatypes.literal.Time", "","org.simantics.xml.sax.base.datatypes.literal.Time.parseTime(",")","(",").toString()")); + schemaTypes.put("dateTime", new TypeEntry("XML.DateTime", "org.simantics.xml.sax.base.datatypes.literal.DateTime.BINDING", "org.simantics.xml.sax.base.datatypes.literal.DateTime", "","org.simantics.xml.sax.base.datatypes.literal.DateTime.parseDateTime(",")","(",").toString()")); + schemaTypes.put("anyURI", new TypeEntry("L0.URI", "Bindings.STRING", "java.lang.String", "","","","","")); + schemaTypes.put("double", new TypeEntry("L0.Double", "Bindings.DOUBLE", "double", "java.lang.Double.NaN","java.lang.Double.parseDouble(",")","java.lang.Double.toString(",")")); + schemaTypes.put("float", new TypeEntry("L0.Float", "Bindings.FLOAT", "float", "java.lang.Float.NaN","java.lang.Float.parseFloat(",")","java.lang.Float.toString(",")")); + schemaTypes.put("decimal", new TypeEntry("L0.Double", "Bindings.DOUBLE", "double", "java.lang.Double.NaN","java.lang.Double.parseDouble(",")","java.lang.Double.toString(",")")); + schemaTypes.put("boolean", new TypeEntry("L0.Boolean", "Bindings.BOOLEAN", "boolean", "false","java.lang.Boolean.parseBoolean(",")","java.lang.Boolean.toString(",")")); + schemaTypes.put("integer", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("positiveInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("nonPositiveInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("nonNegativeInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("negativeInteger", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("unsignedInt", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("int", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("short", new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("unsignedShort",new TypeEntry("L0.Integer", "Bindings.INTEGER", "int", "0","java.lang.Integer.parseInt(",")","java.lang.Integer.toString(",")")); + schemaTypes.put("byte", new TypeEntry("L0.Byte", "Bindings.BYTE", "byte", "0","java.lang.Byte.parseByte(",")","java.lang.Byte.toString(",")")); + schemaTypes.put("unsignedByte", new TypeEntry("L0.Byte", "Bindings.BYTE", "byte", "0","java.lang.Byte.parseByte(",")","java.lang.Byte.toString(",")")); + schemaTypes.put("long", new TypeEntry("L0.Long", "Bindings.LONG", "long", "0","java.lang.Long.parseLong(",")","java.lang.Long.toString(",")")); + schemaTypes.put("unsignedLong", new TypeEntry("L0.Long", "Bindings.LONG", "long", "0","java.lang.Long.parseLong(",")","java.lang.Long.toString(",")")); + schemaTypes.put("base64Binary", new TypeEntry("L0.ByteArray", "Bindings.BYTE_ARRAY", "byte[]", "new byte[0]","",".getBytes(org.simantics.databoard.util.binary.UTF8.CHARSET)","new java.lang.String(",", org.simantics.databoard.util.binary.UTF8.CHARSET)")); - l0Types.put("doubleArray", new TypeEntry("L0.DoubleArray", "Bindings.DOUBLE_ARRAY", "double[]", null,null,null)); - l0Types.put("stringArray", new TypeEntry("L0.StringArray", "Bindings.STRING_ARRAY", "string[]", null,null,null)); + l0Types.put("doubleArray", new TypeEntry("L0.DoubleArray", "Bindings.DOUBLE_ARRAY", "double[]", null,null,null,"java.lang.Double.toString(",")")); + l0Types.put("stringArray", new TypeEntry("L0.StringArray", "Bindings.STRING_ARRAY", "string[]", null,null,null,"","")); } @@ -216,10 +216,12 @@ public abstract class SchemaConversionBase { if (attrs instanceof Element) { Element element = (Element)attrs; SchemaObject obj = new SchemaObject(element); + obj.setRename(getRename(element)); stack.push(obj); } else if (attrs instanceof ComplexType) { ComplexType complexType = (ComplexType)attrs; SchemaObject obj = new SchemaObject(complexType); + obj.setRename(getRename(complexType)); stack.push(obj); } else if (attrs instanceof SimpleType) { SimpleType simpleType = (SimpleType)attrs; @@ -287,7 +289,9 @@ public abstract class SchemaConversionBase { JAXBElement element = (JAXBElement)o; Object elemValue = element.getValue(); if (elemValue instanceof Element) { - stack.add(new SchemaObject(parent,(Element)elemValue)); + SchemaObject obj = new SchemaObject(parent,(Element)elemValue); + obj.setRename(getRename((Element)elemValue)); + stack.add(obj); } else if (elemValue instanceof All) { preload(parent,(All)elemValue, stack); } else if (elemValue instanceof ExplicitGroup) { @@ -509,7 +513,6 @@ public abstract class SchemaConversionBase { Object elemValue = element.getValue(); if (elemValue instanceof LocalElement) { LocalElement localElement = (LocalElement)elemValue; - elements.add(new SchemaElement(indicator,localElement, ElementType.ELEMENT)); } else if (elemValue instanceof All) { alls.add(new SchemaElement(indicator,(All)elemValue, ElementType.ALL)); @@ -603,14 +606,14 @@ public abstract class SchemaConversionBase { protected void handle(SchemaObject parent, SchemaElement indicator, SchemaElement element) { Element localElement = element.getElement(); if (localElement.getName() != null) { - String refName = localElement.getName(); + SchemaObject eObj = elements.get(localElement); // FIXME: handleIndicator should be refactored, not this methdof must be overridden in JavaGenerator to handle renaming of Elements properly + String refName = eObj.getName();//localElement.getName(); QName refType = localElement.getType(); if (refType != null) handleIndicator(parent, indicator, element, false, refName, refType); else { - handleElement(elements.get(localElement)); + handleElement(eObj); handleIndicator(parent, indicator, element, false, refName, localElement); - //FIXME: } } else if (localElement.getRef() != null) { QName refType = localElement.getRef(); @@ -814,11 +817,11 @@ public abstract class SchemaConversionBase { public UnrecognizedChildElement getUnknown(ComplexType complexType) { for (JAXBElement e : configuration.getConversionRule()) { if (e.getValue() instanceof UnrecognizedChildElement) { - UnrecognizedChildElement ref = (UnrecognizedChildElement)e.getValue(); - org.simantics.xml.sax.configuration.ComplexType complexType2 = ref.getComplexType(); + UnrecognizedChildElement rule = (UnrecognizedChildElement)e.getValue(); + org.simantics.xml.sax.configuration.ComplexType complexType2 = rule.getComplexType(); if (complexType2 != null) { if (complexType.getName().equals(complexType2.getName())) - return ref; + return rule; } } } @@ -828,17 +831,65 @@ public abstract class SchemaConversionBase { public UnrecognizedChildElement getUnknown(Element element) { for (JAXBElement e : configuration.getConversionRule()) { if (e.getValue() instanceof UnrecognizedChildElement) { - UnrecognizedChildElement ref = (UnrecognizedChildElement)e.getValue(); - org.simantics.xml.sax.configuration.Element element2 = ref.getElement(); + UnrecognizedChildElement rule = (UnrecognizedChildElement)e.getValue(); + org.simantics.xml.sax.configuration.Element element2 = rule.getElement(); if (element2 != null) { if (element.getName().equals(element2.getName())) - return ref; + return rule; } } } return null; } + public Rename getRename(Attribute element) { + for (JAXBElement e : configuration.getConversionRule()) { + if (e.getValue() instanceof Rename) { + Rename rule = (Rename)e.getValue(); + Object ref = rule.getElementOrComplexTypeOrAttribute().get(0); + if (!(ref instanceof org.simantics.xml.sax.configuration.Attribute)) + continue; + org.simantics.xml.sax.configuration.Attribute element2 = (org.simantics.xml.sax.configuration.Attribute)ref; + if (element2.getName().equals(element.getName())) { + return rule; + } + } + } + return null; + } + + public Rename getRename(ComplexType element) { + for (JAXBElement e : configuration.getConversionRule()) { + if (e.getValue() instanceof Rename) { + Rename rule = (Rename)e.getValue(); + Object ref = rule.getElementOrComplexTypeOrAttribute().get(0); + if (!(ref instanceof org.simantics.xml.sax.configuration.ComplexType)) + continue; + org.simantics.xml.sax.configuration.ComplexType element2 = (org.simantics.xml.sax.configuration.ComplexType)ref; + if (element2.getName().equals(element.getName())) { + return rule; + } + } + } + return null; + } + + public Rename getRename(Element element) { + for (JAXBElement e : configuration.getConversionRule()) { + if (e.getValue() instanceof Rename) { + Rename rule = (Rename)e.getValue(); + Object ref = rule.getElementOrComplexTypeOrAttribute().get(0); + if (!(ref instanceof org.simantics.xml.sax.configuration.Element)) + continue; + org.simantics.xml.sax.configuration.Element element2 = (org.simantics.xml.sax.configuration.Element)ref; + if (element2.getName().equals(element.getName())) { + return rule; + } + } + } + return null; + } + public boolean useOriginalList(SchemaObject parent, SchemaElement indicator, SchemaElement element, boolean reference, String ref, QName refType) { if (parent.getName() == null) @@ -942,7 +993,9 @@ public abstract class SchemaConversionBase { boolean id; String getterPrefix; String getterPostfix; - public TypeEntry(String l0Type, String binding, String javaType, String defaultValue, String getterPrefix, String getterPostfix) { + String stringPrefix; + String stringPostfix; + public TypeEntry(String l0Type, String binding, String javaType, String defaultValue, String getterPrefix, String getterPostfix, String stringPrefix, String stringPostfix) { super(); this.l0Type = l0Type; this.binding = binding; @@ -951,10 +1004,11 @@ public abstract class SchemaConversionBase { this.id = false; this.getterPrefix = getterPrefix; this.getterPostfix = getterPostfix; - + this.stringPrefix = stringPrefix; + this.stringPostfix = stringPostfix; } - public TypeEntry(String l0Type, String binding, String javaType, String defaultValue, String getterPrefix, String getterPostfix, boolean id) { + public TypeEntry(String l0Type, String binding, String javaType, String defaultValue, String getterPrefix, String getterPostfix, String stringPrefix, String stringPostfix, boolean id) { super(); this.l0Type = l0Type; this.binding = binding; @@ -963,6 +1017,8 @@ public abstract class SchemaConversionBase { this.id = id; this.getterPrefix = getterPrefix; this.getterPostfix = getterPostfix; + this.stringPrefix = stringPrefix; + this.stringPostfix = stringPostfix; } public String getValueGetterMethod(String name) { @@ -976,6 +1032,14 @@ public abstract class SchemaConversionBase { return getValueGetter("value"); } + public String getToString(String name) { + return stringPrefix +"("+javaType+")"+name+stringPostfix; + } + + public String getElementToString(String name) { + return stringPrefix + name+stringPostfix; + } + } } diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConverter.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConverter.java index 523788c..32ae167 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConverter.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaConverter.java @@ -33,6 +33,12 @@ public class SchemaConverter { private String[] header; + boolean createPGraph = true; + boolean createImporter = true; + boolean createExporter = true; + + + public void convertSchema(File schemaFile, File conversionFile, File outputPlugin) throws JAXBException, IOException { pluginName = outputPlugin.getName(); @@ -61,6 +67,18 @@ public class SchemaConverter { } + public void setCreateExporter(boolean createExporter) { + this.createExporter = createExporter; + } + + public void setCreateImporter(boolean createImporter) { + this.createImporter = createImporter; + } + + public void setCreatePGraph(boolean createPGraph) { + this.createPGraph = createPGraph; + } + private void convert() throws JAXBException, IOException { JAXBContext jc = JAXBContext.newInstance("org.w3._2001.xmlschema"); Unmarshaller u = jc.createUnmarshaller(); @@ -84,10 +102,37 @@ public class SchemaConverter { header[3] = "Date " + new Date().toString(); + String ontologyName = schema.getTargetNamespace(); + if (ontologyName == null) { + ontologyName = getSchemaFile().getName(); + + int index = ontologyName.lastIndexOf("."); + if (index > 0) + ontologyName = ontologyName.substring(0, index); + } + if (!ontologyName.startsWith("http")) + ontologyName = "http://" + ontologyName; + String parts[] = ontologyName.split("/"); + String name = parts[parts.length-1]; + //String ontRoot = name.substring(0, Math.min(3, name.length())).toUpperCase(); + + + name = name.replaceAll("\\.", "_"); + name = name.replaceAll(" ", "_"); + String className = getPluginName() + "." + name; + + if (createPGraph) { OntologyGenerator ontologyGenerator = new OntologyGenerator(configuration); - ontologyGenerator.createOntology(schema, this); + ontologyGenerator.createOntology(schema, ontologyName, className, this); + } + if (createImporter) { ImporterGenerator importerGenerator = new ImporterGenerator(configuration); - importerGenerator.createParser(schema, ontologyGenerator.getClassName(), this); + importerGenerator.createParser(schema, className, this); + } + if (createExporter) { + ExporterGenerator exporterGenerator = new ExporterGenerator(configuration); + exporterGenerator.createParser(schema, className, this); + } } public File getOntologyFile() { diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaObject.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaObject.java index 3b45c7e..c081b81 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaObject.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/SchemaObject.java @@ -1,5 +1,6 @@ package org.simantics.xml.sax; +import org.simantics.xml.sax.configuration.Rename; import org.w3._2001.xmlschema.AttributeGroup; import org.w3._2001.xmlschema.AttributeGroupRef; import org.w3._2001.xmlschema.ComplexType; @@ -14,11 +15,16 @@ public class SchemaObject { private SchemaObject parent; private ObjectType type; private OpenAttrs obj; + private Rename rename; public SchemaObject(Element element) { this(null,element); } + public void setRename(Rename rename) { + this.rename = rename; + } + public SchemaObject(ComplexType complexType) { this(null, complexType); } @@ -93,8 +99,12 @@ public class SchemaObject { else return ((AttributeGroupRef)obj).getRef().getLocalPart(); case COMPLEX_TYPE: + if (rename != null) + return rename.getName(); return ((ComplexType)obj).getName(); case ELEMENT: + if (rename != null) + return rename.getName(); return ((Element)obj).getName(); case SIMPLE_TYPE: return ((SimpleType)obj).getName(); diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Attribute.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Attribute.java index 91b9848..e161573 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Attribute.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Attribute.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/AttributeComposition.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/AttributeComposition.java index b6beb40..2e799dc 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/AttributeComposition.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/AttributeComposition.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ComplexType.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ComplexType.java index cd4d328..911303d 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ComplexType.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ComplexType.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Configuration.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Configuration.java index 1ab2be7..29be8b6 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Configuration.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Configuration.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // @@ -64,11 +64,12 @@ public class Configuration { *

* Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link OrderedChild }{@code >} - * {@link JAXBElement }{@code <}{@link IDReference }{@code >} - * {@link JAXBElement }{@code <}{@link AttributeComposition }{@code >} - * {@link JAXBElement }{@code <}{@link UnrecognizedChildElement }{@code >} * {@link JAXBElement }{@code <}{@link ConversionRule }{@code >} + * {@link JAXBElement }{@code <}{@link AttributeComposition }{@code >} + * {@link JAXBElement }{@code <}{@link Rename }{@code >} * {@link JAXBElement }{@code <}{@link IDProvider }{@code >} + * {@link JAXBElement }{@code <}{@link IDReference }{@code >} + * {@link JAXBElement }{@code <}{@link UnrecognizedChildElement }{@code >} * * */ diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ConversionRule.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ConversionRule.java index 068745f..1e7e021 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ConversionRule.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ConversionRule.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // @@ -37,7 +37,8 @@ import javax.xml.bind.annotation.XmlType; UnrecognizedChildElement.class, OrderedChild.class, AttributeComposition.class, - IDReference.class + IDReference.class, + Rename.class }) public class ConversionRule { diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Element.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Element.java index 00bf583..5b47d79 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Element.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Element.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDProvider.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDProvider.java index 4031f24..9f3ea82 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDProvider.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDProvider.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDReference.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDReference.java index e48ca71..8640b1c 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDReference.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/IDReference.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ObjectFactory.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ObjectFactory.java index 2dfe1e4..d005c28 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ObjectFactory.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/ObjectFactory.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // @@ -32,6 +32,7 @@ import javax.xml.namespace.QName; public class ObjectFactory { private final static QName _ComplexType_QNAME = new QName("http://www.simantics.org/xml/sax/configuration/", "ComplexType"); + private final static QName _Rename_QNAME = new QName("http://www.simantics.org/xml/sax/configuration/", "Rename"); private final static QName _IDProvider_QNAME = new QName("http://www.simantics.org/xml/sax/configuration/", "IDProvider"); private final static QName _ConversionRule_QNAME = new QName("http://www.simantics.org/xml/sax/configuration/", "ConversionRule"); private final static QName _Attribute_QNAME = new QName("http://www.simantics.org/xml/sax/configuration/", "Attribute"); @@ -129,6 +130,14 @@ public class ObjectFactory { return new ComplexType(); } + /** + * Create an instance of {@link Rename } + * + */ + public Rename createRename() { + return new Rename(); + } + /** * Create an instance of {@link JAXBElement }{@code <}{@link ComplexType }{@code >}} * @@ -138,6 +147,15 @@ public class ObjectFactory { return new JAXBElement(_ComplexType_QNAME, ComplexType.class, null, value); } + /** + * Create an instance of {@link JAXBElement }{@code <}{@link Rename }{@code >}} + * + */ + @XmlElementDecl(namespace = "http://www.simantics.org/xml/sax/configuration/", name = "Rename", substitutionHeadNamespace = "http://www.simantics.org/xml/sax/configuration/", substitutionHeadName = "ConversionRule") + public JAXBElement createRename(Rename value) { + return new JAXBElement(_Rename_QNAME, Rename.class, null, value); + } + /** * Create an instance of {@link JAXBElement }{@code <}{@link IDProvider }{@code >}} * diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/OrderedChild.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/OrderedChild.java index fb9f498..726ad9c 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/OrderedChild.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/OrderedChild.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Rename.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Rename.java new file mode 100644 index 0000000..42153d2 --- /dev/null +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/Rename.java @@ -0,0 +1,117 @@ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2017.01.24 at 12:54:40 PM EET +// + + +package org.simantics.xml.sax.configuration; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * <complexType>
+ *   <complexContent>
+ *     <extension base="{http://www.simantics.org/xml/sax/configuration/}ConversionRule">
+ *       <sequence maxOccurs="unbounded">
+ *         <choice>
+ *           <element ref="{http://www.simantics.org/xml/sax/configuration/}Element"/>
+ *           <element ref="{http://www.simantics.org/xml/sax/configuration/}ComplexType"/>
+ *           <element ref="{http://www.simantics.org/xml/sax/configuration/}Attribute"/>
+ *         </choice>
+ *       </sequence>
+ *       <attribute name="Name" type="{http://www.w3.org/2001/XMLSchema}string" />
+ *     </extension>
+ *   </complexContent>
+ * </complexType>
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "", propOrder = { + "elementOrComplexTypeOrAttribute" +}) +public class Rename + extends ConversionRule +{ + + @XmlElements({ + @XmlElement(name = "Element", type = Element.class), + @XmlElement(name = "ComplexType", type = ComplexType.class), + @XmlElement(name = "Attribute", type = Attribute.class) + }) + protected List elementOrComplexTypeOrAttribute; + @XmlAttribute(name = "Name") + protected String name; + + /** + * Gets the value of the elementOrComplexTypeOrAttribute property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the elementOrComplexTypeOrAttribute property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getElementOrComplexTypeOrAttribute().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Element } + * {@link ComplexType } + * {@link Attribute } + * + * + */ + public List getElementOrComplexTypeOrAttribute() { + if (elementOrComplexTypeOrAttribute == null) { + elementOrComplexTypeOrAttribute = new ArrayList(); + } + return this.elementOrComplexTypeOrAttribute; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/UnrecognizedChildElement.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/UnrecognizedChildElement.java index 4874867..d431344 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/UnrecognizedChildElement.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/UnrecognizedChildElement.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // diff --git a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/package-info.java b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/package-info.java index dd605be..deb96fc 100644 --- a/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/package-info.java +++ b/org.simantics.xml.sax/src/org/simantics/xml/sax/configuration/package-info.java @@ -2,7 +2,7 @@ // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.11.25 at 04:57:27 PM EET +// Generated on: 2017.01.24 at 12:54:40 PM EET // @javax.xml.bind.annotation.XmlSchema(namespace = "http://www.simantics.org/xml/sax/configuration/", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)