Java Code Examples for com.hp.hpl.jena.query.QueryExecution#execSelect()

The following examples show how to use com.hp.hpl.jena.query.QueryExecution#execSelect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TrigKSTripleReader.java    From EventCoreference with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Statement> readTriplesFromKs(String subjectUri, String sparqlQuery){

        ArrayList<Statement> triples = new ArrayList<Statement>();
        HttpAuthenticator authenticator = new SimpleAuthenticator(user, pass.toCharArray());
        try {
            qCount++;
            QueryExecution x = QueryExecutionFactory.sparqlService(serviceEndpoint, sparqlQuery, authenticator);
            ResultSet resultset = x.execSelect();
            while (resultset.hasNext()) {
                QuerySolution solution = resultset.nextSolution();
                String relString = solution.get("predicate").toString();
                RDFNode obj = solution.get("object");
                Model model = ModelFactory.createDefaultModel();
                Resource subj = model.createResource(subjectUri);
                Statement s = createStatement(subj, ResourceFactory.createProperty(relString), obj);
                triples.add(s);
            }
        } catch (Exception e) {
            //e.printStackTrace();
        }
        return triples;
    }
 
Example 2
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
public int getNumberOfConceptualDomains(String contextURI) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT (COUNT (DISTINCT ?cd) as ?count) FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?cdClass rdfs:subClassOf mdr:ConceptualDomain .")
			.append("?cd rdfs:subClassOf ?cdClass .")
			.append("?cd mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> .").append("}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	int size = 0;
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			size = qs.getLiteral("count").getInt();
		}
	} finally {
		qexec.close();
	}

	return size;
}
 
Example 3
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
public int getNumberOfObjectClasses(String contextURI) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT (COUNT (DISTINCT ?objectClass) as ?count) FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?objectClassClass rdfs:subClassOf mdr:ObjectClass .")
			.append("?objectClass rdfs:subClassOf ?objectClassClass .")
			.append("?objectClass mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> .").append("}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	int size = 0;
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			size = qs.getLiteral("count").getInt();
		}
	} finally {
		qexec.close();
	}

	return size;
}
 
Example 4
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 6 votes vote down vote up
public int getNumberOfValueMeanings(String conceptualDomainURI) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT (COUNT(DISTINCT ?vm) as ?count) FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?vm rdfs:subClassOf mdr:ValueMeaning .")
			.append("?vm mdr:containedInValueMeaningSet <")
			.append(conceptualDomainURI).append("> .").append("}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	int size = 0;
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			size = qs.getLiteral("count").getInt();
		}
	} finally {
		qexec.close();
	}
	return size;

}
 
Example 5
Source File: AliadaRDFStoreDAO.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
public String crm2AliadaClass(final String crmClass) {
	final Query query = QueryFactory.create(CRM_TO_ALIADA_CLASS_P1 + crmClass + CRM_TO_ALIADA_CLASS_P2);
	ARQ.getContext().setTrue(ARQ.useSAX);
       
	QueryExecution execution = null;
	try {
		execution = QueryExecutionFactory.sparqlService("http://172.25.5.15:8890/sparql", query);
		execution.setTimeout(2000, 5000);
		final ResultSet results = execution.execSelect();
		//Iterating over the SPARQL Query results
		while (results.hasNext()) {
			QuerySolution soln = results.nextSolution();
			//Printing DBpedia entries' abstract.
			System.out.println(soln.get("?abstract"));   
			return soln.get("?abstract").asResource().getURI();
		}
		return "NULL";
       } finally {
       	try {
       		execution.close();
		} catch (Exception exception) {
			// TODO: handle exception
		}
       }

}
 
Example 6
Source File: Entity.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private Object getSameResource(Model model, String typePrefix,
        Element item, Document dataDoc) throws XPathExpressionException {
    QueryExecution qExec = null;
    try {
        String query = getEqualsQuery(model, typePrefix, item, dataDoc);
        LogUtils.debug(this.getClass(), query);
        qExec = QueryExecutionFactory.create(query, model);
        ResultSet rs = qExec.execSelect();
        while (rs.hasNext()) {
            QuerySolution solution = rs.next();
            return solution.get("?x0");
        }
    } catch (Exception e) {
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        if (qExec != null) {
            qExec.close();
        }
    }
    return null;
}
 
Example 7
Source File: Course_Test.java    From neo4jena with Apache License 2.0 6 votes vote down vote up
public static void getJob(GraphDatabaseService njgraph)
{
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	ST descJob = TemplateLoader.getQueriesGroup().getInstanceOf("getGraph");
	String queryASString = Constants.QUERY_PREFIX+ descJob.render();
	
	Query query = QueryFactory.create(queryASString, Syntax.syntaxSPARQL_11);
	QueryExecution qexec = QueryExecutionFactory.create(query, njmodel);
	ResultSet res = qexec.execSelect();
	
	int count=0;
       while(res.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = res.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      //log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 8
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
public Resource getAdministeredItem(String id) {
	StringBuilder queryString = new StringBuilder()
			.append(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT ?ai FROM <")
			.append(MDRDatabase.BASE_URI)
			.append("> WHERE { ")
			.append("?prop rdfs:subPropertyOf mdr:administeredItemAdministrationRecord. ")
			.append("?ai ?prop ?administrationRecord. ")
			.append("?administrationRecord mdr:administeredItemIdentifier ?ii.")
			.append("?ii mdr:dataIdentifier ?di. FILTER regex (?di, \"")
			.append(id).append("\") .}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	Resource ai = null;
	try {
		ResultSet rs = qexec.execSelect();
		if (rs.hasNext()) {
			QuerySolution qs = rs.next();
			ai = qs.getResource("ai");
		}
		if (rs.hasNext()) {
			throw new IllegalStateException(
					"Something is wrong. There is more than one AdministeredItems with the same ID.");
		}
	} finally {
		qexec.close();
	}
	return ai;
}
 
Example 9
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
public List<? super ValueDomainResource> getValueDomainsOfConceptualDomain(
		String cdURI) {
	List<ValueDomainResource> vdList = new ArrayList<ValueDomainResource>();
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS).append("SELECT ?vd FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?vdClass rdfs:subClassOf mdr:ValueDomain .")
			.append("?vd rdfs:subClassOf ?vdClass . ")
			.append("?vd mdr:representingConceptualDomainRepresentation <")
			.append(cdURI).append("> .").append("}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			// here conceptualDomain is checked whether its enumerated or
			// not, proper instantiation is done
			OntClass res = mdrDatabase.getOntModel().getOntClass(
					qs.getResource("vd").getURI());
			if (res.hasSuperClass(mdrDatabase.getVocabulary().EnumeratedValueDomain)) {
				vdList.add(new EnumeratedValueDomainImpl(res, mdrDatabase));
			} else {
				vdList.add(new NonEnumeratedValueDomainImpl(res,
						mdrDatabase));
			}

		}
	} finally {
		qexec.close();
	}

	return vdList;
}
 
Example 10
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
public List<? super DataElementResource> getDataElementsOfContext(
		String contextURI, Integer limit, Integer offset) {
	List<DataElementResource> dataElementResourceList = new ArrayList<DataElementResource>();

	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS).append("SELECT ?de FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?de rdfs:subClassOf mdr:DataElement .")
			.append("?de mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> .").append("}");
	if (limit != null && offset != null) {
		queryString.append(" ORDER BY ?de ").append(" LIMIT ")
				.append(limit).append(" OFFSET ").append(offset);
	}
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());

	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			DataElementResource ctx = new DataElementImpl(
					qs.getResource("de"), this.mdrDatabase);
			dataElementResourceList.add(ctx);
		}
	} finally {
		qexec.close();
	}
	return dataElementResourceList;

}
 
Example 11
Source File: Course.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
               	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
               	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
               "SELECT ?X ?Z ?Y "+
               "WHERE" +
               "{ ?X ?Z ?Y ." +
               "}"; 
      	          
       Query query = QueryFactory.create(s2); 
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       log.info("Query took (ms): "+ watch.stop());
       System.out.println("Query took (ms): "+ watch.stop());
      // ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 12
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 5 votes vote down vote up
private static void extractEventSource(EventDeclaration ed, Dataset dataset) {
	ed.setServiceId(ed.getnodeId());
	String queryStr = queryPrefix + " select  ?z where {<" + ed.getnodeId()
			+ "> owls:supports ?y. ?y ces:httpService ?z.}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	if (results.hasNext()) {
		RDFNode addr = results.next().get("z");
		ed.setSrc(addr.toString());
		// System.out.println("addr: " + addr);
	}
}
 
Example 13
Source File: Course_Test.java    From neo4jena with Apache License 2.0 5 votes vote down vote up
public static void search(GraphDatabaseService njgraph) {
	NeoGraph graph = new NeoGraph(njgraph);
	Model njmodel = ModelFactory.createModelForGraph(graph);
	
	String s2 = "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n" +
               	"PREFIX uni: <http://seecs.edu.pk/db885#>" +
               	"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
               "SELECT ?X ?Z ?Y "+
               "WHERE" +
               "{ ?X ?Z ?Y ." +
               "}"; 
      	          
       Query query = QueryFactory.create(s2); 
       QueryExecution qExe = QueryExecutionFactory.create(query, njmodel);
       StopWatch watch = new StopWatch();
       ResultSet results = qExe.execSelect();
       long endTime = watch.stop();
       log.info("Query took (ms): "+endTime);
       System.out.println("Query took (ms): "+ endTime);
      // ResultSetFormatter.out(System.out, results);
       
       int count=0;
       while(results.hasNext()){
       	//System.out.println("in while"+count);
       	QuerySolution sol = results.next();
       	System.out.println(sol.get("?Z"));
       	count++;
       }
      
      log.info("Record fetched:"+ count);
      System.out.println("Record fetched:"+ count);
}
 
Example 14
Source File: ResourceQueryFactory.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
public ResultSet getDerivationRulesOfContext(String contextURI) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS).append("SELECT ?dr FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?dr rdfs:subClassOf mdr:DerivationRule .")
			.append("?dr mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> . }");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	return qexec.execSelect();

}
 
Example 15
Source File: VirtuosoQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<? super ConceptualDomainResource> searchConceptualDomain(
		String keyword, String contextURI, TextSearchType searchType) {
	List<ConceptualDomainResource> cdList = new ArrayList<ConceptualDomainResource>();
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT ?cd FROM <")
			.append(MDRDatabase.BASE_URI)
			.append("> WHERE {")
			.append("?cdClass rdfs:subClassOf mdr:ConceptualDomain .")
			.append("?cd rdfs:subClassOf ?cdClass .")
			.append("?cd mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextTerminologicalEntry ?te .")
			.append("?te mdr:containingTerminologicalEntryLanguage ?ls .")
			.append("?ls mdr:containingNameEntry ?designation .")
			.append("?designation mdr:name ?name .");
	if (!Util.isNull(contextURI)) {
		queryString.append("?aic mdr:administeredItemContextContext <")
				.append(contextURI).append("> .");
	}
	if (keyword.matches("\\s*")) {
		return cdList;
	}
	if (searchType == null || searchType.equals(TextSearchType.Exact)) {
		queryString.append(exactMatchKeyword(keyword));
	}

	else if (searchType.equals(TextSearchType.WildCard)) {
		queryString.append(atLeastOneKeyword(keyword));
	}

	else {
		queryString.append(allWordsKeyword(keyword));
	}
	queryString.append(" .}");

	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			// here conceptualDomain is checked whether its enumerated or
			// not, proper instantiation is done
			Resource tempRes = this.mdrDatabase.getOntModel().getResource(
					qs.getResource("cd").getURI());
			OntClass res = tempRes.as(OntClass.class);
			if (res.hasSuperClass(mdrDatabase.getVocabulary().EnumeratedConceptualDomain)) {
				cdList.add(new EnumeratedConceptualDomainImpl(res,
						mdrDatabase));
			} else {
				cdList.add(new NonEnumeratedConceptualDomainImpl(res,
						mdrDatabase));
			}

		}
	} finally {
		qexec.close();
	}
	return cdList;
}
 
Example 16
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 4 votes vote down vote up
private static void extractTrafficLocation(EventDeclaration ed, Dataset dataset) {
	// String queryStr = queryPrefix
	// + " select ?rid ?fnn ?fnsn ?fnst ?fnc ?fnlat ?fnlon ?snn ?snsn ?snst ?snc ?snlat ?snlon where {<"
	// + ed.getID()
	// + "> owls:presents ?profile. <"
	// + ed.getID()
	// +
	// "> ssn:observes ?y. ?profile ct:hasReportID ?rid. ?y ssn:isPropertyOf ?z. ?z ct:hasFirstNode ?fn. ?z ct:hasSecondNode ?sn. "
	// +
	// " ?fn ct:hasNodeName ?fnn. ?fn ct:hasStreetNumber ?fnsn. ?fn ct:hasStreet ?fnst. ?fn ct:hasCity ?fnc. ?fn ct:hasLatitude ?fnlat. ?fn ct:hasLongtitude ?fnlon."
	// +
	// " ?sn ct:hasNodeName ?snn. ?sn ct:hasStreetNumber ?snsn. ?sn ct:hasStreet ?snst. ?sn ct:hasCity ?snc. ?sn ct:hasLatitude ?snlat. ?sn ct:hasLongtitude ?snlon.}";
	String queryStr = queryPrefix + " select ?z where { <" + ed.getnodeId()
			+ "> ssn:observes ?y.   ?y ssn:isPropertyOf ?z.}  ";
	// +
	// " ?fn ct:hasNodeName ?fnn. ?fn ct:hasStreetNumber ?fnsn. ?fn ct:hasStreet ?fnst. ?fn ct:hasCity ?fnc. ?fn ct:hasLatitude ?fnlat. ?fn ct:hasLongtitude ?fnlon."
	// +
	// " ?sn ct:hasNodeName ?snn. ?sn ct:hasStreetNumber ?snsn. ?sn ct:hasStreet ?snst. ?sn ct:hasCity ?snc. ?sn ct:hasLatitude ?snlat. ?sn ct:hasLongtitude ?snlon.}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	if (results.hasNext()) {
		QuerySolution row = results.next();
		String foiStr = row.get("z").toString();
		// String reportId = row.get("rid").asLiteral().getString();
		// String firstNodeName = row.get("fnn").asLiteral().getString();
		// String firstNodeStreetNo = row.get("fnsn").asLiteral().getString();
		// String firstNodeStreet = row.get("fnst").asLiteral().getString();
		// String firstNodeCity = row.get("fnc").asLiteral().getString();
		// Double firstNodeLat = row.get("fnlat").asLiteral().getDouble();
		// Double firstNodeLon = row.get("fnlon").asLiteral().getDouble();
		//
		// String secondNodeName = row.get("snn").asLiteral().getString();
		// String secondNodeStreetNo = row.get("snsn").asLiteral().getString();
		// String secondNodeStreet = row.get("snst").asLiteral().getString();
		// String secondNodeCity = row.get("snc").asLiteral().getString();
		// Double secondNodeLat = row.get("snlat").asLiteral().getDouble();
		// Double secondNodeLon = row.get("snlon").asLiteral().getDouble();
		// ((TrafficReportService) ed).setReportId(reportId);
		// ((TrafficReportService) ed).setNode1City(firstNodeCity);
		// ((TrafficReportService) ed).setNode1Lat(firstNodeLat);
		// ((TrafficReportService) ed).setNode1Lon(firstNodeLon);
		// ((TrafficReportService) ed).setNode1Street(firstNodeStreet);
		// ((TrafficReportService) ed).setNode1StreetNo(firstNodeStreetNo);
		// ((TrafficReportService) ed).setNode1Name(firstNodeName);
		// ((TrafficReportService) ed).setNode2City(secondNodeCity);
		// ((TrafficReportService) ed).setNode2Lat(secondNodeLat);
		// ((TrafficReportService) ed).setNode2Lon(secondNodeLon);
		// ((TrafficReportService) ed).setNode2Name(secondNodeName);
		// ((TrafficReportService) ed).setNode2Street(secondNodeStreet);
		// ((TrafficReportService) ed).setNode2StreetNo(secondNodeStreetNo);
		ed.setFoi(foiStr);
	}
}
 
Example 17
Source File: TDBQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<? super ConceptualDomainResource> searchConceptualDomain(
		String keyword, String contextURI, TextSearchType searchType) {
	List<ConceptualDomainResource> cdList = new ArrayList<ConceptualDomainResource>();
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_PF)
			.append(PREFIX_RDFS)
			.append("SELECT ?cd FROM <")
			.append(MDRDatabase.BASE_URI)
			.append("> WHERE {")
			.append("?cdClass rdfs:subClassOf mdr:ConceptualDomain .")
			.append("?cd rdfs:subClassOf ?cdClass .")
			.append("?cd mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextTerminologicalEntry ?te .")
			.append("?te mdr:containingTerminologicalEntryLanguage ?ls .")
			.append("?ls mdr:containingNameEntry ?designation .")
			.append("?designation mdr:name ?name .");
	if (!Util.isNull(contextURI)) {
		queryString.append("?aic mdr:administeredItemContextContext <")
				.append(contextURI).append("> .");
	}
	if (keyword.matches("\\s*")) {
		return cdList;
	}
	if (searchType == null || searchType.equals(TextSearchType.Exact)) {
		queryString.append(exactMatchKeyword(keyword));
	}

	else if (searchType.equals(TextSearchType.WildCard)) {
		queryString.append(atLeastOneKeyword(keyword));
	}

	else {
		queryString.append(allWordsKeyword(keyword));
	}
	queryString.append(" .}");

	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			// here conceptualDomain is checked whether its enumerated or
			// not, proper instantiation is done
			OntClass res = qs.getResource("cd").as(OntClass.class);
			if (res.hasSuperClass(mdrDatabase.getVocabulary().EnumeratedConceptualDomain)) {
				cdList.add(new EnumeratedConceptualDomainImpl(res,
						mdrDatabase));
			} else {
				cdList.add(new NonEnumeratedConceptualDomainImpl(res,
						mdrDatabase));
			}

		}
	} finally {
		qexec.close();
	}
	return cdList;
}
 
Example 18
Source File: Relation.java    From xcurator with Apache License 2.0 4 votes vote down vote up
private void findAndAddLinkedResouces(Model model,
        Element item, Document dataDoc, Resource parentResouce, String typePrefix) throws XPathExpressionException {

//TODO: Fix it!
    //    createSPARQL();
    // name="x.y.z.y"
    // x
    // ?x y ?y .
    // ?y z ?z .
    // ?z y ?y .
    String whereClause = "WHERE {\n";
    int j = 0;
    whereClause += "?x0 rdf:type <" + getTargetEntity() + "> . \n";

    for (Property lookupProperty : foreignLookupKey.getProperties()) {
        String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc).trim();

        if (localValue.length() == 0) {
            continue;
        }
        //      localValue = localValue.replaceAll("\\s+", "\\\\\\\\s+");
        localValue = JenaUtils.querify(localValue);

        String[] splittedRelation = lookupProperty.getElement().getAttribute("name")
                .replace(typePrefix, "")
                .split("\\.");

        int i;
        for (i = 1; i < splittedRelation.length; i++) {
            whereClause += "?x" + (i - 1) + "" + (i != 1 ? j : "") + " t:" + splittedRelation[i] + " ?x" + (i) + "" + j + ".\n";
        }

        whereClause += "FILTER (?x" + (i - 1) + (i != 1 ? j : "") + " = \"" + localValue + "\").\n";

        j++;
    }

    whereClause += "} ";

    String queryStr
            = "PREFIX t: <" + typePrefix + ">\n"
            + "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "select ?x0 \n" + whereClause;

    LogUtils.debug(this.getClass(), queryStr);

    Query query = QueryFactory.create(queryStr);
    QueryExecution qExec = null;
    try {
        qExec = QueryExecutionFactory.create(query, model);
        ResultSet rs = qExec.execSelect();
        while (rs.hasNext()) {
            QuerySolution solution = rs.next();
            RDFNode subject = solution.get("?x0");
            parentResouce.addProperty(getJenaProperty(model), subject);

        }
    } catch (Exception e) {
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        if (qExec != null) {
            qExec.close();
        }
    }

    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
    //
    //
    //    for (Property lookupProperty: foreignLookupKey.getProperties()) {
    //      String localValue = XMLUtils.getStringByPath(lookupProperty.getPath(), item, dataDoc);
    //      Selector selector = new SimpleSelector(null, lookupProperty.getJenaProperty(model), localValue);
    //      StmtIterator iter = model.listStatements(selector);
    //
    //      while (iter.hasNext()) {
    //        Statement stmt = iter.next();
    //        if (targetEntity.equals(stmt.getSubject().getProperty(RDF.type).getObject().toString())) {
    //          parentResouce.addProperty(getJenaProperty(model), stmt.getSubject());
    //        }
    //      }
    //    }
}
 
Example 19
Source File: VirtuosoQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int getNumberOfDataElementSearch(String keyword, String contextURI,
		TextSearchType searchType) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT (COUNT (DISTINCT ?de) as ?count) FROM <")
			.append(MDRDatabase.BASE_URI)
			.append("> WHERE {")
			.append("?de rdfs:subClassOf mdr:DataElement .")
			.append("?de mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextTerminologicalEntry ?te .")
			.append("?te mdr:containingTerminologicalEntryLanguage ?ls .")
			.append("?ls mdr:containingNameEntry ?designation .")
			.append("?designation mdr:name ?name .");
	if (!Util.isNull(contextURI)) {
		queryString.append("?aic mdr:administeredItemContextContext <")
				.append(contextURI).append("> .");
	}
	// checks if keyword is empty
	if (keyword.matches("\\s*")) {
		return 0;
	}
	if (searchType == null || searchType.equals(TextSearchType.Exact)) {
		queryString.append(exactMatchKeyword(keyword));
	}

	else if (searchType.equals(TextSearchType.WildCard)) {
		queryString.append(atLeastOneKeyword(keyword));
	}

	else {
		queryString.append(allWordsKeyword(keyword));
	}
	queryString.append(" .}");

	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	int size = 0;
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			size = qs.getLiteral("count").getInt();
		}
	} finally {
		qexec.close();
	}
	return size;
}
 
Example 20
Source File: OwlReader.java    From EventCoreference with Apache License 2.0 4 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();
    }