In my ontology, I have an individual that has this data property
hasName "somaName"^^string,
however, when i'm building a class expression and sending to the reasoner for get the instances, I'm getting an empty set with the following query,
OWLClassExpression x = schema.getFactory().getOWLDataHasValue(schema.getDataProperty("hasName"), schema.getFactory().getOWLLiteral("somaName"));
System.out.println(reasoner.getInstances(x, true));
the getDataProperty is just a small method:
public OWLDataProperty getDataProperty(String dataProperty){
return factory.getOWLDataProperty("#"+dataProperty,pm);
}
The following code snippet works, compare it to your code to see what's different. You should use a reasoner that support this type of construct (Hermit does).
//Initiate everything
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
String base = "http://www.example.org/";
OWLOntology ontology = manager.createOntology(IRI.create(base + "ontology.owl"));
OWLDataFactory factory = manager.getOWLDataFactory();
//Add the stuff to the ontology
OWLDataProperty hasName = factory.getOWLDataProperty(IRI.create(base + "hasName"));
OWLNamedIndividual john = factory.getOWLNamedIndividual(IRI.create(base + "john"));
OWLLiteral lit = factory.getOWLLiteral("John");
OWLDataPropertyAssertionAxiom ax =
factory.getOWLDataPropertyAssertionAxiom(hasName, john, lit);
AddAxiom addAx = new AddAxiom(ontology, ax);
manager.applyChange(addAx);
//Init of the reasoner
//I use Hermit because it supports the construct of interest
OWLReasonerFactory reasonerFactory = new Reasoner.ReasonerFactory();
OWLReasoner reasoner = reasonerFactory.createReasoner(ontology);
reasoner.precomputeInferences();
//Prepare the expression for the query
OWLDataProperty p = factory.getOWLDataProperty(IRI.create(base + "hasName"));
OWLClassExpression ex =
factory.getOWLDataHasValue(p, factory.getOWLLiteral("John"));
//Print out the results, John is inside
Set<OWLNamedIndividual> result = reasoner.getInstances(ex, true).getFlattened();
for (OWLNamedIndividual owlNamedIndividual : result) {
System.out.println(owlNamedIndividual);
}
Related
I try to generate a simple text like this by Java into docx document
This is **bold** test
I search the online this part of the code will be the close one, however it bolds the whole line, not a specific word
ObjectFactory factory = Context.getWmlObjectFactory();
P p = factory.createP();
R r = factory.createR();
Text text = factory.createText();
RPr rpr = factory.createRPr();
text.setValue("This is bold test");
BooleanDefaultTrue boldTrue = new BooleanDefaultTrue();
boldTrue.setVal(Boolean.TRUE);
rpr.setB(boldTrue);
r.getContent().add(text);
p.getContent().add(r);
r.setRPr(this.rpr);
mainDocumentPart.getContent().add(p);
This will bold all the paragraph, however I just want that word "bold" into bold, and keep remain unbold.
How can I fix this?
You can use the docx4j webapp or Word Helper AddIn to generate the code you need from a suitable sample Word docx.
In this case:
// Create object for p
P p = wmlObjectFactory.createP();
// Create object for r
R r = wmlObjectFactory.createR();
p.getContent().add( r);
// Create object for t (wrapped in JAXBElement)
Text text = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped = wmlObjectFactory.createRT(text);
r.getContent().add( textWrapped);
text.setValue( "This is ");
text.setSpace( "preserve");
// Create object for r
R r2 = wmlObjectFactory.createR();
p.getContent().add( r2);
// Create object for rPr
RPr rpr = wmlObjectFactory.createRPr();
r2.setRPr(rpr);
// Create object for b
BooleanDefaultTrue booleandefaulttrue = wmlObjectFactory.createBooleanDefaultTrue();
rpr.setB(booleandefaulttrue);
// Create object for bCs
BooleanDefaultTrue booleandefaulttrue2 = wmlObjectFactory.createBooleanDefaultTrue();
rpr.setBCs(booleandefaulttrue2);
// Create object for t (wrapped in JAXBElement)
Text text2 = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped2 = wmlObjectFactory.createRT(text2);
r2.getContent().add( textWrapped2);
text2.setValue( "bold");
// Create object for r
R r3 = wmlObjectFactory.createR();
p.getContent().add( r3);
// Create object for t (wrapped in JAXBElement)
Text text3 = wmlObjectFactory.createText();
JAXBElement<org.docx4j.wml.Text> textWrapped3 = wmlObjectFactory.createRT(text3);
r3.getContent().add( textWrapped3);
text3.setValue( " test");
text3.setSpace( "preserve");
Then your mainDocumentPart.getContent().add(p);
I want to extract some data from a shapefile,
I have this function that can read a shapefile file is show on a map
i can read some informations but i m lost with extract many info in this file
public class Quickstart {
public static void main(String[] args) throws Exception {
// display a data store file chooser dialog for shapefiles
File file = JFileDataStoreChooser.showOpenFile("shp", null);
if (file == null) {
return;
}
FileDataStore dataStore = FileDataStoreFinder.getDataStore(file);
//SimpleFeatureSource featureSource = dataStore.getFeatureSource();
String t = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(t);
SimpleFeatureType schema = featureSource.getSchema();
//String geomType = schema.getGeometryDescriptor().getType().getBinding().getName();
GeometryDescriptor geom = schema.getGeometryDescriptor();
List<AttributeDescriptor> attributes = schema.getAttributeDescriptors();
GeometryType geomType = null;
List<AttributeDescriptor> attribs = new ArrayList<AttributeDescriptor>();
for (AttributeDescriptor attrib : attributes) {
AttributeType type = attrib.getType();
if (type instanceof GeometryType) {
geomType = (GeometryType) type;
} else {
attribs.add(attrib);
}
}
GeometryTypeImpl gt = new GeometryTypeImpl(
new NameImpl("the_geom"), geomType.getBinding(),
geomType.getCoordinateReferenceSystem(),
geomType.isIdentified(), geomType.isAbstract(),
geomType.getRestrictions(), geomType.getSuper(),
geomType.getDescription());
GeometryDescriptor geomDesc = new GeometryDescriptorImpl(
gt, new NameImpl("the_geom"),
geom.getMinOccurs(), geom.getMaxOccurs(),
geom.isNillable(), geom.getDefaultValue());
attribs.add(0, geomDesc);
SimpleFeatureType shpType = new SimpleFeatureTypeImpl(
schema.getName(), attribs, geomDesc,
schema.isAbstract(), schema.getRestrictions(),
schema.getSuper(), schema.getDescription());
dataStore.createSchema(shpType);
CachingFeatureSource cache = new CachingFeatureSource(featureSource);
// Create a map context and add our shapefile to it
MapContext map = new DefaultMapContext();
map.setTitle("Using cached features");
map.addLayer(cache, null);
// Now display the map
JMapFrame.showMap(map);
}
i want to extract this information :
POLYGON((0.6883 49.4666,0.6836 49.4664,0.6836 49.4663,0.6841 49.466,0.6844 49.4658,0.6847 49.4653,0.685 49.465,
0.6852 49.4646,0.6865 49.4624,0.6868 49.4621,0.6869 49.4618,0.6873 49.4617,0.6874 49.4617,0.6878 49.4616,0.6884 49.4615,
0.6898 49.4614,0.6909 49.4613,0.6909 49.4618,0.6913 49.4618,0.6906 49.4667,0.6883 49.4666))
I do not know how to do
plz help
It is hard to see how that snippet is giving you any attributes back.
If you want the geometry of a feature then you need to use
Geometry geom = feature.getDefaultGeometry();
to write it out as Well Known Text (WKT) you can use the .toString() method or use a WKTWriter to give you greater control over the formatting.
I'd like to highlight the whole not analyzed fields if they match the search query.
The indexed entity looks as follows:
#Entity
#Indexed
#AnalyzerDef(
name = "documentAnalyzer",
tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class),
filters = {
#TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(
factory = StopFilterFactory.class,
params = {
#Parameter(name = "words", value = "stoplist.properties"),
#Parameter(name = "ignoreCase", value = "true")
}
)
}
)
public class Document {
...
#Field(analyze = Analyze.NO)
private String notAnalyzedField; // has "x-xxx-xxx" format
#Field(analyze = Analyze.YES)
private String analyzedField;
}
Suppose I have a Document with notAnalyzedField: "a-bbb-ccc", then I run a search query with the same value and highlight search results using the following code:
String highlightText(Query query, Analyzer analyzer, String fieldName, String text) {
QueryScorer queryScorer = new QueryScorer(query);
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span>", "</span>");
Highlighter highlighter = new Highlighter(formatter, queryScorer);
return highlighter.getBestFragment(analyzer, fieldName, text);
}
As a result I get the following snippet:"a-<span>bbb</span>-<span>ccc</span>".
And it seems reasonable because the analyzer treats a symbol as a stop word and - as a delimiter and doesn't highlight them. But I cannot figure out how I can avoid using analyzer while highlighting this field. There are a few methods in Highlighter class that require TokenStream instead of Analyzer but I'm not sure how to use them.
A result I want to achieve is the whole highlighted field: "<span>a-bbb-ccc</span>"
Is there a way to achieve this with hibernate-search?
Where does your analyzer come from?
You might want to get it from Hibernate Search:
FullTextEntityManager em = /*...*/;
Analyzer analyzer = em.getSearchFactory()
.getAnalyzer(Document.class);
highlightText(query, analyzer, fieldName, text);
If it doesn't work, try using a KeywordAnalyzer: highlightText(query, new KeywordAnalyzer(), fieldName, text);
I have my class Alert which contain as individual
Alert_1
Alert_2
Alert_3
and each individual has properties witch contains values
for example
Alert_1 :
hasanalyser : analyser546
hastime: 10
hasdatainfo: difficult
I can now get all individuals but I can not get those (hasanalyser, hastime and hasdatainfo) values
Here is my code and it works. How I can get what I want please?
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");
OntModel model = owlModel.getOntModel();
OWLNamedClass theAlert = owlModel.getOWLNamedClass("Alert");
Collection CAlerte = theAlert.getInstances();
int nombreAlerte =CAlerte.size();
String[ ] list_alerte=new String[ nombreAlerte ];
OWLIndividual[ ] idorg=(OWLIndividual[ ]) CAlerte.toArray(new OWLIndividual[ 0 ]);
for(int j=0;j< nombreAlerte;j++){
list_alerte[ j ]=idorg[ j ].getName();
}
System.out.println(" le nombres des alerte est:"+nombreAlerte);
OntModel inf1 = ModelFactory.createOntologyModel();
for(int k=0;k< nombreAlerte;k++){
System.out.println(" \n"+list_alerte[k]);
}
Here it display my
Alert_1
Alert_2
Alert_3
How to get their properties?
UPDATE:
Thanks for your answer, it doesn't work yet. I tried now to do like you said
JenaOWLModel owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");
OntModel model = owlModel.getOntModel();
ArrayList<Resource> results = new ArrayList<Resource>();
ExtendedIterator individuals = model.listIndividuals();
while (individuals.hasNext()) {
Resource individual = (Resource) individuals.next();
results.add(individual);
}
for(int i = 0; i < results.size(); i++)
{
System.out.println("individual number " + i + " = " + results.get(i));//here it display my individual
Individual ind = model.getIndividual(results.get(i).toString());
Property hasTime = model.createProperty( "file:///D:/base_connaissance.owl#hasanalyser" );
RDFNode time = ind.getPropertyValue( hasTime );
System.out.println("property value of hasanalyser "+time);
At the end it displays all names of my individuals, and after each individual it display property value of hasanalyser NULL.
where is the problème please
IT WORK NOW , i can get now all properties of all individuals thanks lot , now what it doesnt work is HOW to add an individual and add properties to this individual and insert it into my "base_connaissance.owl" if you can help me i realy appreciate it here is the full code witch work perfectly .
static JenaOWLModel owlModel ;
public static void main(String[] args) {
OntModel model;
javax.swing.JDialog jDialog1 = new javax.swing.JDialog();
try{
String ns="file:///D:/base_connaissance.owl#";
owlModel = ProtegeOWL.createJenaOWLModelFromURI("file:///D:/base_connaissance.owl");// crée un modele owl a partir du ficher owl charger
model = owlModel.getOntModel();
JOptionPane.showMessageDialog(jDialog1,"chargement du fichier effectuer avec succé","Information",JOptionPane.INFORMATION_MESSAGE);
ArrayList<Resource> results = new ArrayList<Resource>();
ExtendedIterator individuals = model.listIndividuals();
while (individuals.hasNext()) {
Resource individual = (Resource) individuals.next();
results.add(individual);
}
System.out.println("\n");
for(int i = 0; i < results.size(); i++)
{
Individual ind = model.getIndividual(results.get(i).toString());
System.out.println(""+ind);
StmtIterator it = ind.listProperties();
while ( it.hasNext()) {
Statement s = (Statement) it.next();
if (s.getObject().isLiteral()) {
System.out.println(""+s.getLiteral().getLexicalForm().toString()+" type = "+s.getPredicate().getLocalName());
}
else System.out.println(""+s.getObject().toString().substring(53)+" type = "+s.getPredicate().getLocalName());
}
System.out.println("\n");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(jDialog1,
"error",
"Information",
JOptionPane.INFORMATION_MESSAGE);
}
}
I'm not clear from your code how you are using Jena models. The OntModel called model does not appear to be used, nor does the InfModel called inf1. OWLIndividual is not a Jena class, but a Protégé one. The question asks about using the Jena API, however, so the rest of this answer assumes that you can get the Individuals that you are interested in, not the OWLIndividuals.
Jena's Individuals have a method getPropertyValue that returns the value of a property for the individual. You should be able to do something like this:
Individual alert1 = ...;
String hasTimeURI = "...";
Property hasTime = model.createProperty( hasTimeURI );
RDFNode time = alert1.getPropertyValue( hasTime );
The additional code you posted is printing null probably because the IRI for the property is incorrect. File-based IRIs are not very good identifiers; URIs are supposed to be universal identifiers, and something that includes a file path almost certainly isn't going to be universal. Without seeing your data, we cannot know what the proper IRI for the property should be. However, if you do something like this, you should be able to get enough information to determine what the property IRI should be.
Individual ind = model.getIndividual(results.get(i).toString());
// Check whether ind is null.
System.out.println( "ind: "+ind );
// Iterate over all the statements that have ind as subject.
StmtIterator it = ind.ListProperties();
while ( it.hasNext() ) {
System.out.println( it.next() );
}
I'm currently following the Jena API inferencing tutorial:
https://jena.apache.org/documentation/inference/
and as an exercise to test my understanding, I'd like to rewrite the first example, which demonstrates a trivial RDFS reasoning from a programmatically built model:
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.vocabulary.*;
public class Test1 {
static public void main(String...argv) {
String NS = "foo:";
Model m = ModelFactory.createDefaultModel();
Property p = m.createProperty(NS, "p");
Property q = m.createProperty(NS, "q");
m.add(p, RDFS.subPropertyOf, q);
m.createResource(NS + "x").addProperty(p, "bar");
InfModel im = ModelFactory.createRDFSModel(m);
Resource x = im.getResource(NS + "x");
// verify that property q of x is "bar" (which follows
// from x having property p, and p being a subproperty of q)
System.out.println("Statement: " + x.getProperty(q));
}
}
to something which does the same, but with the model read from this Turtle file instead (which is my own translation of the above, and thus might be buggy):
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>.
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>.
#prefix foo: <http://example.org/foo#>.
foo:p a rdf:Property.
foo:q a rdf:Property.
foo:p rdfs:subPropertyOf foo:q.
foo:x foo:p "bar".
with this code:
public class Test2 {
static public void main(String...argv) {
String NS = "foo:";
Model m = ModelFactory.createDefaultModel();
m.read("foo.ttl");
InfModel im = ModelFactory.createRDFSModel(m);
Property q = im.getProperty(NS + "q");
Resource x = im.getResource(NS + "x");
System.out.println("Statement: " + x.getProperty(q));
}
}
which doesn't seem to be the right approach (I suspect in particular that my extraction of the q property is somehow not right). What am I doing wrong?
String NS = "foo:";
m.createResource(NS + "x")
creates a URI but the Turtle version has foo:x = http://example.org/foo#x
See the differences by printing the model im.write(System.out, "TTL");
Change NS = "foo:" to NS = "http://example.org/foo#"