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

The following examples show how to use com.hp.hpl.jena.query.ResultSet. 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: micro-integrator   Source File: SparqlQueryBase.java    License: Apache License 2.0 6 votes vote down vote up
public DataEntry getDataEntryFromRS(ResultSet rs) {
	DataEntry dataEntry = new DataEntry();
	QuerySolution soln = rs.nextSolution();
	String colName, value;
	boolean useColumnNumbers = this.isUsingColumnNumbers();
	/* for each column get the colName and colValue and add to the data entry */
	for (int i = 0; i < rs.getResultVars().size(); i++) {
		colName = rs.getResultVars().get(i);
		RDFNode node = soln.get(colName) ;  			
		if (node.isLiteral()) {
			value = convertRSToString(soln, colName);
		} else {
			value = soln.getResource(colName).getURI();
		}			
		dataEntry.addValue(useColumnNumbers ? Integer.toString(i + 1) : 
			colName, new ParamValue(value));
	}
	return dataEntry;
}
 
Example 2
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 3
Source Project: GeoTriples   Source File: SPARQLExample.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	ModelD2RQ m = new ModelD2RQ("file:doc/example/mapping-iswc.ttl");
	String sparql = 
		"PREFIX dc: <http://purl.org/dc/elements/1.1/>" +
		"PREFIX foaf: <http://xmlns.com/foaf/0.1/>" +
		"SELECT ?paperTitle ?authorName WHERE {" +
		"    ?paper dc:title ?paperTitle . " +
		"    ?paper dc:creator ?author ." +
		"    ?author foaf:name ?authorName ." +
		"}";
	Query q = QueryFactory.create(sparql); 
	ResultSet rs = QueryExecutionFactory.create(q, m).execSelect();
	while (rs.hasNext()) {
		QuerySolution row = rs.nextSolution();
		System.out.println("Title: " + row.getLiteral("paperTitle").getString());
		System.out.println("Author: " + row.getLiteral("authorName").getString());
	}
	m.close();
}
 
Example 4
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 5
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 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
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, to get 
 * the URIs of the resources to use to discover links towards external datasets.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param graphName 			the graphName, null in case of default graph.
 * @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.
 * @param offset				causes the solutions generated to start after the 
 *                              specified number of solutions.
 * @param limit					upper bound on the number of solutions returned.
 * @return a list of the matched URIs.
 * @since 2.0
 */
public ResourceToLink[] getResourcesToLink(final String sparqlEndpointURI, final String user, final String password, final String sparql, final Integer offset, final Integer limit) {
  	final ArrayList<ResourceToLink> resourcesList = new ArrayList<ResourceToLink>();
  	final String query = sparql + " OFFSET " + offset + " LIMIT " + limit;
       // Execute the query and obtain results
  	final ResultSet results = rdfstoreDAO.executeSelect(sparqlEndpointURI, user, password, query);
 	if (results != null){
           while (results.hasNext())
           {
           	final QuerySolution soln = results.nextSolution() ;
           	final Resource res = soln.getResource("res");
       		final String resURI = res.getURI();
           	final String textToSearch = soln.getLiteral("text").getString();
           	final ResourceToLink resToLink = new ResourceToLink(textToSearch, resURI);
       		resourcesList.add(resToLink);
           }
	}
	if (resourcesList.isEmpty()) {
		return new ResourceToLink[0];
	}
	return (ResourceToLink[]) resourcesList.toArray(new ResourceToLink[resourcesList.size()]);
}
 
Example 10
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 11
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 12
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 13
Source Project: neo4jena   Source File: Course_Test.java    License: 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 14
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 15
/**
 * @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 16
Source Project: SolRDF   Source File: PagedResultSetTestCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Positive test.
 */
@Test
public void range() {
	final int offset = 120; 
	final int size = 24;
	
	final ResultSetRewindable cut = new PagedResultSet(executeQuery(), size, offset);
	final ResultSet resultSet = executeQuery();
	
	while (cut.hasNext()) {
		cut.next();
	}
	
	assertEquals(size, cut.size());
	cut.reset();
	
	for (int i = 0; i < offset; i++) {
		resultSet.next();
	}
	
	for (int i = 0; i < size; i++) {
		assertEquals(resultSet.nextBinding(), cut.nextBinding());
	}
	
	assertFalse(cut.hasNext());
}
 
Example 17
Source Project: wandora   Source File: SparqlExtractor.java    License: GNU General Public License v3.0 6 votes vote down vote up
public ResultSet importResultSet(InputStream in, String format) {
    ResultSet results = null;
    if(in != null) {
        if("JSON".equalsIgnoreCase(format)) {
            System.out.println("Processing SPARQL results set as JSON");
            results = JSONInput.fromJSON(in);
        }
        else if("XML".equalsIgnoreCase(format)) {
            System.out.println("Processing SPARQL results set as XML");
            results = ResultSetFactory.fromXML(in);
        }
        else if("RDF/XML".equalsIgnoreCase(format)) {
            System.out.println("Processing SPARQL results set as RDF/XML");
            results = ResultSetFactory.load(in, ResultsFormat.FMT_RDF_XML);
        }
    }
    return results;
}
 
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
Source Project: LodView   Source File: SPARQLEndPoint.java    License: MIT License 6 votes vote down vote up
public Model extractLocalData(Model result, String IRI, Model m, List<String> queries) throws Exception {

		// System.out.println("executing query on IRI");
		Resource subject = result.createResource(IRI);
		for (String query : queries) {
			QueryExecution qe = QueryExecutionFactory.create(parseQuery(query, IRI, null, -1, null), m);
			try {
				ResultSet rs = qe.execSelect();
				List<Statement> sl = new ArrayList<Statement>();
				while (rs.hasNext()) {
					QuerySolution qs = rs.next();
					RDFNode subject2 = qs.get("s");
					RDFNode property = qs.get("p");
					RDFNode object = qs.get("o");
					result.add(result.createStatement(subject2 != null ? subject2.asResource() : subject, property.as(Property.class), object));
				}
				result.add(sl);
			} catch (Exception e) {
				e.printStackTrace();
				throw new Exception("error in query execution: " + e.getMessage());
			} finally {
				qe.close();
			}
		}
		return result;
	}
 
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 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 22
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 23
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 24
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 25
Source Project: CostFed   Source File: Stats.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private static Info process(String endpoint, String query, String p) {
		
		long sum = 0, n = 0, sumsq = 0;
		for (int j2 = 0; true; j2++) {
			ResultSet rsPs = query(endpoint,
					query, p, j2 * 10000);
			int i2;
			for (i2 = 0; rsPs.hasNext(); i2++) {
				int f = rsPs.next().getLiteral("x").getInt();
				sum += f;
				sumsq += f * f;
//				System.out.println(sum + "," + sumsq);
			}
			n += i2;
			if (i2 == 0)
				break;
		}
		double mean = ((double) sum / n);
		System.out.println("Mean is " + mean);
//		System.out.println(sumsq + "," + sum + "," + n);
		double stdev = n==1 ? 0 : Math.sqrt(Math.abs(sumsq - (sum * sum) / (double) n)
				* (1.0d / (n - 1)));
		System.out.println("StDev is " + stdev);
		
		return new Info(mean, stdev);

	}
 
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 extractEventFoIAsResource(EventDeclaration ed, Dataset dataset, String foiId) {
	// if (ed instanceof TrafficReportService) {
	// extractTrafficLocation(ed, dataset);
	// } else {
	String queryStr = queryPrefix + " select  ?foi where { <" + ed.getServiceId()
			+ "> ssn:observes ?p. ?p ssn:isPropertyOf ?foi.}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	if (results.hasNext()) {
		RDFNode foi = results.next().get("foi");
		ed.setFoi(foi.toString());
		// }
	}
}
 
Example 27
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 28
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 29
Source Project: aliada-tool   Source File: RDFStoreDAO.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint, 
 * to get the discovered links.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param graphName 			the graphName, null in case of default graph.
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param offset				causes the solutions generated to start after 
 *                              the specified number of solutions.
 * @param limit					upper bound on the number of solutions returned.
 * @return a list of triples with the discovered links.
 * @since 2.0
 */
public Triple[] getDiscoveredLinks(final String sparqlEndpointURI, final String graphName, final String user, final String password, final int offset, final int limit) {
	final String query = "select * FROM <" + graphName + "> " + 
					"where {?source ?rel ?target }" +
					" ORDER BY ?source ?target" +
					" OFFSET " + offset + " LIMIT " + limit;
  	ArrayList<Triple> linksList = new ArrayList<Triple>();
 	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() ;
           	final Resource sourceResType = soln.getResource("source");
           	final Resource targetResType = soln.getResource("target");
           	final Resource relResType = soln.getResource("rel");
       		final Triple triple = new Triple(sourceResType.asNode(), relResType.asNode(), targetResType.asNode());
       		linksList.add(triple);
           }
        qexec.close() ;
      } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
	if (linksList.isEmpty()) {
		return new Triple[0];
	}
	return (Triple[]) linksList.toArray(new Triple[linksList.size()]);
}
 
Example 30
Source Project: aliada-tool   Source File: RDFStoreDAO.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * It executes a SELECT SPARQL query on the SPARQL endpoint,
 * to get the ambiguous discovered links.
 *
 * @param sparqlEndpointURI		the SPARQL endpoint URI.  
 * @param graphName 			the graphName, null in case of default graph.
 * @param user					the user name for the SPARQl endpoint.
 * @param password				the password for the SPARQl endpoint.
 * @param offset				causes the solutions generated to start after 
 *                              the specified number of solutions.
 * @param limit					upper bound on the number of solutions returned.
 * @return a list of {@link eu.aliada.shared.rdfstore.AmbiguousLink} with the ambiguous discovered links.
 * @since 2.0
 */
public AmbiguousLink[] getAmbiguousDiscoveredLinks(final String sparqlEndpointURI, final String graphName, final String user, final String password, final int offset, final int limit) {
	final String query = "SELECT ?localRes ?extResBegin (COUNT(?localRes) AS ?count) FROM <" + graphName + "> " + 
			" WHERE {?localRes ?rel ?extRes ." +
			" BIND( str(?extRes) as ?extResStr )." +
			" BIND( SUBSTR(?extResStr, 1,14) AS ?extResBegin)" +
			" }" +
			" GROUP BY ?localRes ?extResBegin" +
			" HAVING (COUNT(?localRes) > 1)" +
			" ORDER BY ?localRes" +
			" OFFSET " + offset + " LIMIT " + limit;
	
	ArrayList<AmbiguousLink> ambiguousLinksList = new ArrayList<AmbiguousLink>();
	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() ;
	    	final Resource localRes = soln.getResource("localRes");
	    	final String extResBegin = soln.getLiteral("extResBegin").getString();
	    	final AmbiguousLink ambiguousLink = new AmbiguousLink();
	    	ambiguousLink.setSourceURI(localRes.getURI());
	    	getSourceURIAmbiguousLinks(ambiguousLink, localRes, extResBegin, sparqlEndpointURI, graphName, user, password);
	    	ambiguousLinksList.add(ambiguousLink);
	    }
	    qexec.close() ;
	  } catch (Exception exception) {
		LOGGER.error(MessageCatalog._00035_SPARQL_FAILED, exception, query);
	}
	if (ambiguousLinksList.isEmpty()) {
		return new AmbiguousLink[0];
	}
	return (AmbiguousLink[]) ambiguousLinksList.toArray(new AmbiguousLink[ambiguousLinksList.size()]);
}