Java Code Examples for com.hp.hpl.jena.query.QueryExecutionFactory#create()

The following examples show how to use com.hp.hpl.jena.query.QueryExecutionFactory#create() . 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: RDFFileManager.java    From Benchmark with 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 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 3
Source File: RDFFileManager.java    From Benchmark with 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 4
Source File: RDFFileManager.java    From Benchmark with 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 5
Source File: ModelImplJena.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String queryString)
        throws ModelRuntimeException {
	assertModel();
	Query query = QueryFactory.create(queryString);
	QueryExecution qexec = QueryExecutionFactory.create(query, this.jenaModel);
	
	if(query.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 queries! Please use CONSTRUCT.");
	}
}
 
Example 6
Source File: RDFFileManager.java    From Benchmark with 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 File: ContextService.java    From semanticMDR with GNU General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{contextid}/de")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response getDataElements(@PathParam("contextid") String contextId,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();

	String queryString;
	File file = new File(QUERY_FILE_GET_ALL_FROM_CONTEXT);
	try {
		queryString = FileUtils.readFileToString(file);
	} catch (IOException e) {
		logger.error("File with context serialization query could not be found ");
		return Response.serverError().build();
	}

	ParameterizedSparqlString query = new ParameterizedSparqlString(
			queryString);
	query.setLiteral("uuid", ResourceFactory.createTypedLiteral(contextId));
	QueryExecution qe = QueryExecutionFactory.create(query.asQuery(),
			ontModel);
	Model resultModel = qe.execConstruct();

	graphStream.setModel(resultModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 8
Source File: IntegrationTestSupertypeLayer.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given CONSTRUCT query against a given dataset.
 * 
 * @param data the mistery guest containing test data (query and dataset)
 * @throws Exception never, otherwise the test fails.
 */
protected void describeTest(final MisteryGuest data) throws Exception {
	load(data);
	
	final Query query = QueryFactory.create(queryString(data.query));
	try {
		inMemoryExecution = QueryExecutionFactory.create(query, memoryDataset);
		
		assertTrue(
				Arrays.toString(data.datasets) + ", " + data.query,
				inMemoryExecution.execDescribe().isIsomorphicWith(
						SOLRDF_CLIENT.describe(queryString(data.query))));
	} catch (final Throwable error) {
		StringWriter writer = new StringWriter();
		RDFDataMgr.write(writer, SOLRDF_CLIENT.describe(queryString(data.query)), RDFFormat.NTRIPLES);
		log.debug("JNS\n" + writer);
		
		QueryExecution debugExecution = QueryExecutionFactory.create(query, memoryDataset);
		writer = new StringWriter();
		RDFDataMgr.write(writer, debugExecution.execDescribe(), RDFFormat.NTRIPLES);
		
		log.debug("MEM\n" + writer);
		
		debugExecution.close();
		throw error;
	} 
}
 
Example 9
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 10
Source File: QueryHelper.java    From ldp4j with Apache License 2.0 5 votes vote down vote up
public <T> T select(ResultProcessor<T> collector) {
	try(QueryExecution execution = QueryExecutionFactory.create(build(),this.model)) {
		ResultSet resultSet = execution.execSelect();
		while(resultSet.hasNext()) {
			collector.handle(resultSet.next());
		}
		return collector.getResult();
	}
}
 
Example 11
Source File: IntegrationTestSupertypeLayer.java    From SolRDF with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given ASK query against a given dataset.
 * 
 * @param data the mistery guest containing test data (query and dataset)
 * @throws Exception never, otherwise the test fails.
 */
protected void askTest(final MisteryGuest data) throws Exception {
	load(data);
	
	inMemoryExecution = QueryExecutionFactory.create(QueryFactory.create(queryString(data.query)), memoryDataset);
		
	assertEquals(
			Arrays.toString(data.datasets) + ", " + data.query,
			inMemoryExecution.execAsk(),
			SOLRDF_CLIENT.ask(queryString(data.query)));
}
 
Example 12
Source File: ModelSetImplJena.java    From semweb4j with 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.");
	}
}
 
Example 13
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 14
Source File: RDFFileManager.java    From Benchmark with 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 15
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 16
Source File: TDBQueryFactory.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected QueryExecution createQueryExecution(String queryString,
		OntModel ontModel) {
	return QueryExecutionFactory.create(queryString,
			this.mdrDatabase.getOntModel());
}
 
Example 17
Source File: SerializationService.java    From semanticMDR with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 
 * @param type
 *            outputFormat "N3", "N-TRIPLE", "RDF/XML-ABBREV" or
 *            "TURTLE"default: "RDF/XML".
 * @param uuid
 * @return
 */
@GET
@Path("/graph")
@Produces({ WebUtil.MEDIA_TYPE_APPLICATION_NTRIPLE,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFJSON,
		WebUtil.MEDIA_TYPE_APPLICATION_RDFXML, MediaType.TEXT_PLAIN,
		WebUtil.MEDIA_TYPE_TEXT_N3, WebUtil.MEDIA_TYPE_TEXT_TURTLE })
public Response serialize(@QueryParam("id") String uuid, @QueryParam("uri") String uri,
		@Context Request request) {

	Variant variant = request.selectVariant(WebUtil.VARIANTS);
	MediaType mediaType = variant.getMediaType();

	Repository repository = RepositoryManager.getInstance().getRepository();
	OntModel ontModel = repository.getMDRDatabase().getOntModel();
	
	String query = "";
	if(uuid != null) {
		// get the uri of the resource
		query = "prefix mdr:     <http://www.salusproject.eu/iso11179-3/mdr#> "
				+ "prefix xsd:     <http://www.w3.org/2001/XMLSchema#> "
				+ "SELECT ?resource WHERE { " + "?resource ?op ?ar . "
				+ "?ar mdr:administeredItemIdentifier ?ii . "
				+ "?ii mdr:dataIdentifier \"" + uuid + "\"^^xsd:string. " + "}";

		logger.debug("Query execution: {}", query);
		Query q = QueryFactory.create(query);
		QueryExecution qe = QueryExecutionFactory.create(q, ontModel);
		ResultSet rs = qe.execSelect();

		while (rs.hasNext()) {
			QuerySolution qs = rs.next();
			uri = qs.getResource("resource").getURI();
		}
	}

	if(uri == null) {
		throw new WebApplicationException(Response.Status.BAD_REQUEST);
	}
	
	// use the uri to construct the model and return its serialization.
	query = "CONSTRUCT WHERE { <" + uri + "> ?p ?o .}";
	Query q2 = QueryFactory.create(query);
	QueryExecution qe2 = QueryExecutionFactory.create(q2, ontModel);
	Model outModel = qe2.execConstruct();

	graphStream.setModel(outModel);
	graphStream.setLanguage(WebUtil.getSerializationLanguage(mediaType
			.toString()));

	return Response.ok(graphStream).build();
}
 
Example 18
Source File: RDFFileManager.java    From Benchmark with GNU General Public License v3.0 4 votes vote down vote up
private static void extractEventQoS(EventDeclaration ed, Dataset dataset) {
	// TODO change quality prefix

	String queryStr = queryPrefix
			+ " select  ?type ?value where {<"
			+ ed.getnodeId()
			+ "> owls:presents ?profile. ?profile ?hasnfp ?x. ?x rdf:type ?type. ?x owlssp:sParameter ?y. ?y emvo:hasQuantityValue ?value "
			+ " graph <http://www.insight-centre.org/ces#> {?hasnfp rdfs:subPropertyOf owlssp:serviceParameter}}";

	// String queryStr = queryPrefix
	// +
	// " select ?srvId ?type ?value where {?srvId owls:presents ?profile. ?profile ?hasnfp ?x. ?x rdf:type ?type. ?x owlssp:sParameter ?y. ?y emvo:hasQuantityValue ?value }";
	long t1 = System.currentTimeMillis();
	// String queryStr = queryPrefix
	// + "select ?srvId ?srvCatName ?pType ?foiId ?a ?b ?c ?d ?qType ?qValue where { "
	// +
	// "?srvId owls:presents ?profile. ?profile owlssc:serviceCategory ?srvCat. ?srvCat owlssc:serviceCategoryName "
	// + "?srvCatName. ?srvId ssn:observes ?pid. ?pid rdf:type ?pType. ?pid ssn:isPropertyOf ?foiId. "
	// + "?foiId ct:hasStartLatitude ?a. ?foiId ct:hasStartLongitude ?b. ?foiId ct:hasEndLatitude ?c. "
	// + "?foiId ct:hasEndLongitude ?d. OPTIONAL {?srvId owls:presents ?profile.  ?profile ?hasnfp ?x.  "
	// + "?x rdf:type ?qType.  ?x owlssp:sParameter ?y.  ?y emvo:hasQuantityValue ?qValue "
	// + "graph <http://www.insight-centre.org/ces#> {?hasnfp rdfs:subPropertyOf ces:hasNFP}}}";
	QueryExecution qe = QueryExecutionFactory.create(queryStr, dataset);
	ResultSet results = qe.execSelect();
	QosVector qos = new QosVector();
	boolean hasQos = false;
	int sum = 0;
	while (results.hasNext()) {
		sum++;
		hasQos = true;
		QuerySolution row = results.next();
		RDFNode type = row.get("type");
		RDFNode value = row.get("value");
		// type.
		// ed.setSrc(addr.toString());
		// System.out.println("type: " + type + "\n value: " + value);
		if (type.toString().equals("http://www.insight-centre.org/ces#Security"))
			qos.setSecurity(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Price"))
			qos.setPrice(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Accuracy"))
			qos.setAccuracy(value.asLiteral().getDouble());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Reliability"))
			qos.setReliability(value.asLiteral().getDouble());
		else if (type.toString().equals("http://www.insight-centre.org/ces#Latency"))
			qos.setLatency(value.asLiteral().getInt());
		else if (type.toString().equals("http://www.insight-centre.org/ces#BandWidthConsumption"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#Availability"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#EnergyConsumption"))
			;
		else if (type.toString().equals("http://www.insight-centre.org/ces#Frequency"))
			ed.setFrequency(value.asLiteral().getDouble());
	}
	long t2 = System.currentTimeMillis();
	// logger.info("QoS extracted: " + qos);
	if (qos.getAccuracy() != null)
		ed.setInternalQos(qos);

}
 
Example 19
Source File: ResourceDescriptionServlet.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
protected void doGet(HttpServletRequest request,
		HttpServletResponse response) throws IOException, ServletException {
	D2RServer server = D2RServer.fromServletContext(getServletContext());
	server.checkMappingFileChanged();
	String relativeResourceURI = request.getRequestURI().substring(
			request.getContextPath().length()
					+ request.getServletPath().length());
	// Some servlet containers keep the leading slash, some don't
	if (!"".equals(relativeResourceURI)
			&& "/".equals(relativeResourceURI.substring(0, 1))) {
		relativeResourceURI = relativeResourceURI.substring(1);
	}
	if (request.getQueryString() != null) {
		relativeResourceURI = relativeResourceURI + "?"
				+ request.getQueryString();
	}

	/* Determine service stem, i.e. vocab/ in /[vocab/]data */
	int servicePos;
	if (-1 == (servicePos = request.getServletPath().indexOf(
			"/" + D2RServer.getDataServiceName())))
		throw new ServletException("Expected to find service path /"
				+ D2RServer.getDataServiceName());
	String serviceStem = request.getServletPath().substring(1,
			servicePos + 1);

	String resourceURI = RequestParamHandler
			.removeOutputRequestParam(server.resourceBaseURI(serviceStem)
					+ relativeResourceURI);
	String documentURL = server.dataURL(serviceStem, relativeResourceURI);

	String pageURL = server.pageURL(serviceStem, relativeResourceURI);

	String sparqlQuery = "DESCRIBE <" + resourceURI + ">";
	QueryExecution qe = QueryExecutionFactory.create(sparqlQuery,
			server.dataset());
	if (server.getConfig().getPageTimeout() > 0) {
		qe.setTimeout(Math.round(server.getConfig().getPageTimeout() * 1000));
	}
	Model description = qe.execDescribe();
	qe.close();
	
	if (description.size() == 0) {
		response.sendError(404);
	}
	if (description.qnameFor(FOAF.primaryTopic.getURI()) == null
			&& description.getNsPrefixURI("foaf") == null) {
		description.setNsPrefix("foaf", FOAF.NS);
	}
	Resource resource = description.getResource(resourceURI);

	Resource document = description.getResource(documentURL);
	document.addProperty(FOAF.primaryTopic, resource);

	Statement label = resource.getProperty(RDFS.label);
	if (label != null) {
		document.addProperty(RDFS.label,
				"RDF Description of " + label.getString());
	}
	server.addDocumentMetadata(description, document);
	if (server.getConfig().serveMetadata()) {
		// add document metadata from template
		Model resourceMetadataTemplate = server.getConfig().getResourceMetadataTemplate(
				server, getServletContext());
		MetadataCreator resourceMetadataCreator = new MetadataCreator(
				server, resourceMetadataTemplate);
		description.add(resourceMetadataCreator.addMetadataFromTemplate(
				resourceURI, documentURL, pageURL));
		
		Map<String, String> descPrefixes = description.getNsPrefixMap();
		descPrefixes.putAll(resourceMetadataTemplate.getNsPrefixMap());
		description.setNsPrefixes(descPrefixes);
	}
	// TODO: Add a Content-Location header
	new ModelResponse(description, request, response).serve();
}
 
Example 20
Source File: Sparql.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Object execute(Map<String, EdmLiteral> parameters) throws ODataException
{
   EdmLiteral query_lit = parameters.remove("query");
   // Olingo2 checks for presence of non-nullable parameters for us!
   String query_s = query_lit.getLiteral();
   Query query = QueryFactory.create(query_s);
   if (!(query.isSelectType() || query.isDescribeType()))
   {
      throw new InvalidOperationException(query.getQueryType());
   }

   DrbCortexModel cortexmodel;
   try
   {
      cortexmodel = DrbCortexModel.getDefaultModel();
   }
   catch (IOException ex)
   {
      throw new RuntimeException(ex);
   }

   Model model = cortexmodel.getCortexModel().getOntModel();

   QueryExecution qexec = null;
   // FIXME: QueryExecution in newer versions of Jena (post apache incubation) implement AutoClosable.
   try
   {
      qexec = QueryExecutionFactory.create(query, model);
      if (query.isSelectType())
      {
         ResultSet results = qexec.execSelect();
         return ResultSetFormatter.asXMLString(results);
      }
      else
      {
         Model description = qexec.execDescribe();
         // newer version of Jena have the RIOT package for I/O
         StringWriter strwrt = new StringWriter();
         Abbreviated abb = new Abbreviated();
         abb.write(description, strwrt, null);
         return strwrt.toString();
      }
   }
   finally
   {
      if (qexec != null)
      {
         qexec.close();
      }
   }
}