Java Code Examples for com.hp.hpl.jena.query.QueryExecution

The following examples show how to use com.hp.hpl.jena.query.QueryExecution. These examples are extracted from open source projects. 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 Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Map<String, EventDeclaration> extractEDsFromDataset(Dataset dataset) {
	// List<EventDeclaration> eds = new ArrayList<EventDeclaration>();
	String describeStr = queryPrefix
			+ " select ?x"
			+ " where{?x rdf:type ?y graph <http://www.insight-centre.org/ces#> { ?y rdfs:subClassOf ces:EventService}}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	while (results.hasNext()) {
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		extractEDByServiceID(edID, dataset, edMap);
	}
	// RDFDataMgr.write(System.out, results, Lang.TURTLE);
	return edMap;
}
 
Example 2
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static String extractFoIById(Dataset dataset, String foiId) {
	String queryStr = queryPrefix + " select  ?a ?b ?c ?d where { <" + foiId + "> ct:hasStartLatitude ?a. <"
			+ foiId + "> ct:hasStartLongitude ?b. <" + foiId + "> ct:hasEndLatitude ?c. <" + foiId
			+ "> ct:hasEndLongitude ?d.}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	if (results.hasNext()) {
		// RDFNode foi = results.next().get("y");
		QuerySolution qs = results.next();
		Double startLat = qs.getLiteral("a").getDouble();
		Double startLon = qs.getLiteral("b").getDouble();
		Double endLat = qs.getLiteral("c").getDouble();
		Double endLon = qs.getLiteral("d").getDouble();
		return startLat + "," + startLon + "-" + endLat + "," + endLon;
		// ed.setFoi(startLat + "," + startLon + "-" + endLat + "," + endLon);
		// }
	}
	return null;

}
 
Example 3
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 Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void extractEventPattern(EventDeclaration ed, Dataset dataset, Map<String, EventDeclaration> edMap)
		throws CloneNotSupportedException {
	String desribeStr = queryPrefix + " describe  ?z where {<" + ed.getnodeId()
			+ "> owls:presents ?y. ?y ces:hasPattern ?z.}";
	QueryExecution qe1 = QueryExecutionFactory.create(desribeStr, dataset);
	Model patternModel = qe1.execDescribe();
	// RDFDataMgr.write(System.out, patternModel, Lang.TURTLE);
	EventPattern ep = new EventPattern();
	ep.setID("EP-" + ed.getnodeId());

	// ep.setFilters(new HashMap<String, List<Filter>>());
	String queryRoot = queryPrefix + " select  ?z where {<" + ed.getnodeId()
			+ "> owls:presents ?y. ?y ces:hasPattern ?z.}";
	QueryExecution qe2 = QueryExecutionFactory.create(queryRoot, dataset);
	ResultSet results = qe2.execSelect();
	if (results.hasNext()) {
		ed.setEp(ep);
		RDFNode root = results.next().get("z");
		traverseToExtract(0, root, patternModel, ep, dataset, edMap);
		extractSelectionMap(root, patternModel, ep, dataset, edMap);
		// System.out.println("EP extracted: " + ep.toString());
	}
	// traverse
	// RDFDataMgr.write(System.out, results, Lang.TURTLE);

}
 
Example 5
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static String extractEventPayloads(EventDeclaration ed, Dataset dataset) {
	String queryStr = queryPrefix + " select ?x ?y ?z where {<" + ed.getnodeId()
			+ "> ssn:observes ?x. ?x rdf:type ?y. ?x ssn:isPropertyOf ?z }";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	List<String> payloads = new ArrayList<String>();
	String foiId = "";
	while (results.hasNext()) {
		QuerySolution result = results.next();
		RDFNode propertyName = result.get("x");
		RDFNode propertyType = result.get("y");
		RDFNode foi = result.get("z");
		if (propertyType.toString().equals("http://www.w3.org/2000/01/rdf-schema#Resource"))
			continue;
		// System.out.println("type: " + property + " foi: " + foi);
		payloads.add(propertyType.toString() + "|" + foi.toString() + "|" + propertyName.toString());
		foiId = foi.toString();
		// System.out.println("payload: " + propertyType.toString() + "|" + foi.toString() + "|"
		// + propertyName.toString());
	}
	ed.setPayloads(payloads);
	return foiId;
}
 
Example 6
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(true);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 7
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractCompositionPlanFromDataset(String serviceRequest) {
	Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, queryBase));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:CompositionPlan}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();
	ep.setQuery(false);
	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 8
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static EventPattern extractQueryFromModel(Model serviceRequest) {
	// Model queryBase = FileManager.get().loadModel(datasetDirectory + serviceRequest);
	dataset.getDefaultModel().add(ModelFactory.createOntologyModel(ontoSpec, serviceRequest));

	String describeStr = queryPrefix + " select ?x  where{?x rdf:type ces:EventRequest}";
	// Query query = QueryFactory.create(describeStr);
	// query.setPrefixMapping(pmap);
	QueryExecution qe = QueryExecutionFactory.create(describeStr, dataset);
	ResultSet results = qe.execSelect();
	// ResultSetFormatter.out(System.out, results, query);
	Map<String, EventDeclaration> edMap = new HashMap<String, EventDeclaration>();
	EventPattern ep = new EventPattern();

	while (results.hasNext()) {
		// System.out.println("results!");
		QuerySolution row = results.next();
		RDFNode edID = row.get("x");
		// System.out.println("has id: " + edID.toString());
		ep = extractEDByServiceID(edID, dataset, edMap).getEp();
	}
	return ep;
}
 
Example 9
Source Project: semweb4j   Source File: ModelImplJena.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * @return opened result Model
 */
@Override
public ClosableIterable<Statement> sparqlDescribe(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException("Cannot handle this type of queries! Please use DESCRIBE.");
	}
	
}
 
Example 10
Source Project: semweb4j   Source File: ModelSetImplJena.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String query,
		String querylanguage) throws QueryLanguageNotSupportedException,
		MalformedQueryException, ModelRuntimeException {

	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isConstructType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execConstruct();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use CONSTRUCT.");
	}
}
 
Example 11
Source Project: semweb4j   Source File: ModelSetImplJena.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String query)
		throws ModelRuntimeException, MalformedQueryException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isConstructType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execConstruct();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use CONSTRUCT.");
	}

}
 
Example 12
Source Project: semweb4j   Source File: ModelSetImplJena.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String query)
		throws ModelRuntimeException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isDescribeType()) {
		com.hp.hpl.jena.rdf.model.Model m = qexec.execDescribe();
		Model resultModel = new ModelImplJena(null, m, Reasoning.none);
		resultModel.open();
		return resultModel;
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use DESCRIBE.");
	}
}
 
Example 13
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 14
Source Project: aliada-tool   Source File: RDFStoreDAO.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, 
 * to get the number of resources specified in the query argument.
 *
 * @param query					the query to execute to get the number of resources.  
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @return the number of resources.
 * @since 2.0
 */
public int getNumResources(final String query, final String sparqlEndpointURI, final String user, final String password) {
	int numRes = 0;
	try {
        // Execute the query and obtain results
        final QueryExecution qexec = QueryExecutionFactory.sparqlService(
        		sparqlEndpointURI, 
        		QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
        qexec.setTimeout(2000, 5000);
           final ResultSet results = qexec.execSelect() ;
           while (results.hasNext())
           {
           	final QuerySolution soln = results.nextSolution() ;
           	numRes = soln.getLiteral("count").getInt();
           }
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
	return numRes;
}
 
Example 15
Source Project: aliada-tool   Source File: RDFStoreDAO.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param query					the query to use to look for the resources.
 * @return the {@link com.hp.hpl.jena.query.ResultSet} of the SELECT SPARQL query.
 * @since 2.0
 */
public ResultSet executeSelect(final String sparqlEndpointURI, final String user, final String password, final String query) {
	ResultSet results = null;
 	try {
        // Execute the query and obtain results
        final QueryExecution qexec = QueryExecutionFactory.sparqlService(
        		sparqlEndpointURI, 
        		QueryFactory.create(query), 
				auth(sparqlEndpointURI, user, password));
        qexec.setTimeout(2000, 5000);
           results = qexec.execSelect() ;
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
 	return results;
}
 
Example 16
Source Project: EventCoreference   Source File: TrigKSTripleReader.java    License: Apache License 2.0 6 votes vote down vote up
public static ArrayList<String> readEventIdsFromKs(String sparqlQuery)throws Exception {
    ArrayList<String> eventIds = new ArrayList<String>();
    //System.out.println("serviceEndpoint = " + serviceEndpoint);
    //System.out.println("sparqlQuery = " + sparqlQuery);
    //System.out.println("user = " + user);
    //System.out.println("pass = " + pass);
    HttpAuthenticator authenticator = new SimpleAuthenticator(user, pass.toCharArray());

    QueryExecution x = QueryExecutionFactory.sparqlService(serviceEndpoint, sparqlQuery, authenticator);
    ResultSet resultset = x.execSelect();
    while (resultset.hasNext()) {
        QuerySolution solution = resultset.nextSolution();
        //System.out.println("solution.toString() = " + solution.toString());
        //( ?event = <http://www.newsreader-project.eu/data/Dasym-Pilot/425819_relink_dominant.naf#ev24> )
        String currentEvent = solution.get("event").toString();
        //System.out.println("currentEvent = " + currentEvent);
        //http://www.newsreader-project.eu/data/Dasym-Pilot/425819_relink_dominant.naf#ev24
        if (!eventIds.contains(currentEvent)) {
            eventIds.add(currentEvent);
        }
    }
    return eventIds;
}
 
Example 17
public int getNumberOfDEC(String objectClassURI) {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS)
			.append("SELECT (COUNT (DISTINCT ?dec) as ?count) FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?dec rdfs:subClassOf mdr:DataElementConcept .")
			.append("?dec mdr:dataElementConceptObjectClass <")
			.append(objectClassURI).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 18
Source Project: xcurator   Source File: Entity.java    License: 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 19
/**
 * @return all of the {@link Datatype}s
 */
public List<? super DatatypeResource> getDatatypes() {
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS).append(PREFIX_XSD)
			.append("SELECT ?datatype FROM <").append(MDRDatabase.BASE_URI)
			.append("> WHERE {")
			.append("?datatype rdfs:subClassOf mdr:Datatype }");

	List<DatatypeResource> datatypeList = new ArrayList<DatatypeResource>();
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			Resource res = qs.getResource("datatype");
			datatypeList.add(new DatatypeImpl(res, mdrDatabase));
		}
	} finally {
		qexec.close();
	}
	return datatypeList;
}
 
Example 20
Source Project: LodView   Source File: SPARQLEndPoint.java    License: MIT License 6 votes vote down vote up
public String testEndpoint(ConfigurationBean conf) {
	System.out.println("testing connection on " + conf.getEndPointUrl());
	QueryExecution qe = QueryExecutionFactory.sparqlService(conf.getEndPointUrl(), "select ?s {?s ?p ?o} LIMIT 1");
	String msg = "";
	try {
		ResultSet rs = qe.execSelect();
		if (rs.hasNext()) {
			System.out.println("is online");
			msg = "online";
		} else {
			System.out.println("is offline");
			msg = "offline";
		}
	} catch (Exception e) {
		System.out.println("is offline " + e.getMessage());
		msg = "offline " + e.getMessage();
	} finally {
		qe.close();
	}
	return msg;
}
 
Example 21
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 22
public List<? super ContextResource> getContextsOfContext(String contextURI) {
	List<ContextResource> contextResourceList = new ArrayList<ContextResource>();

	StringBuilder queryString = new StringBuilder().append(PREFIX_MDR)
			.append(PREFIX_RDFS).append("SELECT ?ctx FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?ctx rdfs:subClassOf mdr:Context .")
			.append("?ctx mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> .").append("FILTER (?ctx != <")
			.append(contextURI).append("> )  }");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			ContextResource ctx = new ContextImpl(qs.getResource("ctx"),
					this.mdrDatabase);
			contextResourceList.add(ctx);
		}
	} finally {
		qexec.close();
	}
	return contextResourceList;
}
 
Example 23
public List<? super PropertyResource> getPropertiesOfContext(
		String contextURI) {
	List<PropertyResource> propertyList = new ArrayList<PropertyResource>();
	StringBuilder queryString = new StringBuilder(PREFIX_MDR)
			.append(PREFIX_RDFS).append("SELECT ?property FROM <")
			.append(MDRDatabase.BASE_URI).append("> WHERE {")
			.append("?property rdfs:subClassOf mdr:Property .")
			.append("?property mdr:having ?aic .")
			.append("?aic mdr:administeredItemContextContext <")
			.append(contextURI).append("> .").append("}");
	QueryExecution qexec = this.createQueryExecution(
			queryString.toString(), this.mdrDatabase.getOntModel());
	try {
		ResultSet rs = qexec.execSelect();
		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			PropertyResource prop = new PropertyImpl(
					qs.getResource("property"), mdrDatabase);
			propertyList.add(prop);
		}
	} finally {
		qexec.close();
	}
	return propertyList;
}
 
Example 24
Source Project: EventCoreference   Source File: TrigKSTripleReader.java    License: 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 25
Source Project: micro-integrator   Source File: SparqlEndpointQuery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
   public Object processPreQuery(InternalParamCollection params, int queryLevel) throws DataServiceFault {
	try {
	    ResultSet results = null;
   		    QueryExecution qe = this.getQueryExecution();
   		    /* execute query as a select query */
   		    results = qe.execSelect();
   		    return results;
	} catch (Exception e) {
		throw new DataServiceFault(e, "Error in 'SparqlQueryBase.processQuery'");
	}
}
 
Example 26
Source Project: Benchmark   Source File: RDFFileManager.java    License: 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 27
Source Project: Benchmark   Source File: RDFFileManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
private static String extractEventType(String edID, Dataset dataset) {
	String queryStr = queryPrefix + " select  ?name where {<" + edID
			+ "> owls:presents ?profile. ?profile owlssc:serviceCategory ?z. ?z owlssc:serviceCategoryName ?name}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	String type = "";
	if (results.hasNext()) {
		Literal l = results.next().getLiteral("name");
		type = l.getString();
	}
	return type;
}
 
Example 28
public QueryResultTableImpl(QueryExecution qe) {
	if(!qe.getQuery().isSelectType()) {
		throw new ModelRuntimeException("The given query execution is not a SELECT query");
	}
	
	this.varnames = new ArrayList<String>();
	for(Object o : qe.getQuery().getResultVars()) {
		this.varnames.add((String)o);
	}
	this.qexec = qe;
}
 
Example 29
Source Project: semweb4j   Source File: ModelImplJena.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean sparqlAsk(String queryString) throws ModelRuntimeException {
	assertModel();
	log.debug("Query " + queryString);
	Query query = QueryFactory.create(queryString);
	
	if(!query.isAskType()) {
		throw new ModelRuntimeException("The given query is not an ASK query");
	}
	// else
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	return qexec.execAsk();
}
 
Example 30
Source Project: semweb4j   Source File: ModelSetImplJena.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public boolean sparqlAsk(String query) throws ModelRuntimeException,
		MalformedQueryException {
	Query jenaQuery = QueryFactory.create(query);
	QueryExecution qexec = QueryExecutionFactory.create(jenaQuery,
			this.dataset);

	if (jenaQuery.isAskType()) {
		return qexec.execAsk();
	} else {
		throw new RuntimeException(
				"Cannot handle this type of query! Please use ASK.");
	}
}