Java Code Examples for com.hp.hpl.jena.ontology.OntModel

The following are top voted examples for showing how to use com.hp.hpl.jena.ontology.OntModel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: t5-doc   File: XMLToRDFConverter.java   Source Code and License 7 votes vote down vote up
private void triplifyChildNodes(OntModel modelAbox, Individual ind, NodeList nlist) {
	// Elements order may be relevant. Keep track of index within same tag name group

	String currentTagName = "";
	int elemTagIndex = 0;

	for (int j = 0; nlist != null && j < nlist.getLength(); j++) {
		Node node = nlist.item(j);
		if (node.getNodeType() != Node.ELEMENT_NODE)
			continue;
		Element elem = (Element) nlist.item(j);
		if (elem.getNodeName().equals(currentTagName)) {
			elemTagIndex++;
		} else {
			elemTagIndex = 0;
			currentTagName = elem.getNodeName();
		}

		triplifyElement(elem, elemTagIndex, ind, modelAbox);
	}
}
 
Example 2
Project: OntologyBasedInormationExtractor   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    OntoManager om = OntoManager.getInstance();
    om.load();
    OntModel model = om.getModel();
    final String NS = om.getOntologyIRI() + "#";
    logger.info(NS);

    Scanner s = new Scanner(System.in);

    while (true) {

        System.out.println("enter:");
        String clsName = s.nextLine();
        System.out.println("enhancing for: |"+clsName+"|");
        if(clsName.equalsIgnoreCase("exit"))break;
        OntClass pCls = model.getOntClass(NS + clsName);
        if(pCls==null){
            System.err.println("class does not exist");
            continue;
        }

        LinguisticEnhancer le = new LinguisticEnhancer();
        List<SynSuggestion> suggestions = le.suggestLinguisticData(pCls);


        // exclude name + labels , syn includes etc when adding syn includes

        //for suspects
        for (SynSuggestion sug : suggestions) {
            logger.debug(sug.toString());
            if (true) {
                List<String> excludeList = le.getAllExcludes(pCls, le.getClassLabels(pCls).toArray(new String[0]));
                le.addSuggestion(pCls, sug, excludeList);
            }
        }

        om.save();
    }
}
 
Example 3
Project: BimSPARQL   File: QueryFunctionTest.java   Source Code and License 6 votes vote down vote up
public static OntModel loadDefaultModel(){
	InputStream in = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("Duplex_A_20110505.ttl");
	Model model=ModelFactory.createDefaultModel();
	model.read(in,null,"TTL");
	InputStream ins = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("IFC2X3_TC1.ttl");
	InputStream input = BodyGeometryTest.class.getClassLoader()
			.getResourceAsStream("Duplex_A_20110505_geometry.ttl");
	Model geometryModel=ModelFactory.createDefaultModel();
	geometryModel.read(input,null,"TTL");
	Model schema=ModelFactory.createDefaultModel();
	schema.read(ins,null,"TTL");	
		try {
			BimSPARQL.init(model,geometryModel);
		} catch (ClassNotFoundException | IOException | ParserConfigurationException | SAXException
				| URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	OntModel ontology=ModelFactory.createOntologyModel();
	ontology.add(schema);
	ontology.add(model);
	ontology.add(geometryModel);
	return ontology;
}
 
Example 4
Project: StreamEventCoreference   File: OwlReader.java   Source Code and License 6 votes vote down vote up
static void readOwlFile (String pathToOwlFile) {
        OntModel ontologyModel =
                ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
        ontologyModel.read(pathToOwlFile, "RDF/XML-ABBREV");
       // OntClass myClass = ontologyModel.getOntClass("namespace+className");

        OntClass myClass = ontologyModel.getOntClass(ResourcesUri.nwr+"domain-ontology#Motion");
        System.out.println("myClass.toString() = " + myClass.toString());
        System.out.println("myClass.getSuperClass().toString() = " + myClass.getSuperClass().toString());

        //List list =
              //  namedHierarchyRoots(ontologyModel);


       Iterator i = ontologyModel.listHierarchyRootClasses()
                .filterDrop( new Filter() {
                    public boolean accept( Object o ) {
                        return ((Resource) o).isAnon();
                    }} ); ///get all top nodes and excludes anonymous classes

       // Iterator i = ontologyModel.listHierarchyRootClasses();
        while (i.hasNext()) {
            System.out.println(i.next().toString());
/*            OntClass ontClass = ontologyModel.getOntClass(i.next().toString());
            if (ontClass.hasSubClass()) {

            }*/
        }

        String q = createSparql("event", "<http://www.newsreader-project.eu/domain-ontology#Motion>");
        System.out.println("q = " + q);
        QueryExecution qe = QueryExecutionFactory.create(q,
                ontologyModel);
        for (ResultSet rs = qe.execSelect() ; rs.hasNext() ; ) {
            QuerySolution binding = rs.nextSolution();
            System.out.println("binding = " + binding.toString());
            System.out.println("Event: " + binding.get("event"));
        }

        ontologyModel.close();
    }
 
Example 5
Project: JenaKBClient   File: KBIndividualImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSomeMethod2() throws Exception {
  Dataset ds = TDBFactory.createDataset("/scratch/WORK2/jena/dataset2/");
  
  OntModel model1 = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, ds.getNamedModel("vijaym1"));
  OntModel model2 = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, ds.getNamedModel("vijaym2"));
  OntClass thing = model1.createClass("http://www.w3.org/2002/07/owl#Thing");
  model1.createIndividual("http://example.com/onto1#VijayRaj", thing);
  model2.createIndividual("http://example.;cegilovcom/onto2#VijayRaj", thing);
  Model m = model1.union(model2);
  
  FileWriter fw = new FileWriter("/scratch/WORK2/jena/testModels/mergetestds.xml");
  RDFDataMgr.write(fw, ds, RDFFormat.NQUADS_UTF8);
  

}
 
Example 6
Project: ExpertFinder   File: ExpertiseModel.java   Source Code and License 6 votes vote down vote up
private void calcSim() {
	OntologyIndex.get().load(OntologyIndex.class.getResource(Config.getAppProperty(Config.Key.ONTOLOGY_FILE)));
	
	OntologyIndex oi = OntologyIndex.get();
	OntModel model = oi.getModel();
	
	persistenceStore.beginTransaction();
	Query query = persistenceStore.createHQLQuery("from Concept");
	List<Concept> concepts1 = (List<Concept>)query.list();

	Query query1 = persistenceStore.createHQLQuery("from Concept");
	List<Concept> concepts2 = (List<Concept>)query1.list();
	persistenceStore.endTransaction();

	for (Concept co1 : concepts1) {
		OntClass c1 = model.getOntClass(co1.getUri());
		for (Concept co2 : concepts2) {
				OntClass c2 = model.getOntClass(co2.getUri());
		}
	}
}
 
Example 7
Project: u-qasar.platform   File: UQasarUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the user entities to rdf
 */
private static OntModel writeUserEntries() {
	OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
	try {
		thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
		InitialContext ic = new InitialContext();
		UserService userService = (UserService) ic.lookup("java:module/UserService");
		List<User> users = userService.getAll();
		for (User u : users) {
			writer.save(u);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return model;
}
 
Example 8
Project: u-qasar.platform   File: UQasarUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Writes the project entities to rdf
 */
private static OntModel writeProjectEntries() {
	OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
	try {
		thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
		InitialContext ic = new InitialContext();
		TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");
		List<Project> projects = treeNodeService.getAllProjects();
		for (Project proj : projects) {
			writer.save(proj);
		}

	} catch (Exception e) {
		e.printStackTrace();
	}
	return model;
}
 
Example 9
Project: u-qasar.platform   File: UQasarUtil.java   Source Code and License 6 votes vote down vote up
/**
	 * Read the RDF model from files.
	 */
	public static void readSemanticModelFiles() {
		logger.debug("Reading the model from a file");
		// Read the model to an existing model
		String dataDir = UQasarUtil.getDataDirPath();
		String modelPath = "file:///" + dataDir + ONTOLOGYFILE;
//		String modelPath = "file:///C:/nyrhinen/Programme/jboss-as-7.1.1.Final/standalone/data/uq-ontology-model.rdf";

		OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
		RDFDataMgr.read(model, modelPath);
		// Test output to standard output
		//		RDFDataMgr.write(System.out, uqModel, RDFFormat.RDFXML_PRETTY);
		logger.debug("Model read from file " +modelPath);
		UQasarUtil.setUqModel(model);
		System.out.println("Reading done.");
	}
 
Example 10
Project: sadlos2   File: JenaTranslatorPlugin.java   Source Code and License 6 votes vote down vote up
public List<ModelError> translateAndSaveModel(OntModel model, String translationFolder,
	String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException {

// Jena models have been saved to the OwlModels folder by the ModelManager prior to calling the translator. For Jena
//	reasoners, no additional saving of OWL models is need so we can continue on to rule translation and saving.
if (errors != null) {
	errors.clear();
}
if (model == null) {
	return addError("Cannot save model in file '" + saveFilename + "' as it has no model.");
}
if (modelName == null) {
	return addError("Cannot save model in file '" + saveFilename + "' as it has no name.");
}

      if (saveRuleFileAfterModelSave) {
	String ruleFilename = createDerivedFilename(saveFilename, "rules");
	String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename;
       translateAndSaveRules(model, null, modelName, fullyQualifiedRulesFilename);
      }
      saveRuleFileAfterModelSave = false;	// reset
return (errors != null && errors.size() > 0) ? errors : null;
  }
 
Example 11
Project: sadlos2   File: ConfigurationManagerForIDE.java   Source Code and License 6 votes vote down vote up
@Override
public OntModel loadOntModel(String owlFilename) {
	try {
		FileInputStream is = new FileInputStream(new File(owlFilename));
		return initOntModel(is, getOwlFormatFromFile(owlFilename));
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
	boolean savePI = ontModel.getDocumentManager().getProcessImports();
	ontModel.getDocumentManager().setProcessImports(false);
	try {
		ontModel.read(owlFilename, getOwlFormatFromFile(owlFilename));
	}
	finally {
		ontModel.getDocumentManager().setProcessImports(savePI);
	}
	return ontModel;
}
 
Example 12
Project: sadlos2   File: ConfigurationManager.java   Source Code and License 6 votes vote down vote up
private Map<String, String> listSubModelsAndPrefixes(Map<String, String> map, OntModel m, String modelUri) {
	Ontology onto = m.getOntology(modelUri);
	if (onto != null) {
		String prefix = m.getNsURIPrefix(modelUri);
		if (prefix == null) {
			prefix = getGlobalPrefix(modelUri);
		}
		if (!map.containsKey(modelUri)) {
			map.put(modelUri, prefix);
		}
		ExtendedIterator<OntResource> importsItr = onto.listImports();
		if (importsItr.hasNext()) {
			while (importsItr.hasNext()) {
				OntResource or = importsItr.next();
				logger.debug("Ontology of model '" + modelUri + "' has import '" + or.toString() + "' with prefix '" + prefix + "'");
				if (!map.containsKey(or.toString())) {
					OntModel submodel = m.getImportedModel(or.getURI());
					if (submodel != null) {
						map = listSubModelsAndPrefixes(map, submodel, or.getURI());
					}
				}
			}
		}
	}
	return map;
}
 
Example 13
Project: sadlos2   File: SadlServerPEImpl.java   Source Code and License 6 votes vote down vote up
@Override
public boolean addImport(String modelName, String importedModelUri) throws ConfigurationException, IOException, InvalidNameException, URISyntaxException {
	try {
		String altImportUrl = getConfigurationMgr().getAltUrlFromPublicUri(importedModelUri);
		OntModel model = getOntModelForEditing(modelName);
		Resource importingOntology = model.getOntology(modelName);
		if (importingOntology == null) {
			importingOntology = model.createResource(modelName);
		}
		model.getOntology(modelName).addImport(importingOntology);
		model.loadImports();
		return true;
	} catch (ConfigurationException e) {
		throw new ConfigurationException("Model cannot be imported as its location is unknown.", e);
	}
}
 
Example 14
Project: Curso2014-2015   File: Task05.java   Source Code and License 6 votes vote down vote up
public static void main(String args[])
{
	String filename = "example4.rdf";
	
	// Create an empty model
	OntModel model = ModelFactory.createOntologyModel(OntModelSpec.RDFS_MEM);
	
	// ** TASK 5.1: Read the ontology from the given file **
	// Use the FileManager to find the input file
	InputStream in = FileManager.get().open(filename);

	if (in == null)
		throw new IllegalArgumentException("File: "+filename+" not found");

	// Read the RDF/XML file
	model.read(in, null);
	
	// ** TASK 5.2: Write the ontology **
	model.write(System.out, "RDF/XML-ABBREV");
}
 
Example 15
Project: com.inova8.remediator   File: Dataset.java   Source Code and License 6 votes vote down vote up
protected void updatePropertyPartition(OntModel partitionModel) {
	Query query = QueryFactory.create(propertyPartitionQuery);
	QueryExecution qexec = QueryExecutionFactory.create(query,
			partitionModel);

	try {
		ResultSet results = qexec.execSelect();
		for (; results.hasNext();) {
			QuerySolution soln = results.nextSolution();
			OntResource property = soln.getResource("property").as(
					OntResource.class);
			partitions.addPropertyPartition(property, null);
		}
	} catch (Exception e) {
		Log.debug(Dataset.class,
				"Failed to execute to execute propertyPartitionQuery");
	} finally {
		qexec.close();
	}
}
 
Example 16
Project: sadlos2   File: JenaTranslatorPlugin.java   Source Code and License 6 votes vote down vote up
private boolean translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName, String filename) throws TranslationException, IOException {
	if (ruleList == null || ruleList.size() < 1) {
		throw new TranslationException("No rules provided to rule translation.");
	}
	// Open file and output header and imports
	File ruleFile = new File(filename);
	if (ruleFile.exists()) {
		boolean success = ruleFile.delete();
		if (!success) {
			addError("Failed to delete old rules file '" + filename + "'.");
			logger.error("Failed to delete old rule file '" + filename + "'.");
			if (ruleList == null || ruleList.size() == 0) {
				setTheModel(null);
				setModelName(null);
				return false;   
			}
			// else don't return--maybe we can open it for output anyway
		}
	}
	String jenaRules = translateAndSaveRules(model, ruleList, modelName) ;
	SadlUtils su = new SadlUtils();
	su.stringToFile(ruleFile, jenaRules, true);
	return (errors== null || errors.size() == 0) ? true : false;
}
 
Example 17
Project: sadlos2   File: JenaReasonerPlugin.java   Source Code and License 6 votes vote down vote up
private String getBaseUriOfModel(OntModel model) {
	String modelBaseUri = null;
	Set<String> importuris = model.listImportedOntologyURIs(true);
	ExtendedIterator<Ontology> ontItr = model.listOntologies();
	if (ontItr.hasNext()) {
		while (ontItr.hasNext()) {
			Ontology ont = ontItr.next();
			if (modelBaseUri == null) {
				modelBaseUri = ont.getURI();	// first is default incase imports are circular
			}
			if (!importuris.contains(ont.getURI())) {
				modelBaseUri = ont.getURI();
				break;
			}
		}
	}
	return modelBaseUri;
}
 
Example 18
Project: sadlos2   File: SadlJenaModelGetter.java   Source Code and License 6 votes vote down vote up
public boolean configureToModel(OntModel m) {
	ModelGetter mg = m.getSpecification().getImportModelGetter();
	if (mg.equals(this)) {
		return false;
	}
	else if (mg.getClass().equals(this.getClass())) {
		return false;
	}
	else if (originalModelGetter == null) {
		originalModelGetter = mg;
		m.getSpecification().setImportModelGetter(this);
		return true;
	}
	else {
		m.getSpecification().setImportModelGetter(this);
		return true;
	}
}
 
Example 19
Project: 2014-trires   File: UsuariosService.java   Source Code and License 6 votes vote down vote up
public OutputStream listarTodosRdf(String urlBase){
	OutputStream ret = new ByteArrayOutputStream();
	OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
	model.setNsPrefix( "trires", Constantes.ONTO_URI );
	
	CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
	CriteriaQuery<Usuario> criteriaQuery = criteriaBuilder.createQuery(Usuario.class);
	Root<Usuario> from = criteriaQuery.from(Usuario.class);
	criteriaQuery.select(from);
	List<Usuario> gruposTrabalho = entityManager.createQuery(criteriaQuery).getResultList();
	for (Usuario usuario : gruposTrabalho) {
		Resource recurso = model.createResource(Constantes.USUARIO_URI + usuario.getId().toString());
		recurso.addProperty(RDF.type, VocabularioMembro.RDF_TYPE_CLASS);
		recurso.addProperty(VocabularioMembro.ID, usuario.getId().toString());
		recurso.addProperty(VocabularioMembro.DESCRICAO, usuario.getDescricao());
		recurso.addProperty(VocabularioMembro.EMAIL, usuario.getEmail());
		recurso.addProperty(VocabularioMembro.INSTITUICAO, usuario.getInstituicao());
		recurso.addProperty(VocabularioMembro.LINK_LATTES, usuario.getLinkLattes());
		recurso.addProperty(VocabularioMembro.NOME, usuario.getNome());
	}
	model.write(ret, "RDF/XML");
	model.close();
	return ret;
}
 
Example 20
Project: sadlos2   File: SadlServerPEImpl.java   Source Code and License 6 votes vote down vote up
@Override
public boolean updateRdfsLabel(String modelName, String uri, String label, String language) throws IOException, ConfigurationException, InvalidNameException, URISyntaxException {
	OntModel ontModel = getOntModelForEditing(modelName);
	boolean retval = false;
	if (ontModel != null) {
		OntResource rsrc = ontModel.getOntResource(uri);
		if (rsrc == null) {
			throw new InvalidNameException("'" + uri + "' was not found in model '" + modelName + "'");
		}
		String lbl = rsrc.getLabel(language);
		if (lbl != null) {
			if (!lbl.equals(label)) {
				rsrc.removeLabel(lbl, language);
				retval = true;
			}
		}
		rsrc.addLabel(label, language);
	}
	return retval;
}
 
Example 21
Project: SemanticSCo   File: SemanticReasoner.java   Source Code and License 5 votes vote down vote up
public LinkedList<SemanticConcept> findAllLabels(String ontologyUri,String rootClass){
    
    LinkedList<SemanticConcept> list = new LinkedList<>();
    
    try{
    
        //Create a reasoner
        OntModel model = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC);

        //Create new URL of ontology
        URL url = new URL(ontologyUri);
    
        //Create model for the ontology
        model.read(url.openStream(),null);
    
        //Load model to the reasoner
        model.prepare();
    
        //Compute the classification tree
        ((PelletInfGraph) model.getGraph()).getKB().classify();
        
        //Set OWL root element (e.g., it could be thing: model.getOntClass(OWL.Thing.getURI()))
        OntClass owlRoot = model.getOntClass(rootClass);
        
        SemanticConcept sc = new SemanticConcept();
        sc.setUrl(owlRoot.getURI());
        sc.setName("");
        sc.setSemanticSimilarity("");
        list.add(sc);
    
        //For each subclass (direct or indirect)
        for (Iterator it = owlRoot.listSubClasses(false); it.hasNext();) {

            OntClass subclass = (OntClass) it.next();

            //If subclass is not anonymous
            if (!subclass.isAnon()) {

                //If subclass is not nothing
                if(!subclass.getURI().equals(com.hp.hpl.jena.vocabulary.OWL.Nothing.getURI())){
                    
                    sc = new SemanticConcept();
                    sc.setUrl(subclass.getURI());
                    sc.setName("");
                    sc.setSemanticSimilarity("");
                
                    list.add(sc);
                }
            }
        }
        
    }catch(IOException ex){}
    
    return list;
    
}
 
Example 22
Project: zebra-puzzle-workshop   File: Exercise4.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 23
Project: zebra-puzzle-workshop   File: Exercise32.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel(String modelInput) {
    Reasoner reasoner = PelletReasonerFactory.theInstance().create();
    Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
    OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
    ontModel.read(getClass().getResourceAsStream("/" + modelInput), null, TTL);
    return ontModel;
}
 
Example 24
Project: zebra-puzzle-workshop   File: Exercise4Jena.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 25
Project: zebra-puzzle-workshop   File: Exercise.java   Source Code and License 5 votes vote down vote up
protected List<Individual> getIndividuals(OntModel model) {
  List<Individual> individuals = new ArrayList<Individual>();
  ExtendedIterator<Individual> iterator = model.listIndividuals();
  while (iterator.hasNext()) {
    individuals.add(iterator.next());
  }
  return individuals;
}
 
Example 26
Project: zebra-puzzle-workshop   File: Exercise4.java   Source Code and License 5 votes vote down vote up
protected OntModel readModel() {
  Reasoner reasoner = PelletReasonerFactory.theInstance().create();
  Model infModel = ModelFactory.createInfModel(reasoner, ModelFactory.createDefaultModel());
  OntModel ontModel = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, infModel);
  ontModel.read(getClass().getResourceAsStream("/" + modelBase), null, TTL);
  return ontModel;
}
 
Example 27
Project: zebra-puzzle-workshop   File: Exercise.java   Source Code and License 5 votes vote down vote up
protected List<Individual> getIndividuals(OntModel model) {
  List<Individual> individuals = new ArrayList<Individual>();
  ExtendedIterator<Individual> iterator = model.listIndividuals();
  while (iterator.hasNext()) {
    individuals.add(iterator.next());
  }
  return individuals;
}
 
Example 28
Project: c4a_data_repository   File: RuleEngine.java   Source Code and License 5 votes vote down vote up
/**
 * This method search in geocitties Ontology to obtain a valid URI containing the city information
 *
 * @param pCity The name of the city to search
 * @return A statmenet contianing the needed knowledge to link a city with its information
 */
private void obtainCityInformation(String pCity, OntModel pModel) {

    // Making the call to geoname database
    //TODO put this url as a static final value at top of this file
    String query = "http://api.geonames.org/search?name_equals="+pCity+"&featureClass=P&type=rdf&&username=elektro";
    ProcessBuilder p = new ProcessBuilder("curl", "-X", "POST", query);
    try {
        System.out.println("Calling to geocities about city information from: "+pCity +"\n");
        LOGGER.info("--> obtainCityInformation: Calling to geocities to obtain information from: "+ pCity);
        // Execute our command
        final Process shell = p.start();
        // catch output and see if all is ok
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(shell.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        // Filling with information the string builder list
        while ((line = reader.readLine()) != null) {
            // with the actual line we need to extract a defiend pattern
            if (line.contains("<gn:Feature rdf:about=") || line.contains("<rdfs:seeAlso rdf:resource=\"http://dbpedia.org/resour")) {
                // Regex pattern to extract the needed URI
                Pattern pattern = Pattern.compile("\"(.*?)\"");
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    // Obtaining the needed resource

                    // CAmbiar por el mimso sujeto de arriba que /City4age_ar/pilot/***
                    // y SR -_-

                    Resource subject = pModel.getResource(c4aBaseURI+"City");
                    // Obtaining the needed property
                    Property predicate = pModel.getProperty("owl:sameAS");
                    // Adding the URIS (They are not literal)
                    Resource object = ResourceFactory.createResource(matcher.group(1));
                    // Creating the logical statement
                    //use add property
                    pModel.add(subject, predicate, object);
                    //pModel.add(subject2, predicate, object);
                }else {
                    // we are only to save the problem, but not raise any error.
                    LOGGER.warning("--> obtainCityInformation: We found a possible resource but the Regex matcher" +
                            "is failing for some reason: "+line);
                }
            }
        }
        //System.out.println("Call succeeded. The size of new statement is: "+listStatements.size());
        //LOGGER.info("Call successful. The size of new statements is: "+listStatements.size());
    } catch (IOException e) {
        LOGGER.severe("--> obtainCityInformation: Fatal IO error detected in ProcessBuilder call");
        e.printStackTrace();
    }
}
 
Example 29
Project: c4a_data_repository   File: RuleEngine.java   Source Code and License 5 votes vote down vote up
/**
 * Prints the actual knowledge with the actual execution number and what new statements are created with
 * ruleEngine
 *
 *
 * @param pOntology: The actual knowledge ( Base + inferred)
 * @param pInf: The list containing the inferred elements.
 */
private void printResults(OntModel pOntology, InfModel pInf, Model pInstances) {
    this.execution++;
    pOntology.write(System.out, "N-TRIPLES");
    System.out.println("========================================");
    System.out.println("Number of elements: "+ pInstances.size());
    System.out.println("Execution number :"+this.execution);
    System.out.println("Infered count list "+pInf.getDeductionsModel().size());
}
 
Example 30
Project: OntologyBasedInormationExtractor   File: LinguisticEnhancer.java   Source Code and License 5 votes vote down vote up
public List<SynSuggestion> suggestLinguisticData(Resource rdfResource) {
    if (rdfResource.canAs(OntClass.class)) {
        OntClass ontCls = rdfResource.as(OntClass.class);
        OntModel om = OntoManager.getInstance().getModel();

        if (ontCls.hasSuperClass(om.getOntClass(NS + "Product"))) { //if rdfResource is a product
            return suggestForProduct(ontCls);
        } else if (ontCls.hasSuperClass(om.getOntClass(NS + "Feature"))) { //if feature
            return suggestForFeature(ontCls);
        } else {
            logger.error("unsupported class type");
        }
    }
    return null;
}
 
Example 31
Project: OntologyBasedInormationExtractor   File: Test.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
    String NS;
    OntoManager om=OntoManager.getInstance();
    om.load();
    NS=om.getOntologyIRI()+"#";

    OntModel model=om.getModel();
    //OntClass tvCls=model.getOntClass(NS+"TV");
   // OntClass featureCls=model.getOntClass(NS+"PowerConsumption");
   // OntoUtil.getFeatures(tvCls) ;
    ProductClass tv = om.getProductClass("TV");
    boolean has=tv.hasFeature("http://cse.mrt.ac.lk/com.sigmacr/ontologies/product_ontolology#PictureQuality");
    System.out.println(has);
}
 
Example 32
Project: OntologyBasedInormationExtractor   File: OntoUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetAnnotationPropertyValueInAxiom() throws Exception {
    OntModel model=om.getModel();
    OntClass tvCls=model.getOntClass(NS+"TV");
    OntClass featureCls=model.getOntClass(NS+"PowerConsumption");
    Literal isNeg=OntoUtil.getAnnotationPropertyValueInAxiom(tvCls,featureCls, PO.AP_IS_NEGATIVE);
    assertTrue( isNeg.getBoolean() );
}
 
Example 33
Project: OntologyBasedInormationExtractor   File: OntoManagerTest.java   Source Code and License 5 votes vote down vote up
@org.junit.Test
public void testGetSuperClassesWithDistance() throws Exception {
    OntModel model=om.getModel();

    OntClass tvCls=model.getOntClass(NS+"Fridge");
    Map<Integer,List<OntClass>> map = om.getSuperClassesWithDistance(tvCls);
    System.out.println(map);
}
 
Example 34
Project: BimSPARQL   File: RDFWriter.java   Source Code and License 5 votes vote down vote up
public RDFWriter(OntModel ontModel, OntModel expressModel, OntModel listModel, InputStream inputStream, String baseURI, Map<String, EntityVO> ent, Map<String, TypeVO> typ, String ontURI) {
    this.ontModel = ontModel;
    this.expressModel = expressModel;
    this.listModel = listModel;
    this.inputStream = inputStream;
    this.baseURI = baseURI;
    this.ent = ent;
    this.typ = typ;
    this.ontNS = ontURI;
}
 
Example 35
Project: BimSPARQL   File: QueryFunctionTest.java   Source Code and License 5 votes vote down vote up
public static void executeQuery(String query){
	System.out.println("Load model...");
	OntModel ontModel=loadDefaultModel();
	System.out.println("Start to query...");
	  long start=System.currentTimeMillis();
	Query q = QueryFactory.create(prefixes+query);
	QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
	ResultSet qresults = qe.execSelect();
	ResultSetFormatter.out(qresults);
	  long end=System.currentTimeMillis();
        System.out.println("Query time: "+((float)(end-start))/1000+ " s");
}
 
Example 36
Project: BimSPARQL   File: FireSeparationDistance.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args)
	throws ClassNotFoundException, IOException, ParserConfigurationException, SAXException, URISyntaxException {
Model model = ModelFactory.createDefaultModel();
InputStream in = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final.ttl");
model.read(in, null, "TTL");
System.out.println(model.size());
Model geometryModel = ModelFactory.createDefaultModel();
InputStream ing = FireSeparationDistance.class.getClassLoader().getResourceAsStream("lifeline_final_geometry.ttl");
geometryModel.read(ing, null, "TTL");
System.out.println(geometryModel.size());
Model schema=loadModel("IFC2X3_TC1.ttl","TTL");
BimSPARQL.init(model, geometryModel);
Model ibcspin = ModelFactory.createDefaultModel();
addMagicProperty(ibcspin, IBC+"hasFireSeparationDistance", prefixes+hasFireSeparationDistance, 1);
addMagicProperty(ibcspin, IBC+"hasProtectedOpeningArea", prefixes+hasProtectedOpeningArea, 1);
addMagicProperty(ibcspin, IBC+"hasUnprotectedOpeningArea", prefixes+hasUnprotectedOpeningArea, 1);
addMagicProperty(ibcspin, IBC+"hasAp", prefixes+hasAp, 1);
addMagicProperty(ibcspin, IBC+"hasAu", prefixes+hasAu, 1);
Model ibc=loadIbcData();
SPINModuleRegistry.get().registerAll(ibc, null);
for (Function f:SPINModuleRegistry.get().getFunctions())
{
	System.out.println(f.getURI());
}
com.hp.hpl.jena.query.Query query = QueryFactory.create(prefixes + mainQuery);

OntModel union = ModelFactory.createOntologyModel();
union.add(schema);
union.add(model);
union.add(geometryModel);
union.add(ibc);
System.out.println(union.size());
QueryExecution qe = QueryExecutionFactory.create(query, union);
com.hp.hpl.jena.query.ResultSet result = qe.execSelect();
      ResultSetFormatter.out(result);

      }
 
Example 37
Project: bygle-ldp   File: JenaEndPointManager.java   Source Code and License 5 votes vote down vote up
@Override
public void executePublishing() throws Exception {
	super.executeImport();
	SDBConnection conn = new SDBConnection(jenaDataSource);
	StoreDesc storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesHash, BygleSystemUtils.getDBType(databaseType));
	Store store = SDBFactory.connectStore(conn, storeDesc);
	if (!StoreUtils.isFormatted(store))
		store.getTableFormatter().create();
	File importDir = new File(importDirectory);
	FileFilter fileFilter = new WildcardFileFilter("*.nt");
	File[] importFiles = importDir.listFiles(fileFilter);
	if (importFiles.length > 0) {
		OntModel ontModel = ModelFactory.createOntologyModel();
		FileFilter ontologyFileFilter = new WildcardFileFilter("*.owl");
		File[] ontologyfiles = importDir.listFiles(ontologyFileFilter);
		for (int x = 0; x < ontologyfiles.length; x++) {
			FileManager.get().readModel(ontModel, ontologyfiles[x].getAbsolutePath());
		}
		System.out.println("##############################STARTING PUBLISHING#############################");
		for (int i = 0; i < importFiles.length; i++) {
			Model modelTpl = ModelFactory.createDefaultModel();
			FileManager.get().readModel(modelTpl, importFiles[i].getAbsolutePath());
			System.out.println("PUBLISHING  FILE " + importFiles[i].getName());
			System.out.println("##############################START SAVING DATA###############################");
			ontModel.add(modelTpl);
		}
		Dataset dataset = SDBFactory.connectDataset(store);
		dataset.getDefaultModel().add(ontModel);
		store.getConnection().close();
		store.close();
		System.out.println("##############################END PUBLISHING##################################");
		FileUtils.cleanDirectory(importDir);
		System.out.println("##############################PUBLISHING SUCCESS##############################");
	} else {
		System.out.println("##############################NO FILES TO PUBLISH##############################");
	}
}
 
Example 38
Project: JenaKBClient   File: KBObjectImpl.java   Source Code and License 5 votes vote down vote up
public static OntModel getContextModel(Context ctx) {
  if (contextModelMap.containsKey(ctx)) {
    return contextModelMap.get(ctx);
  } else {
    OntModel tempModel = ModelFactory.createOntologyModel(
            OntModelSpec.OWL_MEM, ds.getNamedModel(((ContextImpl)ctx).getCore().getURI()));
    contextModelMap.put(ctx, tempModel);
    return tempModel;
  }
}
 
Example 39
Project: fiware-iot-discovery-ngsi9   File: SemanticConverter.java   Source Code and License 5 votes vote down vote up
public void createJenaModel(RegisterContextRequest rcr) {

        OntModel ontModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
        Model entityOnt = FileManager.get().loadModel(ONT_FILE);
        ontModel.addSubModel(entityOnt);
        ontModel.setNsPrefixes(entityOnt.getNsPrefixMap());

//         OntClass regClass = ontModel.getOntClass(ONT_URL + "iotReg");
//         OntClass entClass = ontModel.createOntClass(ONT_URL + "entity");
//        OntClass regClass = (OntClass) ontModel.createOntResource(OntClass.class, null,ONT_URL+"Registration" );
//        OntClass regClass = (OntClass) ontModel.createClass(ONT_URL + "Registration");
//        OntClass entityClass = (OntClass) ontModel.createClass(ONT_URL + "Entity");
        OntClass entityClass = (OntClass) ontModel.getOntClass(ONT_URL + "Entity");

//         System.out.println("Class type is: " + regClass.getLocalName());
//         System.out.println(rcr.getRegistrationId());
        Individual regIndividual = ontModel.createIndividual(ONT_URL + "roomSensor13CII01", entityClass);
        
        System.out.println("has propertry \"expiry\":"+regIndividual.hasProperty(ontModel.getProperty(ONT_URL, "expiry")));
//        Property p = ontModel.createProperty(ONT_URL, "hasRegistrationId");
//        regIndividual.addProperty(p, "");
        regIndividual.setPropertyValue(ontModel.getProperty(ONT_URL, "registrationId"), ontModel.createLiteral(rcr.getRegistrationId()));
//        p = ontModel.createProperty(ONT_URL, "hasDuration");
//        regIndividual.addProperty(p, "");
        regIndividual.setPropertyValue(ontModel.getProperty(ONT_URL, "expiry"), ontModel.createLiteral(rcr.getDuration()));
        System.out.println("has propertry \"expiry\":"+regIndividual.hasProperty(ontModel.getProperty(ONT_URL, "expiry")));

        ExtendedIterator<OntProperty> iter = ontModel.listAllOntProperties();
        while (iter.hasNext()) {
            OntProperty ontProp = iter.next();
            System.out.println(ontProp.getLocalName());
//            if (formParams.containsKey(ontProp.getLocalName())) {
//                regIndividual.addProperty(ontProp, ontModel.getcreateTypedLiteral(formParams.get(ontProp.getLocalName())[0]));
//            }
        }
        ontModel.write(System.out, "TURTLE");
//        ontModel.write(System.out, "RDF/XML");
//          ontModel.write(System.out, "JSON-LD");

    }
 
Example 40
Project: t5-doc   File: CSVSToRDFConverter.java   Source Code and License 5 votes vote down vote up
public void saveModel(OntModel model, String path) throws IOException {

		File file = new File(path);
		file.createNewFile();
		FileOutputStream fos = new FileOutputStream(file, false);
		OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
		model.write(writer, "N-TRIPLES");
	}