Permalink
Browse files

Shapes : support multiple namespaces and ontology imports

  • Loading branch information...
1 parent 2349bbb commit db673c2ccca048c727901ff8d437470eec8e1eb3 @sotty sotty committed Aug 25, 2012
Showing with 1,592 additions and 358 deletions.
  1. +1 −0 drools-shapes/drools-shapes-examples/conyard-example/pom.xml
  2. +5 −1 drools-shapes/drools-shapes-examples/conyard-example/src/test/java/FactTest.java
  3. +1 −1 drools-shapes/drools-shapes-examples/translator-example/pom.xml
  4. +5 −2 drools-shapes/drools-shapes-examples/translator-example/src/main/resources/translators/onto2drl.drl
  5. +2 −2 drools-shapes/drools-shapes-examples/translator-example/src/test/java/IndividualsTest.java
  6. +5 −5 ...apes/drools-shapes-generator-plugin/src/main/java/org/drools/shapes/DefaultConstructorPlugin.java
  7. +61 −51 drools-shapes/drools-shapes-generator-plugin/src/main/java/org/drools/shapes/ShapeCaster.java
  8. +1 −1 drools-shapes/drools-shapes-reasoner-generator/pom.xml
  9. +4 −0 ...shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLFactory.java
  10. +29 −11 ...es/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLFactoryImpl.java
  11. +2 −1 ...rools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLTemplateManager.java
  12. +38 −13 ...es/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/Concept.java
  13. +5 −0 ...ools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/DRLModelImpl.java
  14. +46 −48 ...-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/GenericModelImpl.java
  15. +2 −1 ...ls-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/GraphModelImpl.java
  16. +3 −3 ...ools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/JarModelImpl.java
  17. +45 −15 ...s-reasoner-generator/src/main/java/org/drools/semantics/builder/model/JavaInterfaceModelImpl.java
  18. +8 −8 .../drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/ModelImpl.java
  19. +4 −4 .../drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/OntoModel.java
  20. +12 −3 ...-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/SemanticXSDModel.java
  21. +123 −9 ...pes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/SemanticXSDModelImpl.java
  22. +4 −0 ...s/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/XSDModel.java
  23. +181 −26 ...ools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/XSDModelImpl.java
  24. +24 −20 ...tor/src/main/java/org/drools/semantics/builder/model/compilers/JarInterfaceModelCompilerImpl.java
  25. +30 −20 ...or/src/main/java/org/drools/semantics/builder/model/compilers/JavaInterfaceModelCompilerImpl.java
  26. +3 −2 ...soner-generator/src/main/java/org/drools/semantics/builder/model/compilers/ModelCompilerImpl.java
  27. +53 −36 ...ator/src/main/java/org/drools/semantics/builder/model/compilers/SemanticXSDModelCompilerImpl.java
  28. +2 −0 ...asoner-generator/src/main/java/org/drools/semantics/builder/model/compilers/XSDModelCompiler.java
  29. +55 −14 ...er-generator/src/main/java/org/drools/semantics/builder/model/compilers/XSDModelCompilerImpl.java
  30. +5 −0 ...or/src/main/java/org/drools/semantics/builder/model/inference/AbstractModelInferenceStrategy.java
  31. +45 −7 ...nerator/src/main/java/org/drools/semantics/builder/model/inference/DelegateInferenceStrategy.java
  32. +14 −23 ...r-generator/src/main/resources/org/drools/semantics/builder/model/compilers/bindings.xjb.template
  33. +1 −1 .../src/main/resources/org/drools/semantics/builder/model/compilers/empire.annotation.index.template
  34. +48 −0 ...pes-reasoner-generator/src/main/resources/org/drools/semantics/builder/model/compilers/global.xjb
  35. +18 −0 ...s-reasoner-generator/src/main/resources/org/drools/semantics/builder/model/compilers/owlThing.xsd
  36. +2 −2 ...-shapes-reasoner-generator/src/main/resources/org/drools/semantics/templates/model/drl/trait.drlt
  37. +6 −6 ...r-generator/src/main/resources/org/drools/semantics/templates/model/java/ShadowInterface.template
  38. +7 −7 ...er-generator/src/main/resources/org/drools/semantics/templates/model/java/TraitInterface.template
  39. +3 −0 ...generator/src/main/resources/org/drools/semantics/templates/model/java/package-info.java.template
  40. +2 −1 ...hapes-reasoner-generator/src/test/java/org/drools/semantics/lang/dl/DL_2_ModelGenerationTest.java
  41. +87 −0 ...hapes-reasoner-generator/src/test/java/org/drools/semantics/lang/dl/DL_6_MixedNamespacesTest.java
  42. +4 −4 .../drools-shapes-reasoner-generator/src/test/java/org/drools/semantics/lang/dl/DL_99_ModelTest.java
  43. +27 −0 drools-shapes/drools-shapes-reasoner-generator/src/test/resources/appendix.owl
  44. +45 −0 drools-shapes/drools-shapes-reasoner-generator/src/test/resources/mixed.owl
  45. +16 −0 drools-shapes/drools-shapes-utilities/pom.xml
  46. +2 −2 drools-shapes/drools-shapes-utilities/src/main/java/org.drools.semantics/UIdAble.java
  47. +1 −8 drools-shapes/drools-shapes-utilities/src/main/java/org.drools.semantics/utils/NameUtils.java
  48. +68 −0 drools-shapes/drools-shapes-utilities/src/main/java/org.drools.semantics/utils/NamespaceUtils.java
  49. +34 −0 drools-shapes/drools-shapes-utilities/src/main/java/org/w3/_2002/_07/owl/Thing.java
  50. +403 −0 drools-shapes/drools-shapes-utilities/src/main/java/org/w3/_2002/_07/owl/ThingImpl.java
View
1 drools-shapes/drools-shapes-examples/conyard-example/pom.xml
@@ -57,6 +57,7 @@
<groupId>org.drools</groupId>
<artifactId>drools-chance-core</artifactId>
<version>${drools.version}</version>
+ <scope>test</scope>
</dependency>
View
6 drools-shapes/drools-shapes-examples/conyard-example/src/test/java/FactTest.java
@@ -3,6 +3,8 @@
import com.clarkparsia.empire.config.ConfigKeys;
import com.clarkparsia.empire.sesametwo.OpenRdfEmpireModule;
import com.clarkparsia.empire.sesametwo.RepositoryDataSourceFactory;
+import com.sun.xml.bind.v2.runtime.JAXBContextImpl;
+import com.sun.xml.bind.v2.runtime.NameList;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
@@ -15,6 +17,7 @@
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
+import org.w3._2002._07.owl.ThingImpl;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -30,6 +33,7 @@
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
+import javax.xml.bind.annotation.XmlNs;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
@@ -591,7 +595,7 @@ public void testXMLNamespaces() {
for ( int j = 0; j < nodeList.getLength(); j++ ) {
Node n = nodeList.item( j );
if ( n.getNodeName().equals( "xmlns" ) ) {
- assertEquals( "http://owl.drools.org/conyard#", n.getNodeValue() );
+ assertEquals( "http://owl.drools.org/conyard", n.getNodeValue() );
} else if ( n.getNodeName().equals( "xmlns:xml" ) ) {
assertEquals( "http://www.w3.org/XML/1998/namespace", n.getNodeValue() );
} else if ( n.getNodeName().equals( "xmlns:xsi" ) ) {
View
2 drools-shapes/drools-shapes-examples/translator-example/pom.xml
@@ -254,7 +254,7 @@
<generateTraitDRL>true</generateTraitDRL>
<generateDefaultImplClasses>true</generateDefaultImplClasses>
<preserveInheritanceInImpl>false</preserveInheritanceInImpl>
- <buildSpecXSDs>true</buildSpecXSDs>
+ <buildSpecXSDs>false</buildSpecXSDs>
<useExistingImplementations>true</useExistingImplementations>
<generateIndividuals>true</generateIndividuals>
</configuration>
View
7 ...pes/drools-shapes-examples/translator-example/src/main/resources/translators/onto2drl.drl
@@ -1,6 +1,9 @@
-package org.drools.trnaslators;
+package org.drools.translators;
+import org.w3._2002._07.owl.Thing;
import org.semanticweb.ontologies._2012._1.rule_merged.*;
+import org.semanticweb.ontologies._2012._1.rules.*;
+import org.semanticweb.ontologies._2012._1.rule_example.*;
import org.drools.lang.api.*;
import org.drools.lang.descr.*;
import org.drools.semantics.UIdAble;
@@ -42,7 +45,7 @@ dialect "mvel"
when
$r : Rule( $uid : dyEntryId, $lhs : hasPremiseFormula )
not MetaRule ( this == $r ) //MVEL bug with instanceof... TODO
- $f : Pattern( $pid : dyEntryId, this == $lhs, $fct : get("hasFunctorType") )
+ $f : Pattern( $pid : dyEntryId, this == $lhs, $fct : get( "hasFunctorType" ), $fct != null && $fct.size() > 0 )
$t : Thing( $type : this.semanticTypeName ) from $fct.get(0)
$x : RuleDescr( name == $uid )
then
View
4 drools-shapes/drools-shapes-examples/translator-example/src/test/java/IndividualsTest.java
@@ -8,6 +8,8 @@
import org.drools.lang.descr.PackageDescr;
import org.drools.runtime.StatefulKnowledgeSession;
import org.junit.Test;
+import org.semanticweb.ontologies._2012._1.rule_example.Pattern1Type;
+import org.semanticweb.ontologies._2012._1.rule_example.Pattern1TypeImpl;
import org.semanticweb.ontologies._2012._1.rule_merged.*;
import java.util.Collection;
@@ -24,8 +26,6 @@ public void testIndividuals() {
Pattern1Type p1 = new Pattern1TypeImpl();
Object x = p1.getHasFunctorType();
Object y = ((Pattern1TypeImpl)p1).getHasFunctorTypeInferred();
-
-
Collection c = IndividualFactory.getIndividuals();
assertEquals( 21, c.size() );
View
10 ...ols-shapes-generator-plugin/src/main/java/org/drools/shapes/DefaultConstructorPlugin.java
@@ -59,14 +59,14 @@ public String getUsage() {
@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) throws SAXException {
for (ClassOutline co : outline.getClasses() ) {
-
CPluginCustomization c = co.target.getCustomizations().find( uri, "default" );
- if ( co.implClass.getConstructor( new JType[0]) == null ) {
- createDefaultConstructor( co.implClass );
+ if ( c != null ) {
+ if ( co.implClass.getConstructor( new JType[0]) == null ) {
+ createDefaultConstructor( co.implClass );
+ }
+ c.markAsAcknowledged();
}
- c.markAsAcknowledged();
}
-
return true;
}
View
112 ...ls-shapes/drools-shapes-generator-plugin/src/main/java/org/drools/shapes/ShapeCaster.java
@@ -28,6 +28,7 @@
import org.drools.semantics.builder.model.compilers.ModelCompiler;
import org.drools.semantics.builder.model.compilers.ModelCompilerFactory;
import org.drools.semantics.builder.model.compilers.XSDModelCompiler;
+import org.w3._2002._07.owl.Thing;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@@ -44,6 +45,9 @@
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.*;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
/**
* Goal which creates various possible fact model representations from an ontology
@@ -88,6 +92,19 @@ public void setOntology(String ontology) {
this.ontology = ontology;
}
+ /**
+ * @parameter
+ */
+ private List<String> ontologyImports;
+
+ public List<String> getOntologyImports() {
+ return ontologyImports;
+ }
+
+ public void setOntologyImports(List<String> ontologyImports) {
+ this.ontologyImports = ontologyImports;
+ }
+
/**
* @parameter default-value="model"
@@ -263,7 +280,18 @@ public void execute() throws MojoExecutionException {
}
DLFactory factory = DLFactoryBuilder.newDLFactoryInstance();
- Resource res = ResourceFactory.newFileResource( ontology );
+ if ( ontologyImports == null ) {
+ ontologyImports = Collections.emptyList();
+ }
+
+ int n = 1 + ontologyImports.size();
+ Resource[] res = new Resource[ n ];
+ int j = 0;
+ for ( String imp : ontologyImports ) {
+ res[j++] = ResourceFactory.newFileResource( imp );
+ }
+ res[j] = ResourceFactory.newFileResource( ontology );
+
factory.setInferenceStrategy( isDelegateInference() ? DLFactory.INFERENCE_STRATEGY.EXTERNAL : DLFactory.INFERENCE_STRATEGY.INTERNAL );
OntoModel results = factory.buildModel( getModelName(), res );
@@ -316,13 +344,12 @@ public void execute() throws MojoExecutionException {
((XSDModelCompiler) compiler).setTransientPropertiesEnabled( false );
((XSDModelCompiler) compiler).setUseImplementation( false );
+ ((XSDModelCompiler) compiler).setSchemaMode( "_$spec" );
xsdModel = (SemanticXSDModel) compiler.compile( results );
try {
- FileOutputStream fos = new FileOutputStream( target + metainf + slash + getModelName() +"_$spec.xsd" );
+ File fos = new File( target + metainf + slash + getModelName() +"_$spec.xsd" );
xsdModel.stream( fos );
- fos.flush();
- fos.close();
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
@@ -331,27 +358,25 @@ public void execute() throws MojoExecutionException {
((XSDModelCompiler) compiler).setTransientPropertiesEnabled( false );
((XSDModelCompiler) compiler).setUseImplementation( true );
+ ((XSDModelCompiler) compiler).setSchemaMode( "_$impl" );
xsdModel = (SemanticXSDModel) compiler.compile( results );
try {
- FileOutputStream fos = new FileOutputStream( target + metainf + slash + getModelName() +"_$impl.xsd" );
+ File fos = new File( target + metainf + slash + getModelName() +"_$impl.xsd" );
xsdModel.stream( fos );
- fos.flush();
- fos.close();
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
((XSDModelCompiler) compiler).setTransientPropertiesEnabled( true );
((XSDModelCompiler) compiler).setUseImplementation( false );
+ ((XSDModelCompiler) compiler).setSchemaMode( "_$full" );
xsdModel = (SemanticXSDModel) compiler.compile( results );
try {
- FileOutputStream fos = new FileOutputStream( target + metainf + slash + getModelName() +"_$full.xsd" );
+ File fos = new File( target + metainf + slash + getModelName() +"_$full.xsd" );
xsdModel.stream( fos );
- fos.flush();
- fos.close();
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
@@ -425,55 +450,21 @@ public void execute() throws MojoExecutionException {
((XSDModelCompiler) compiler).setUseImplementation( false );
+ ((XSDModelCompiler) compiler).setSchemaMode( "" );
xsdModel = (SemanticXSDModel) compiler.compile( results );
try {
- FileOutputStream fos = new FileOutputStream( target + metainf + slash + getModelName() +".xsd" );
+ File fos = new File( target + metainf + slash + getModelName() +".xsd" );
xsdModel.stream( fos );
- fos.flush();
- fos.close();
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
try {
- FileOutputStream fos = new FileOutputStream( target + metainf + slash + "bindings.xjb" );
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- xsdModel.streamBindings( baos );
-
- DocumentBuilderFactory doxFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = doxFactory.newDocumentBuilder();
- InputSource is = new InputSource( new StringReader( new String( baos.toByteArray() ) ) );
- Document dox = builder.parse( is );
- dox.normalize();
-
- XPathFactory xpathFactory = XPathFactory.newInstance();
- XPathExpression xpathExp = xpathFactory.newXPath().compile(
- "//text()[normalize-space(.) = '']");
- NodeList emptyTextNodes = (NodeList)
- xpathExp.evaluate(dox, XPathConstants.NODESET);
-
- // Remove each empty text node from document.
- for (int i = 0; i < emptyTextNodes.getLength(); i++) {
- Node emptyTextNode = emptyTextNodes.item(i);
- emptyTextNode.getParentNode().removeChild(emptyTextNode);
- }
-
-
-
- TransformerFactory tFactory = TransformerFactory.newInstance();
- tFactory.setAttribute( "indent-number", new Integer(2) );
- Transformer transformer = tFactory.newTransformer();
- transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
- DOMSource source = new DOMSource( dox );
- StreamResult result = new StreamResult( new OutputStreamWriter( fos ) );
- transformer.transform( source, result );
-
- fos.flush();
- fos.close();
+ File fos = new File( target + metainf + slash + "bindings.xjb" );
+ xsdModel.streamBindings( fos );
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
@@ -489,6 +480,25 @@ public void execute() throws MojoExecutionException {
}
+ // namespace fix. For some reason, hj needs the (local) owl package to be assigned to the default namespace
+ try {
+ String classPathTemp = target + "xjc" + slash + Thing.class.getPackage().getName().replace(".", slash);
+ File f2 = new File( classPathTemp );
+ if ( ! f2.exists() ) {
+ f2.mkdirs();
+ }
+
+ FileOutputStream fos2 = new FileOutputStream( classPathTemp + slash + "package-info.java" );
+ xsdModel.streamNamespaceFix( fos2 );
+
+ fos2.flush();
+ fos2.close();
+ } catch (Exception e) {
+
+ }
+
+
+
}
@@ -505,7 +515,7 @@ public void execute() throws MojoExecutionException {
xsdModel = (SemanticXSDModel) compiler.compile( results );
try {
- String classPath = target + "xjc" + slash + xsdModel.getPackage().replace(".", slash);
+ String classPath = target + "xjc" + slash + xsdModel.getDefaultPackage().replace(".", slash);
File f = new File( classPath );
if ( ! f.exists() ) {
f.mkdirs();
@@ -515,14 +525,14 @@ public void execute() throws MojoExecutionException {
xsdModel.streamIndividualFactory( fos );
fos.flush();
fos.close();
+
+
} catch (Exception e) {
throw new MojoExecutionException( e.getMessage() );
}
}
-
-
// private boolean generateTraitDRL = true;
View
2 drools-shapes/drools-shapes-reasoner-generator/pom.xml
@@ -248,7 +248,7 @@
</releases>
<snapshots>
<enabled>true</enabled>
- <updatePolicy>daily</updatePolicy>
+ <updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
View
4 ...rools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLFactory.java
@@ -54,7 +54,11 @@
public OntoModel buildModel( String name, Resource res, StatefulKnowledgeSession kSession );
+ public OntoModel buildModel( String name, Resource[] res, StatefulKnowledgeSession kSession );
+
public OntoModel buildModel( String name, Resource res );
+ public OntoModel buildModel( String name, Resource[] res );
+
}
View
40 ...s-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLFactoryImpl.java
@@ -30,11 +30,11 @@
import org.drools.semantics.builder.model.inference.DelegateInferenceStrategy;
import org.drools.semantics.builder.model.inference.InternalInferenceStrategy;
import org.drools.semantics.builder.model.inference.ModelInferenceStrategy;
+import org.drools.semantics.utils.NameUtils;
import org.semanticweb.owlapi.apibinding.OWLManager;
-import org.semanticweb.owlapi.model.OWLDataFactory;
-import org.semanticweb.owlapi.model.OWLOntology;
-import org.semanticweb.owlapi.model.OWLOntologyCreationException;
-import org.semanticweb.owlapi.model.OWLOntologyManager;
+import org.semanticweb.owlapi.io.OWLOntologyDocumentSource;
+import org.semanticweb.owlapi.io.StreamDocumentSource;
+import org.semanticweb.owlapi.model.*;
import java.io.IOException;
import java.util.LinkedHashMap;
@@ -77,12 +77,21 @@ public void setExternalReasoner(SupportedReasoners externalReasoner) {
public OWLOntology parseOntology( Resource resource ) {
+ return parseOntology( new Resource[] { resource } );
+ }
+
+ public OWLOntology parseOntology( Resource[] resources ) {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
+ OWLOntologyLoaderConfiguration config = new OWLOntologyLoaderConfiguration();
+ config.setMissingOntologyHeaderStrategy( OWLOntologyLoaderConfiguration.MissingOntologyHeaderStrategy.IMPORT_GRAPH );
-
- OWLOntology onto = manager.loadOntologyFromOntologyDocument( resource.getInputStream() );
+ OWLOntology onto = null;
+ for ( Resource res : resources ) {
+ OWLOntologyDocumentSource source = new StreamDocumentSource( res.getInputStream() );
+ onto = manager.loadOntologyFromOntologyDocument( source, config );
+ }
return onto;
} catch (IOException e) {
@@ -148,13 +157,17 @@ private OntoModel buildModel( String name, OWLOntology ontoDescr, Map<ModelInfer
}
+ public OntoModel buildModel( String name, Resource res, StatefulKnowledgeSession kSession ) {
+ return buildModel( name, new Resource[] { res }, kSession );
+ }
+
/**
* Builds an ontology-driven model from a DL resource, using a kSession
* @param res
* @param kSession
* @return
*/
- public OntoModel buildModel( String name, Resource res, StatefulKnowledgeSession kSession ) {
+ public OntoModel buildModel( String name, Resource[] res, StatefulKnowledgeSession kSession ) {
OWLOntology ontoDescr = DLFactoryImpl.getInstance().parseOntology( res );
@@ -194,10 +207,6 @@ public OntoModel buildModel( String name, Resource res, StatefulKnowledgeSession
ontoDescr,
theory,
kSession );
-
- results.setPackage( ontoDescr.getOntologyID().getOntologyIRI().toString() );
- results.setNamespace( ontoDescr.getOntologyID().getOntologyIRI().toString() );
-
return results;
}
@@ -215,6 +224,15 @@ public OntoModel buildModel( String name, Resource res ) {
return buildModel( name, res, kSession );
}
+ public OntoModel buildModel( String name, Resource[] res ) {
+ KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+ StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession();
+
+ setInferenceStrategy( DLFactory.INFERENCE_STRATEGY.EXTERNAL );
+
+ return buildModel( name, res, kSession );
+ }
+
View
3 ...apes-reasoner-generator/src/main/java/org/drools/semantics/builder/DLTemplateManager.java
@@ -46,7 +46,8 @@
protected static final String[] NAMED_TEMPLATES_JAVA = new String[] {
"model/java/TraitInterface.template",
"model/java/ShadowInterface.template",
- "model/java/IndividualFactory.template"
+ "model/java/IndividualFactory.template",
+ "model/java/package-info.java.template"
};
View
51 ...s-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/Concept.java
@@ -18,6 +18,7 @@
import org.drools.definition.type.Position;
import org.drools.semantics.utils.NameUtils;
+import org.semanticweb.owlapi.model.IRI;
import java.util.*;
@@ -32,7 +33,9 @@
@Position(6) private Set<Concept> subConcepts;
@Position(7) private Map<String, PropertyRelation> shadowProperties;
@Position(8) private String chosenSuper;
- @Position(9) private String fullyQualifiedName;
+ @Position(9) private String pack;
+ @Position(10) private String namespace;
+
public enum Resolution { NONE, CLASS, IFACE, ENUM ; }
@@ -46,8 +49,8 @@
- public Concept( String iri, String name, boolean primitive ) {
- this.iri = iri;
+ public Concept( IRI iri, String name, boolean primitive ) {
+ this.iri = iri.toQuotedString();
this.name = primitive ? name : NameUtils.compactUpperCase( name );
this.superConcepts = new HashSet();
this.subConcepts = new HashSet();
@@ -56,17 +59,22 @@ public Concept( String iri, String name, boolean primitive ) {
this.equivalentConcepts = new HashSet();
this.keys = new ArrayList<PropertyRelation>();
this.primitive = primitive;
+ this.pack = NameUtils.namespaceURIToPackage( iri.getStart() );
+ this.namespace = iri.getStart();
}
- public Concept( String iri, String name, Set superConcepts, Map properties, Set equivalentConcepts, Set subConcepts, Map shadowProperties, boolean primitive ) {
- this.iri = iri;
+ public Concept( IRI iri, String name, Set superConcepts, Map properties, Set equivalentConcepts, Set subConcepts, Map shadowProperties, boolean primitive ) {
+ this.iri = iri.toQuotedString();
this.name = primitive ? name : NameUtils.compactUpperCase( name );
this.superConcepts = superConcepts != null ? superConcepts : new HashSet<Concept>();
this.properties = properties != null ? properties : new HashMap<String, PropertyRelation>();
this.shadowProperties = shadowProperties != null ? shadowProperties : new HashMap<String, PropertyRelation>();
this.equivalentConcepts = equivalentConcepts != null ? equivalentConcepts : new HashSet<Concept>();
this.subConcepts = subConcepts != null ? subConcepts : new HashSet<Concept>();
this.primitive = primitive;
+ this.pack = NameUtils.namespaceURIToPackage( iri.getStart() );
+ this.namespace = iri.getStart();
+
}
@@ -86,6 +94,7 @@ public String toFullString() {
return "Concept{" +
"iri='" + iri + '\'' +
", name='" + name + '\'' +
+ ", pack='" + pack + '\'' +
supers +
// ", properties=" + properties +
'}';
@@ -126,14 +135,6 @@ public void setName(String name) {
}
- public String getFullyQualifiedName() {
- return fullyQualifiedName == null ? name : fullyQualifiedName;
- }
-
- public void setFullyQualifiedName(String fullyQualifiedName) {
- this.fullyQualifiedName = fullyQualifiedName;
- }
-
public Set<Concept> getSuperConcepts() {
return superConcepts;
}
@@ -330,6 +331,30 @@ public void setShadowed(boolean shadowed) {
this.shadowed = shadowed;
}
+ public String getPackage() {
+ return pack;
+ }
+
+ public void setPackage(String pack) {
+ this.pack = pack;
+ }
+
+ public String getNamespace() {
+ return namespace;
+ }
+
+ public void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
+
+ public String getFullyQualifiedName() {
+ if ( ! isPrimitive() && pack != null ) {
+ return pack + "." + name;
+ } else {
+ return name;
+ }
+ }
+
public static class Range {
private Concept concept;
private Integer minCard = 1;
View
5 ...pes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/DRLModelImpl.java
@@ -16,6 +16,8 @@
package org.drools.semantics.builder.model;
+import org.w3._2002._07.owl.Thing;
+
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
@@ -69,6 +71,9 @@ protected String traitsToString() {
public String getDRL() {
StringBuilder sb = new StringBuilder();
+
+ sb.append( "package " + getDefaultPackage() + ";\n");
+ sb.append( "declare " + Thing.class.getName() + " end \n" );
for ( String key : getTraitNames() ) {
sb.append( getTrait(key) ).append( "\n" );
}
View
94 ...reasoner-generator/src/main/java/org/drools/semantics/builder/model/GenericModelImpl.java
@@ -3,15 +3,16 @@
import org.drools.semantics.utils.NameUtils;
+import org.w3._2002._07.owl.Thing;
import java.util.*;
public class GenericModelImpl implements OntoModel, Cloneable {
- private String pack;
+ private String defaultPackage;
- private String namespace;
+ private String defaultNamespace;
private String name;
@@ -32,7 +33,7 @@ protected GenericModelImpl newInstance() {
public Object clone() {
GenericModelImpl twin = newInstance();
- twin.setPackage( pack );
+ twin.setDefaultPackage( defaultPackage );
twin.setName( name );
twin.setFlat( flat );
twin.setConcepts( new LinkedHashMap<String, Concept>( concepts ) );
@@ -42,28 +43,24 @@ public Object clone() {
}
- public String getPackage() {
- return pack;
+ public String getDefaultPackage() {
+ return defaultPackage;
}
- public void setPackage( String pack ) {
- this.pack = NameUtils.namespaceURIToPackage( pack );
+ public void setDefaultPackage( String pack ) {
+ this.defaultPackage = pack;
}
- public String getNamespace() {
- return namespace;
+ public String getDefaultNamespace() {
+ return defaultNamespace;
}
- public void setNamespace(String namespace) {
- this.namespace = namespace;
+ public void setDefaultNamespace(String namespace) {
+ this.defaultNamespace = namespace;
}
- public String getPack() {
- return pack;
- }
-
- public void setPack(String pack) {
- this.pack = pack;
+ public String getDefaultPackagee() {
+ return defaultPackage;
}
public String getName() {
@@ -250,15 +247,15 @@ public void raze() {
con.addShadowProperty( propKey, con.getProperties().get( propKey ) );
}
for ( Concept sup : con.getSuperConcepts() ) {
- if ( ! sup.getName().equals( "Thing" ) && ! sup.getShadowProperties().containsKey( propKey ) ) {
+ if ( ! sup.getFullyQualifiedName().equals( Thing.class.getName() ) && ! sup.getShadowProperties().containsKey( propKey ) ) {
System.err.println( "Getting prop" + propKey + " up from " + con.getName() + " to " + sup.getName() );
sup.addShadowProperty( propKey, con.getProperties().get( propKey ) );
}
}
}
for ( String propKey : con.getShadowProperties().keySet() ) {
for ( Concept sup : con.getSuperConcepts() ) {
- if ( ! sup.getName().equals( "Thing" ) && ! sup.getShadowProperties().containsKey( propKey ) ) {
+ if ( ! sup.getFullyQualifiedName().equals( Thing.class.getName() ) && ! sup.getShadowProperties().containsKey( propKey ) ) {
System.err.println( "Getting prop" + propKey + " up from " + con.getName() + " to " + sup.getName() );
sup.addShadowProperty( propKey, con.getShadowProperties().get( propKey ) );
}
@@ -308,35 +305,35 @@ protected void setFlat( boolean flat ) {
public void resolve( ) {
- for ( Concept con : getConcepts() ) {
- if ( con.getIri().startsWith("<java://") ) {
- String fullName = NameUtils.buildFQNameFromIri( con.getIri() );
- System.out.println( "Looking for " + con.getName() + " as " + fullName );
- try {
- Class existingKlass = Class.forName( fullName );
- if ( existingKlass != null ) {
- System.out.println( "FOUND!!!! "+ existingKlass.getName() );
- con.setFullyQualifiedName( fullName );
- con.setResolved( true );
- if ( existingKlass.isInterface() ) {
- con.setResolvedAs( Concept.Resolution.IFACE );
- } else if ( existingKlass.isEnum() ) {
- con.setResolvedAs( Concept.Resolution.ENUM );
- } else {
- con.setResolvedAs( Concept.Resolution.CLASS );
- }
- }
- else {
- con.setFullyQualifiedName( name );
-// System.out.println( con.getName() + " Is Novel ");
- }
-
- } catch ( ClassNotFoundException e ) {
- con.setFullyQualifiedName( name );
-// System.out.println( con.getName() + "Is Novel ");
- }
- }
- }
+// for ( Concept con : getConcepts() ) {
+// if ( con.getIri().startsWith("<java://") ) {
+// String fullName = NameUtils.buildFQNameFromIri( con.getIri() );
+// System.out.println( "Looking for " + con.getName() + " as " + fullName );
+// try {
+// Class existingKlass = Class.forName( fullName );
+// if ( existingKlass != null ) {
+// System.out.println( "FOUND!!!! "+ existingKlass.getName() );
+// con.setFullyQualifiedName( fullName );
+// con.setResolved( true );
+// if ( existingKlass.isInterface() ) {
+// con.setResolvedAs( Concept.Resolution.IFACE );
+// } else if ( existingKlass.isEnum() ) {
+// con.setResolvedAs( Concept.Resolution.ENUM );
+// } else {
+// con.setResolvedAs( Concept.Resolution.CLASS );
+// }
+// }
+// else {
+// con.setFullyQualifiedName( name );
+//// System.out.println( con.getName() + " Is Novel ");
+// }
+//
+// } catch ( ClassNotFoundException e ) {
+// con.setFullyQualifiedName( name );
+//// System.out.println( con.getName() + "Is Novel ");
+// }
+// }
+// }
}
@@ -362,6 +359,7 @@ public void sort() {
root.addChild( node );
} else {
for ( Concept superCon : con.getSuperConcepts() ) {
+
String superKey = superCon.getIri();
Node<Concept> superNode = map.get( superKey );
View
3 ...s-reasoner-generator/src/main/java/org/drools/semantics/builder/model/GraphModelImpl.java
@@ -25,6 +25,7 @@
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import org.apache.commons.collections15.Transformer;
+import org.semanticweb.owlapi.model.IRI;
import javax.swing.*;
import java.awt.*;
@@ -114,7 +115,7 @@ public void addRelationEdge( Relation rel ) {
}
if ( obj == null ) {
// literal aka datatype, most probably
- Concept k = new Concept( rel.getObject(), ((PropertyRelation) rel).getTarget().getName(), true );
+ Concept k = new Concept( IRI.create( rel.getObject() ), ((PropertyRelation) rel).getTarget().getName(), true );
cgraph.addVertex( k );
obj = k;
}
View
6 ...pes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/JarModelImpl.java
@@ -64,17 +64,17 @@ public ByteArrayOutputStream buildJar( ) {
// System.out.println("Adding " + name);
// Add archive entry
- JarEntry jarAdd = new JarEntry( getPackage().replace(".","/") + "/" + name + ".java" );
+ JarEntry jarAdd = new JarEntry( getDefaultPackage().replace(".","/") + "/" + name + ".java" );
jarAdd.setTime( now.getTime() );
out.putNextEntry(jarAdd);
// Write file to archive
- out.write( ((String) getTrait(name) ).getBytes() );
+ out.write( ((InterfaceHolder) getTrait( name ) ).getSource().getBytes() );
// Add archive entry
- jarAdd = new JarEntry( getPackage().replace(".","/") + "/" + name + ".class" );
+ jarAdd = new JarEntry( getDefaultPackage().replace(".","/") + "/" + name + ".class" );
jarAdd.setTime( now.getTime() );
out.putNextEntry(jarAdd);
View
60 ...er-generator/src/main/java/org/drools/semantics/builder/model/JavaInterfaceModelImpl.java
@@ -27,24 +27,25 @@
public class JavaInterfaceModelImpl extends ModelImpl implements JavaInterfaceModel {
+ protected static String slash = System.getProperty("file.separator");
JavaInterfaceModelImpl() {
}
- private Map<String, String> traits = new HashMap<String, String>();
+ private Map<String, InterfaceHolder> traits = new HashMap<String, InterfaceHolder>();
- public Map<String, String> getTraits() {
+ public Map<String, InterfaceHolder> getTraits() {
return traits;
}
- public void addTrait(String name, String trait) {
+ public void addTrait( String name, InterfaceHolder trait ) {
traits.put( name, trait );
}
- public void addTrait(String name, Object trait) {
- addTrait( name, (String) trait );
+ public void addTrait( String name, Object trait ) {
+ addTrait( name, (InterfaceHolder) trait );
}
public Object getTrait( String name ) {
@@ -68,20 +69,15 @@ protected String traitsToString() {
public boolean save( String targetDirectory ) {
- String slash = System.getProperty("file.separator");
-
- String path = targetDirectory + slash + getPackage().replace(".", "/");
- File dir = new File( path );
- if (! dir.exists()) {
- dir.mkdirs();
- }
+ for ( String key : getTraitNames() ) {
+ InterfaceHolder holder = (InterfaceHolder) getTrait( key );
+ String path = getPackageDir( targetDirectory, holder.getPack() );
- for ( String key : getTraitNames() ) {
- File f = new File( path + slash + key + ".java" );
+ File f = new File( path + slash + key.substring( key.lastIndexOf('.') + 1 ) + ".java" );
try {
FileOutputStream fos = new FileOutputStream( f );
- fos.write( getTrait(key).toString().getBytes());
+ fos.write( holder.getSource().getBytes() );
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
@@ -98,6 +94,40 @@ public boolean save( String targetDirectory ) {
}
+ private String getPackageDir(String targetDirectory, String pack) {
+ String path = targetDirectory + slash + pack.replace(".", "/");
+ File dir = new File( path );
+ if (! dir.exists()) {
+ dir.mkdirs();
+ }
+ return path;
+ }
+
+
+ public static class InterfaceHolder {
+ private String source;
+ private String pack;
+
+ public InterfaceHolder(String source, String pack) {
+ this.source = source;
+ this.pack = pack;
+ }
+
+ public String getSource() {
+ return source;
+ }
+
+ public void setSource(String source) {
+ this.source = source;
+ }
+
+ public String getPack() {
+ return pack;
+ }
+ public void setPack(String pack) {
+ this.pack = pack;
+ }
+ }
}
View
16 ...shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/ModelImpl.java
@@ -41,21 +41,21 @@ public void initFromBaseModel( OntoModel base ) {
- public String getPackage() {
- return innerModel.getPackage();
+ public String getDefaultPackage() {
+ return innerModel.getDefaultPackage();
}
- public void setPackage(String pack) {
- innerModel.setPackage( pack );
+ public void setDefaultPackage(String pack) {
+ innerModel.setDefaultPackage( pack );
}
- public String getNamespace() {
- return innerModel.getNamespace();
+ public String getDefaultNamespace() {
+ return innerModel.getDefaultNamespace();
}
- public void setNamespace( String namespace ) {
- innerModel.setNamespace( namespace );
+ public void setDefaultNamespace( String namespace ) {
+ innerModel.setDefaultNamespace( namespace );
}
View
8 ...shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/OntoModel.java
@@ -21,17 +21,17 @@
public interface OntoModel extends Cloneable {
- public String getPackage();
+ public String getDefaultPackage();
- public void setPackage( String pack );
+ public void setDefaultPackage( String pack );
public String getName();
public void setName( String name );
- public String getNamespace();
+ public String getDefaultNamespace();
- public void setNamespace( String ns );
+ public void setDefaultNamespace( String ns );
View
15 ...reasoner-generator/src/main/java/org/drools/semantics/builder/model/SemanticXSDModel.java
@@ -17,17 +17,22 @@
package org.drools.semantics.builder.model;
+import org.jdom.Namespace;
+
+import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public interface SemanticXSDModel extends XSDModel {
- public String getBindings();
+ public String getBindings( String namespace );
+
+ public void setBindings( String namespace, String bindings );
- public void setBindings( String bindings );
+ public boolean streamBindings( OutputStream os );
- public boolean streamBindings( OutputStream os);
+ public boolean streamBindings( File file );
public void setIndex( String index );
@@ -36,4 +41,8 @@
public void setIndividualFactory( String factory );
public boolean streamIndividualFactory( OutputStream os );
+
+ public void setNamespaceFix( String fix );
+
+ public boolean streamNamespaceFix( OutputStream os );
}
View
132 ...oner-generator/src/main/java/org/drools/semantics/builder/model/SemanticXSDModelImpl.java
@@ -16,22 +16,53 @@
package org.drools.semantics.builder.model;
-import java.io.IOException;
-import java.io.OutputStream;
+import org.drools.KnowledgeBaseConfiguration;
+import org.drools.KnowledgeBaseFactory;
+import org.drools.RuleBaseConfiguration;
+import org.drools.reteoo.AlphaNode;
+import org.drools.reteoo.ObjectSource;
+import org.drools.reteoo.builder.BuildContext;
+import org.drools.reteoo.builder.DefaultNodeFactory;
+import org.drools.reteoo.builder.NodeFactory;
+import org.drools.semantics.builder.DLTemplateManager;
+import org.drools.spi.AlphaNodeFieldConstraint;
+import org.jdom.Namespace;
+import org.mvel2.templates.CompiledTemplate;
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.*;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.xpath.XPathConstants;
+import javax.xml.xpath.XPathExpression;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+import java.io.*;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
public class SemanticXSDModelImpl extends XSDModelImpl implements SemanticXSDModel {
private String index;
- private String bindings;
+ private Map<String,String> bindings;
private String individualFactory;
- public String getBindings() {
- return this.bindings;
+ private String namespaceFix;
+
+ public String getBindings( String namespace ) {
+ return this.bindings != null && bindings.containsKey( namespace )? bindings.get( namespace ) : "";
}
public boolean streamIndividualFactory( OutputStream os ) {
@@ -45,14 +76,97 @@ public boolean streamIndividualFactory( OutputStream os ) {
- public void setBindings(String bindings) {
- this.bindings = bindings;
+ public void setBindings( String namespace, String bindings ) {
+ if ( this.bindings == null ) {
+ this.bindings = new HashMap<String,String>();
+ }
+ this.bindings.put( namespace, bindings );
+ }
+
+ public String getNamespaceFix() {
+ return namespaceFix;
+ }
+
+ public void setNamespaceFix(String namespaceFix) {
+ this.namespaceFix = namespaceFix;
}
public boolean streamBindings( OutputStream os ) {
try {
- os.write( bindings.getBytes() );
- } catch (IOException e) {
+ for ( String ns : bindings.keySet() ) {
+ os.write( compactXML( getBindings ( ns ) ).getBytes() );
+ }
+ } catch ( Exception e ) {
+ return false;
+ }
+ return true;
+ }
+
+ public boolean streamNamespaceFix( OutputStream os ) {
+ try {
+ os.write( getNamespaceFix().getBytes() );
+ } catch ( Exception e ) {
+ return false;
+ }
+ return true;
+ }
+
+
+ private String compactXML( String source ) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException {
+ DocumentBuilderFactory doxFactory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder = doxFactory.newDocumentBuilder();
+ InputSource is = new InputSource( new StringReader( source ) );
+ Document dox = builder.parse( is );
+ dox.normalize();
+
+ XPathFactory xpathFactory = XPathFactory.newInstance();
+ XPathExpression xpathExp = xpathFactory.newXPath().compile(
+ "//text()[normalize-space(.) = '']");
+ NodeList emptyTextNodes = (NodeList)
+ xpathExp.evaluate(dox, XPathConstants.NODESET);
+
+ // Remove each empty text node from document.
+ for (int i = 0; i < emptyTextNodes.getLength(); i++) {
+ Node emptyTextNode = emptyTextNodes.item(i);
+ emptyTextNode.getParentNode().removeChild(emptyTextNode);
+ }
+
+ TransformerFactory tFactory = TransformerFactory.newInstance();
+ tFactory.setAttribute( "indent-number", new Integer(2) );
+ Transformer transformer = tFactory.newTransformer();
+ transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
+ DOMSource domSrc = new DOMSource( dox );
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ StreamResult result = new StreamResult( baos );
+ transformer.transform( domSrc, result );
+
+ return new String( baos.toByteArray() );
+ }
+
+ public boolean streamBindings( File file ) {
+ try {
+ for ( String ns : namespaces.keySet() ) {
+ FileOutputStream os = null;
+ if ( "xsd".equals( ns ) ) {
+ continue;
+ }
+ if ( "owl".equals( ns ) ) {
+ os = new FileOutputStream( file.getParent() + "/global.xjb" );
+ } else if ( "tns".equals( ns ) ) {
+ os = new FileOutputStream( file );
+ } else {
+ os = new FileOutputStream( file.getAbsolutePath().replace( ".xjb", "_" + ns + ".xjb" ) );
+ }
+
+ if ( os != null ) {
+ os.write( compactXML( getBindings( namespaces.get( ns ).getURI() ) ).getBytes() );
+ os.flush();
+ os.close();
+ }
+ }
+ } catch ( Exception e ) {
+ e.printStackTrace();
return false;
}
return true;
View
4 ...-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/XSDModel.java
@@ -20,6 +20,7 @@
import org.jdom.Document;
import org.jdom.Namespace;
+import java.io.File;
import java.io.OutputStream;
import java.util.Collection;
@@ -31,10 +32,13 @@
public boolean stream( OutputStream os );
+ public boolean stream( File file );
+
public Namespace getNamespace( String ns );
public Collection<Namespace> getNamespaces( );
public void setNamespace( String ns, String nameSpace );
+ public void setSchemaMode( String schemMode );
}
View
207 ...pes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/XSDModelImpl.java
@@ -1,44 +1,32 @@
-/*
- * Copyright 2011 JBoss Inc
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
package org.drools.semantics.builder.model;
+import org.drools.io.ResourceFactory;
import org.drools.semantics.utils.NameUtils;
+import org.drools.semantics.utils.NamespaceUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.StringWriter;
+import javax.xml.parsers.DocumentBuilderFactory;
+import java.io.*;
import java.util.*;
public class XSDModelImpl extends ModelImpl implements XSDModel {
private Document schema;
- private Map<String,Namespace> namespaces = new HashMap<String,Namespace>();
+ private Map<Namespace, Document> subSchemas = new HashMap<Namespace, Document>();
+ protected Map<String,Namespace> namespaces = new HashMap<String,Namespace>();
+ private String schemaMode = "";
- XSDModelImpl() {
+ XSDModelImpl() {
}
@@ -48,16 +36,25 @@ public void initFromBaseModel(OntoModel base) {
super.initFromBaseModel(base);
setNamespace( "xsd", "http://www.w3.org/2001/XMLSchema" );
+// setNamespace( "xjc", "http://java.sun.com/xml/ns/jaxb/xjc" );
+
+ schema = initDocument( this.getDefaultNamespace() );
+ }
- schema = new Document();
+ private Document initDocument( String tgtNamespace ) {
+ Document dox = new Document();
Element root = new Element("schema", getNamespace("xsd") );
root.setAttribute( "elementFormDefault", "qualified" );
- root.setAttribute( "targetNamespace", this.getNamespace() );
+ root.setAttribute( "targetNamespace", tgtNamespace );
+ for ( Namespace ns : namespaces.values() ) {
+ root.addNamespaceDeclaration( ns );
+ }
- schema.addContent(root);
+ dox.addContent(root);
+ return dox;
}
public Document getXSDSchema() {
@@ -67,6 +64,37 @@ public Document getXSDSchema() {
public boolean stream( OutputStream os ) {
try {
os.write( serialize( getXSDSchema() ).getBytes() );
+ os.write(getOWLSchema().getBytes());
+ for ( Document dox : subSchemas.values() ) {
+ os.write( serialize( dox ).getBytes() );
+ }
+ } catch (IOException e) {
+ e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
+ return false;
+ }
+ return true;
+ }
+
+ public boolean stream( File file ) {
+ try {
+ FileOutputStream fos = new FileOutputStream( file );
+ fos.write( serialize( getXSDSchema() ).getBytes() );
+ fos.flush();
+ fos.close();
+
+ FileOutputStream owl = new FileOutputStream( file.getParent() + "/owlThing.xsd" );
+ owl.write(getOWLSchema().getBytes());
+ owl.flush();
+ owl.close();
+
+
+ for ( Namespace ns : subSchemas.keySet() ) {
+ String subFileName = file.getAbsolutePath().replace( ".xsd", "_" + ns.getPrefix() + ".xsd" );
+ FileOutputStream subFos = new FileOutputStream( subFileName );
+ subFos.write( serialize( subSchemas.get( ns ) ).getBytes() );
+ subFos.flush();
+ subFos.close();
+ }
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return false;
@@ -84,19 +112,124 @@ public Namespace getNamespace(String ns) {
public void setNamespace( String prefix, String namespace ) {
- Namespace ns = Namespace.getNamespace(prefix, namespace);
+ Namespace ns = Namespace.getNamespace( prefix, namespace );
namespaces.put( prefix, ns );
if ( schema != null ) {
schema.getRootElement().addNamespaceDeclaration( ns );
}
+ for ( Document dox : subSchemas.values() ) {
+ dox.getRootElement().addNamespaceDeclaration( ns );
+ }
}
- public void addTrait(String name, Object trait) {
- getXSDSchema().getRootElement().addContent( (Element) trait );
+ public void addTrait( String name, Object trait ) {
+ Element elx = (Element) trait;
+ String type = elx.getAttributeValue( "type" );
+ if ( type != null ) {
+ boolean mainNamespace = type.startsWith( "tns:" );
+ if ( mainNamespace ) {
+ getXSDSchema().getRootElement().addContent( (Element) trait );
+ } else {
+ Namespace altNamespace = namespaces.get( type.substring( 0, type.indexOf( ":" ) ) );
+ getXSDSchema( altNamespace ).getRootElement().addContent( (Element) trait );
+ }
+ } else {
+ Element typeDef = (Element) trait;
+ Document schema = getXSDSchema( name );
+ schema.getRootElement().addContent( typeDef );
+ if ( typeDef.getName().equals( "complexType" ) ) {
+ Element complexContent = typeDef.getChild( "complexContent", namespaces.get( "xsd" ) );
+ if ( complexContent != null ) {
+ Element base = complexContent.getChild( "extension", namespaces.get( "xsd" ) );
+ if ( base != null ) {
+ String sup = base.getAttributeValue( "base" );
+ if ( sup.indexOf( ":" ) >= 0 ) {
+ String ns = sup.substring( 0, sup.indexOf( ":" ) );
+ String baseNs = namespaces.get( ns ).getURI();
+ String localNs = schema.getRootElement().getAttributeValue( "targetNamespace" );
+ if ( ! localNs.equals( baseNs ) ) {
+ addImport( schema, namespaces.get( ns ) );
+ System.out.println( sup );
+ }
+
+ }
+ }
+ }
+
+ }
+ }
+
}
+ private Document getXSDSchema( String type ) {
+ if ( type.indexOf( ":" ) >= 0 ) {
+ return getXSDSchema();
+ }
+ if ( definesType( getXSDSchema(), type ) ) {
+ return getXSDSchema();
+ }
+ for ( Document sub : subSchemas.values() ) {
+ if ( definesType(sub, type) ) {
+ return sub;
+ }
+ }
+ return getXSDSchema();
+// throw new IllegalStateException( "No schema has been initialized for type " + type );
+ }
+
+ private boolean definesType( Document dox, String name ) {
+ Element schema = dox.getRootElement();
+ List<Element> types = schema.getChildren( "element", Namespace.getNamespace( "xsd", "http://www.w3.org/2001/XMLSchema" ) );
+ for ( Element ct : types ) {
+ String declaredName = ct.getAttributeValue( "name" );
+ if ( declaredName != null && declaredName.equals( name ) ) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private Document getXSDSchema( Namespace altNamespace ) {
+ if ( subSchemas.containsKey( altNamespace ) ) {
+ return subSchemas.get( altNamespace );
+ } else {
+ System.out.println( "Need to create a new schema on the fly " + altNamespace );
+ Document dox = initDocument( altNamespace.getURI() );
+ subSchemas.put( altNamespace, dox );
+
+ addImport( getXSDSchema(), altNamespace );
+ return dox;
+ }
+ }
+
+ private void addImport( Document dox, Namespace altNamespace ) {
+ List<Element> imports = dox.getRootElement().getChildren( "import", NamespaceUtils.getNamespaceByPrefix( "xsd" ) );
+ for ( Element e : imports ) {
+ if ( e.getAttributeValue( "namespace" ).equals( altNamespace.getURI() ) ) {
+ return;
+ }
+ }
+
+ Element imp = new Element( "import", getNamespace( "xsd" ) );
+ imp.setAttribute( "namespace", altNamespace.getURI() );
+ imp.setAttribute( "schemaLocation", getSchemaName( altNamespace ) );
+ System.err.println( "Adding import " + altNamespace + " , just to be sure" );
+
+ dox.getRootElement().addContent( 0, imp );
+ }
+
+ private String getSchemaName( Namespace altNamespace ) {
+ if ( NamespaceUtils.getNamespaceByPrefix( "owl" ).getURI().equals( altNamespace.getURI() ) ) {
+ return "owlThing.xsd";
+ } else {
+ String prefix = NamespaceUtils.compareNamespaces( altNamespace.getURI(), getDefaultNamespace() )
+ ? ""
+ : ( "_" + altNamespace.getPrefix() );
+ return getName() + getSchemaMode() + prefix + ".xsd";
+ }
+ }
public Object getTrait(String name) {
@@ -107,6 +240,7 @@ public Object getTrait(String name) {
public Set<String> getTraitNames() {
Set<String> names = new HashSet<String>();
+ //TODO
return names;
}
@@ -131,4 +265,25 @@ protected String serialize( Document dox ) {
return out.toString();
}
+
+ public String getOWLSchema() {
+ InputStream schemaIS = null;
+ try {
+ schemaIS = ResourceFactory.newClassPathResource("org/drools/semantics/builder/model/compilers/owlThing.xsd").getInputStream();
+ byte[] data = new byte[ schemaIS.available() ];
+ schemaIS.read( data );
+ return new String( data );
+ } catch ( Exception e ) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ public String getSchemaMode() {
+ return schemaMode;
+ }
+
+ public void setSchemaMode(String schemaMode) {
+ this.schemaMode = schemaMode;
+ }
}
View
44 ...main/java/org/drools/semantics/builder/model/compilers/JarInterfaceModelCompilerImpl.java
@@ -24,6 +24,7 @@
import org.drools.factmodel.BuildUtils;
import org.drools.semantics.utils.NameUtils;
import org.drools.semantics.builder.model.*;
+import org.drools.semantics.utils.NamespaceUtils;
import org.mvel2.asm.*;
import javax.persistence.Basic;
@@ -45,9 +46,13 @@ public void setModel(OntoModel model) {
public void compile( Concept con, Object context, Map<String, Object> params ) {
+ if ( "Thing".equals( con.getName() ) && NamespaceUtils.compareNamespaces("http://www.w3.org/2002/07/owl", con.getNamespace()) ) {
+ return;
+ }
+
// if ( ! con.isResolved() ) {
super.compile( con, context, params );
- String name = con.getName().substring( con.getName().lastIndexOf( "." ) + 1 );
+ String name = con.getFullyQualifiedName();
((JarModel) getModel()).addCompiledTrait( name, this.compile( name, params ) );
@@ -73,7 +78,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
AnnotationVisitor av0;
- String pack = ( (String) params.get( "package" ) ).replace( ".", "/" ) + "/";
+// String pack = ( (String) params.get( "package" ) ).replace( ".", "/" ) + "/";
Set<Concept> sup = ( (Set<Concept>) params.get( "superConcepts" ) );
String implInterface = (String) params.get( "implInterface" );
@@ -85,24 +90,24 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
int j = 1;
if ( implInterface != null ) {
- superTypes[ j++ ] = implInterface;
+ superTypes[ j++ ] = implInterface.replace( ".", "/" );
}
for ( Iterator<Concept> iter = sup.iterator(); iter.hasNext(); ) {
- superTypes[ j++ ] = pack + iter.next().getName();
+ superTypes[ j++ ] = iter.next().getFullyQualifiedName().replace( ".", "/" );
}
Map<String, PropertyRelation> props = (Map<String, PropertyRelation>) params.get( "properties" );
cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,
- pack + trait,
+ trait.replace( ".", "/" ),
null,
Type.getInternalName( Object.class ),
superTypes);
{
av0 = cw.visitAnnotation( Type.getDescriptor( RdfsClass.class ), true);
- av0.visit( "value", "tns:" + trait );
+ av0.visit( "value", "tns:" + params.get( "name" ) );
av0.visitEnd();
}
{
@@ -112,7 +117,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
AnnotationVisitor av1 = av0.visitArray( "value" );
av1.visit( null, "tns" );
// av1.visit( null, "http://" + pack + "#" );
- av1.visit( null, getModel().getNamespace() );
+ av1.visit( null, params.get( "namespace" ) );
av1.visitEnd();
}
av0.visitEnd();
@@ -154,13 +159,13 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
PropertyRelation rel = props.get( propKey );
String propName = rel.getName();
propName = propName.substring( 0, 1 ).toUpperCase() + propName.substring( 1 );
- String target = rel.getTarget().getName();
+ String target = rel.getTarget().getFullyQualifiedName();
boolean isBoolean = target.equalsIgnoreCase( "xsd:boolean" );
if ( target.startsWith( "xsd:" ) ) {
target = NameUtils.map( target, rel.getMaxCard() == null || rel.getMaxCard() != 1 );
} else {
- target = pack + target;
+ target = target.replace( ".", "/" );
}
String propType = BuildUtils.getTypeDescriptor( target );
@@ -182,7 +187,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
null);
if ( ! rel.isRestricted() && ! rel.isTransient() ) {
av0 = mv.visitAnnotation( Type.getDescriptor( RdfProperty.class ), true );
- av0.visit( "value", "tns:hasCollectionPoint" );
+ av0.visit( "value", "tns:" + propName );
av0.visitEnd();
if ( rel.isSimple() ) {
av0 = mv.visitAnnotation( Type.getDescriptor( Basic.class ), true );
@@ -229,8 +234,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
if ( rel.isSimple() || ( ( rel.getMaxCard() == null || rel.getMaxCard() > 1 ) && ! rel.isTransient() ) ) {
mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT,
"add" + NameUtils.compactUpperCase( rel.getName() ),
- "(" + BuildUtils.getTypeDescriptor( ( rel.getTarget().isPrimitive() ? "" : pack )
- + NameUtils.map( rel.getTarget().getName(), true ) ) + ")V",
+ "(L" + NameUtils.map( rel.getTarget().getFullyQualifiedName(), true ).replace( ".", "/" ) + ";)V",
null,
null );
{
@@ -272,15 +276,15 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
AnnotationVisitor av0;
- String pack = ( (String) params.get( "package" ) ).replace( ".", "/" ) + "/";
+// String pack = ( (String) params.get( "package" ) ).replace( ".", "/" ) + "/";
Set<Concept> sup = ((Set<Concept>) params.get( "subConcepts" ) );
String[] superTypes = new String[ sup.size() +1 ];
superTypes[0] = Type.getInternalName( SupportsRdfId.class );
int j = 1;
for ( Iterator<Concept> iter = sup.iterator(); iter.hasNext(); ) {
- superTypes[j++] = pack + iter.next().getName() + "$$Shadow";
+ superTypes[j++] = iter.next().getFullyQualifiedName().replace( ".", "/" ) + "$$Shadow";
}
@@ -290,7 +294,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
cw.visit(V1_5, ACC_PUBLIC + ACC_ABSTRACT + ACC_INTERFACE,
- pack + trait,
+ trait.replace( ".", "/" ),
null,
Type.getInternalName( Object.class ),
superTypes);
@@ -306,7 +310,7 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
AnnotationVisitor av1 = av0.visitArray( "value" );
av1.visit( null, "tns" );
// av1.visit( null, "http://" + pack + "#" );
- av1.visit( null, getModel().getNamespace() );
+ av1.visit( null, params.get( "namespace" ) );
av1.visitEnd();
}
av0.visitEnd();
@@ -333,12 +337,12 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
String propName = rel.getName();
propName = propName.substring( 0, 1 ).toUpperCase() + propName.substring( 1 );
//String target = pack + props.get( rel ).getName();
- String target = rel.getTarget().getName();
+ String target = rel.getTarget().getFullyQualifiedName();
boolean isBoolean = target.equalsIgnoreCase( "xsd:boolean" );
if ( target.startsWith("xsd:") ) {
target = NameUtils.map( target, rel.getMaxCard() == null || rel.getMaxCard() != 1 ).replace( ".", "/" );
} else {
- target = pack + target;
+ target = target.replace( ".", "/" );
}
String propType = BuildUtils.getTypeDescriptor( target );
@@ -354,13 +358,13 @@ public void compile( Concept con, Object context, Map<String, Object> params ) {
if ( ! rel.isRestricted() && ! rel.isTransient() ) {
mv = cw.visitMethod( ACC_PUBLIC + ACC_ABSTRACT,
- NameUtils.getter( rel.getName(), rel.getTarget().getName(), rel.getMaxCard() ),
+ NameUtils.getter( rel.getName(), rel.getTarget().getFullyQualifiedName(), rel.getMaxCard() ),
"()" + propType,
genericGetType,
null);
if ( ! rel.isRestricted() && ! rel.isTransient() ) {
av0 = mv.visitAnnotation( Type.getDescriptor( RdfProperty.class ), true );
- av0.visit( "value", "tns:hasCollectionPoint" );
+ av0.visit( "value", "tns:" + propName );
av0.visitEnd();
if ( rel.isSimple() ) {
av0 = mv.visitAnnotation( Type.getDescriptor( Basic.class ), true);
View
50 ...ain/java/org/drools/semantics/builder/model/compilers/JavaInterfaceModelCompilerImpl.java
@@ -17,10 +17,9 @@
package org.drools.semantics.builder.model.compilers;
import org.drools.semantics.builder.DLTemplateManager;
-import org.drools.semantics.builder.model.CompiledOntoModel;
-import org.drools.semantics.builder.model.Concept;
-import org.drools.semantics.builder.model.ModelFactory;
-import org.drools.semantics.builder.model.OntoModel;
+import org.drools.semantics.builder.model.*;
+import org.drools.semantics.utils.NameUtils;
+import org.drools.semantics.utils.NamespaceUtils;
import org.mvel2.templates.CompiledTemplate;
import org.mvel2.templates.TemplateRegistry;
import org.mvel2.templates.TemplateRuntime;
@@ -45,27 +44,35 @@ public void setModel(OntoModel model) {
public void compile( Concept con, Object context, Map<String, Object> params ) {
// if ( ! con.isResolved() ) {
- CompiledTemplate template = registry.getNamedTemplate( templateName );
- CompiledTemplate shadowTemplate = registry.getNamedTemplate( shadowTemplateName );
+ if ( "Thing".equals( con.getName() ) && NamespaceUtils.compareNamespaces("http://www.w3.org/2002/07/owl", con.getNamespace()) ) {
+ return;
+ }
+ CompiledTemplate template = registry.getNamedTemplate( templateName );
+ CompiledTemplate shadowTemplate = registry.getNamedTemplate( shadowTemplateName );
- switch ( getMode() ) {
- case FLAT:
- getModel().flatten();
- break;
- case HIERARCHY:
- getModel().elevate();
- break;
- case LEVELLED:
- getModel().raze();
- break;
- }
- String name = con.getName().substring( con.getName().lastIndexOf( "." ) + 1 );
+ switch ( getMode() ) {
+ case FLAT:
+ getModel().flatten();
+ break;
+ case HIERARCHY:
+ getModel().elevate();
+ break;
+ case LEVELLED:
+ getModel().raze();
+ break;
+ }
- getModel().addTrait( name, TemplateRuntime.execute( template, context, params ).toString().trim() );
+ String name = con.getFullyQualifiedName();
- getModel().addTrait( name+"$$Shadow", TemplateRuntime.execute( shadowTemplate, context, params ).toString().trim());
+ getModel().addTrait( name, new JavaInterfaceModelImpl.InterfaceHolder(
+ TemplateRuntime.execute( template, context, params ).toString().trim(),
+ con.getPackage() ) );
+
+ getModel().addTrait( name+"$$Shadow", new JavaInterfaceModelImpl.InterfaceHolder(
+ TemplateRuntime.execute( shadowTemplate, context, params ).toString().trim(),
+ con.getPackage() ) );
// }
}
@@ -78,4 +85,7 @@ public void setMode(Mode mode) {
public Mode getMode() {
return currentMode;
}
+
+
+
}
View
5 ...nerator/src/main/java/org/drools/semantics/builder/model/compilers/ModelCompilerImpl.java
@@ -45,10 +45,11 @@ public CompiledOntoModel compile( OntoModel model ) {
for ( Concept con : getModel().getConcepts() ) {
String name = NameUtils.compactUpperCase( con.getName() );
Map map = new HashMap();
- map.put( "package", getModel().getPackage() );
- map.put( "namespace", getModel().getNamespace() );
+ map.put( "package", con.getPackage() );
+ map.put( "namespace", con.getNamespace() );
map.put( "iri", con.getIri() );
map.put( "name", con.getName().substring(con.getName().lastIndexOf(".") + 1) );
+ map.put( "fullyQualifiedName", con.getFullyQualifiedName() );
map.put( "superConcepts", con.getSuperConcepts() );
map.put( "subConcepts", con.getSubConcepts() );
map.put( "properties", con.getProperties() );
View
89 .../main/java/org/drools/semantics/builder/model/compilers/SemanticXSDModelCompilerImpl.java
@@ -20,6 +20,8 @@
import org.drools.semantics.builder.DLTemplateManager;
import org.drools.semantics.utils.NameUtils;
import org.drools.semantics.builder.model.*;
+import org.drools.semantics.utils.NamespaceUtils;
+import org.jdom.Namespace;
import org.mvel2.templates.CompiledTemplate;
import org.mvel2.templates.TemplateRegistry;
import org.mvel2.templates.TemplateRuntime;
@@ -32,26 +34,6 @@
public class SemanticXSDModelCompilerImpl extends XSDModelCompilerImpl implements SemanticXSDModelCompiler {
- private static final String defaultBindings = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
- "<bindings xmlns=\"http://java.sun.com/xml/ns/jaxb\"\n" +
- " xmlns:xsi=\"http://www.w3.org/2000/10/XMLSchema-instance\"\n" +
- " xmlns:xjc=\"http://java.sun.com/xml/ns/jaxb/xjc\"\n" +
- " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
- " xmlns:inheritance=\"http://jaxb2-commons.dev.java.net/basic/inheritance\"\n" +
- " xsi:schemaLocation=\"http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd\"\n" +
- " version=\"2.1\"\n" +
- " extensionBindingPrefixes=\"xjc\" >\n" +
- " <bindings>\n" +
- " <globalBindings localScoping=\"toplevel\" >\n" +
- " <serializable/>\n" +
- " <xjc:simple/>\n" +
- " <xjc:treatRestrictionLikeNewType/>\n" +
- " </globalBindings>\n" +
- "\n" +
- " </bindings>\n" +
- "</bindings>";
-
-
private TemplateRegistry registry = DLTemplateManager.getDataModelRegistry( ModelFactory.CompileTarget.XSDX );
protected static final String semGetterTemplateName = "semGetter.drlt";
@@ -62,25 +44,36 @@
private static CompiledTemplate settt;
private static CompiledTemplate chant;
+
@Override
public CompiledOntoModel compile(OntoModel model) {
SemanticXSDModel sxsdModel = (SemanticXSDModel) super.compile(model);
- sxsdModel.setBindings( createBindings( sxsdModel ) );
+
+ for ( Namespace ns : sxsdModel.getNamespaces() ) {
+ sxsdModel.setBindings( ns.getURI(), createBindings( ns.getURI(), sxsdModel ) );
+ }
sxsdModel.setIndex( createIndex( sxsdModel ) );
sxsdModel.setIndividualFactory( compileIntoFactory( sxsdModel ) );
+ sxsdModel.setNamespaceFix( createNSFix() );
+
return sxsdModel;
}
+ private String createNSFix() {
+ HashMap map = new HashMap();
+ map.put( "namespace", getModel().getDefaultNamespace() );
+ return getTemplatedCode( "package-info.java", map, ModelFactory.CompileTarget.JAVA );
+ }
private String compileIntoFactory(SemanticXSDModel sxsdModel) {
try {
Map<String,Object> vars = new HashMap<String, Object>();
- vars.put( "package", sxsdModel.getPackage() );
+ vars.put( "package", sxsdModel.getDefaultPackage() );
vars.put( "individuals", sxsdModel.getIndividuals() );
String index = getTemplatedCode( "IndividualFactory", vars, ModelFactory.CompileTarget.JAVA );
return index;
@@ -95,7 +88,7 @@ private String createIndex( SemanticXSDModel sxsdModel ) {
try {
String template = readFile( "empire.annotation.index.template" );
Map<String,Object> vars = new HashMap<String, Object>();
- vars.put( "package", sxsdModel.getPackage() );
+ vars.put( "package", sxsdModel.getDefaultPackage() );
vars.put( "klasses", sxsdModel.getConcepts() );
String index = TemplateRuntime.eval( template, vars ).toString();
return index;
@@ -107,26 +100,27 @@ private String createIndex( SemanticXSDModel sxsdModel ) {
}
- public void setModel(OntoModel model) {