Java Code Examples for org.apache.jena.query.QuerySolutionMap

The following examples show how to use org.apache.jena.query.QuerySolutionMap. 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: shacl   Author: TopQuadrant   File: AbstractSPARQLExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private void addDefaultMessages(ValidationEngine engine, Resource messageHolder, Resource fallback, Resource result, 
			QuerySolution bindings, QuerySolution solution) {
	boolean found = false;
	for(Statement s : messageHolder.listProperties(SH.message).toList()) {
		if(s.getObject().isLiteral()) {
			QuerySolutionMap map = new QuerySolutionMap();
			map.addAll(bindings);
			map.addAll(solution);
			engine.addResultMessage(result, s.getLiteral(), map);
			found = true;
		}
	}
	if(!found && fallback != null) {
		addDefaultMessages(engine, fallback, null, result, bindings, solution);
	}
}
 
Example #2
Source Project: shacl   Author: TopQuadrant   File: SPARQLTarget.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(Dataset dataset, RDFNode node) {
	QuerySolutionMap bindings = new QuerySolutionMap();
	bindings.add(SH.thisVar.getVarName(), node);
	if(parameterizableTarget != null) {
		parameterizableTarget.addBindings(bindings);
	}
	if(query.isAskType()) {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    return qexec.execAsk();
		}
	}
	else {
		try(QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, dataset, bindings)) {
		    ResultSet rs = qexec.execSelect();
		    return rs.hasNext();
		}
	}
}
 
Example #3
Source Project: shacl   Author: TopQuadrant   File: JSComponentExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   protected Collection<RDFNode> getValueNodes(ValidationEngine validationEngine, Constraint constraint, QuerySolutionMap bindings, RDFNode focusNode) {
	SHConstraintComponent component = constraint.getComponent();
	Resource context = constraint.getContext();
	Resource validatorResource = component.getValidator(SH.JSValidator, context);
	if(SH.PropertyShape.equals(context)) {
		if(component.hasProperty(SH.propertyValidator, validatorResource)) {
			bindings.add("path", constraint.getShapeResource().getRequiredProperty(SH.path).getObject());
			List<RDFNode> valueNodes = new ArrayList<>();
			valueNodes.add(null);
			return valueNodes;
		}
		else {
			return validationEngine.getValueNodes(constraint, focusNode);
		}
	}
	else {
		bindings.add("value", focusNode);
		return Collections.singletonList(focusNode);
	}
}
 
Example #4
Source Project: shacl   Author: TopQuadrant   File: SPARQLRule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(RuleEngine ruleEngine, List<RDFNode> focusNodes, Shape shape) {
	ProgressMonitor monitor = ruleEngine.getProgressMonitor();
	for(RDFNode focusNode : focusNodes) {
		
		if(monitor != null && monitor.isCanceled()) {
			return;
		}

		QuerySolutionMap bindings = new QuerySolutionMap();
		bindings.add(SH.thisVar.getVarName(), focusNode);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, ruleEngine.getDataset(), bindings)) {
			Iterator<Triple> it = qexec.execConstructTriples();
			while(it.hasNext()) {
				Triple triple = it.next();
				ruleEngine.infer(triple, this, shape);
			}
		}
	}
}
 
Example #5
Source Project: Processor   Author: AtomGraph   File: TemplateCall.java    License: Apache License 2.0 6 votes vote down vote up
public QuerySolutionMap getQuerySolutionMap()
{
    QuerySolutionMap qsm = new QuerySolutionMap();
    
    org.spinrdf.model.TemplateCall spinTemplateCall = SPINFactory.asTemplateCall(getTemplate().getQuery());
    if (spinTemplateCall != null)
    {
        qsm = spinTemplateCall.getInitialBinding();
        
        List<org.spinrdf.model.Argument> spinArgs = spinTemplateCall.getTemplate().getArguments(false);
        // add SPIN Arguments that match LDT Arguments (by predicate)
        for (org.spinrdf.model.Argument spinArg : spinArgs)
            if (getTemplate().getParameters().containsKey(spinArg.getPredicate()) && hasArgument(spinArg.getPredicate()))
            {
                Parameter param = getTemplate().getParameters().get(spinArg.getPredicate());
                qsm.add(param.getVarName(), getArgumentProperty(param.getPredicate()).getObject());
            }
    }
            
    return qsm;
}
 
Example #6
Source Project: incubator-taverna-language   Author: apache   File: CombineManifest.java    License: Apache License 2.0 6 votes vote down vote up
private static List<RDFNode> creatingAgentsFor(Resource r) {
	logger.fine("Finding creator of " + r);
	String queryStr = sparqlPrefixes + "SELECT ?agent WHERE { \n" + " { \n"
			+ "  ?r dct:creator [ \n" + "	    rdfs:member ?agent \n"
			+ "  ] \n" + " } UNION { \n" + "   ?r dct:creator ?agent .\n "
			+ "   FILTER NOT EXISTS { ?agent rdfs:member ?member } \n"
			+ " } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			r.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("r", r);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	List<RDFNode> agents = new ArrayList<>();

	while (select.hasNext()) {
		RDFNode agent = select.next().get("agent");
		logger.fine("Found: " + agent);
		agents.add(agent);
	}
	return agents;
}
 
Example #7
Source Project: incubator-taverna-language   Author: apache   File: CombineManifest.java    License: Apache License 2.0 6 votes vote down vote up
private static Resource mboxForAgent(Resource agentResource) {
	logger.fine("Finding mbox of " + agentResource);
	String queryStr = sparqlPrefixes + "SELECT ?mbox WHERE { \n"
			+ "		{ ?agent foaf:mbox ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:hasEmail ?mbox } \n" + "	UNION  \n"
			+ "		{ ?agent vcard:email ?email .  \n"
			+ "       BIND(IRI(CONCAT(\"mbox:\", ?email)) AS ?mbox) \n" // legacy
			+ "	    } \n" + "} \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		Resource mbox = select.next().getResource("mbox");
		logger.fine("Found mbox: " + mbox);
		return mbox;
	}
	logger.fine("mbox not found");
	return null;
}
 
Example #8
Source Project: RDFUnit   Author: AKSW   File: TestCaseWithTarget.java    License: Apache License 2.0 6 votes vote down vote up
private String injectTarget(String sparqlQuery, ShapeTarget target) {
    String changedQuery = sparqlQuery;

    if (target.getTargetType().equals(ShapeTargetType.NodeTarget)) {
        changedQuery = sparqlQuery
                .replaceFirst("[\\$\\?]this", thisVar )
                .replaceAll("(?i)BOUND\\s*\\(\\s*[\\$\\?]this\\s*\\)", "BOUND\\("+ thisVar+"\\)")
                .replaceAll("(?i)GROUP\\s+BY\\s+[\\$\\?]this", "GROUP BY "+ thisVar);

        QuerySolutionMap qsm = new QuerySolutionMap();
        qsm.add(CommonNames.This, target.getNode());
        ParameterizedSparqlString pq = new ParameterizedSparqlString(changedQuery, qsm);
        changedQuery = pq.toString();

        changedQuery = changedQuery
                .replaceFirst(thisVar, "\\$this")
                .replaceAll("(?i)BOUND\\("+ thisVar+"\\)", "BOUND\\(\\?this\\)")
                .replaceAll("(?i)GROUP BY "+ thisVar, "GROUP BY \\$this");
    }

    return injectSparqlSnippet(changedQuery, target.getPattern());
}
 
Example #9
Source Project: rdf2neo   Author: Rothamsted   File: RdfDataManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Uses the underlining TDB and mapping queries to create a new {@link CyNode} instance.
 * 
 * @param nodeRes the RDF/Jena resource correspnding to the Cypher node. This provides the ?iri paramter in the queries below.
 * @param labelsSparql the node labels query, which is usually taken from {@link CyNodeLoadingHandler#getLabelsSparql()}.
 * @param propsSparql the node properties query, which is usually taken from {@link CyNodeLoadingHandler#getNodePropsSparql()}.
 */
public CyNode getCyNode ( Resource nodeRes, String labelsSparql, String propsSparql )
{
	ensureOpen ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", nodeRes );

	CyNode cyNode = new CyNode ( nodeRes.getURI () );
	
	// The node's labels
	if ( labelsSparql != null )
	{
		// If it's omitted, it will get the default label.
		Query qry = SparqlUtils.getCachedQuery ( labelsSparql );
		Function<String, String> labelIdConverter = this.getCyNodeLabelIdConverter ();
		
		boolean wasInTnx = dataSet.isInTransaction ();
		if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
		try {
			QueryExecution qx = QueryExecutionFactory.create ( qry, this.getDataSet(), params );
			qx.execSelect ().forEachRemaining ( row ->
				cyNode.addLabel ( this.getCypherId ( row.get ( "label" ), labelIdConverter ) )
			);
		}
		finally {
			if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
		}
	}
	
	// and the properties
	this.addCypherProps ( cyNode, propsSparql );
	
	return cyNode;
}
 
Example #10
Source Project: rdf2neo   Author: Rothamsted   File: RdfDataManager.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Take an existing {@link CypherEntity} and adds the properties that can be mapped from the underlining TDB by means 
 * of a property query, like {@link CyNodeLoadingHandler#getNodePropsSparql()}, or 
 * {@link CyRelationLoadingHandler#getRelationPropsSparql()}.
 * 
 * It doesn't do anything if the query is null.
 * 
 */
protected void addCypherProps ( CypherEntity cyEnt, String propsSparql )
{
	ensureOpen ();		
	Dataset dataSet = this.getDataSet ();
	
	QuerySolutionMap params = new QuerySolutionMap ();
	params.add ( "iri", dataSet.getUnionModel().getResource ( cyEnt.getIri () ) );

	// It may be omitted, if you don't have any property except the IRI.
	if ( propsSparql == null ) return;
	
	Query qry = SparqlUtils.getCachedQuery ( propsSparql );
	Function<String, String> propIdConverter = this.getCyPropertyIdConverter ();
	
	boolean wasInTnx = dataSet.isInTransaction ();
	if ( !wasInTnx ) dataSet.begin ( ReadWrite.READ );
	try
	{
		QueryExecution qx = QueryExecutionFactory.create ( qry, dataSet, params );
		qx.execSelect ().forEachRemaining ( row ->
		{
			String propName = this.getCypherId ( row.get ( "name" ), propIdConverter );
			if ( propName == null ) throw new IllegalArgumentException ( 
				"Null property name for " + cyEnt.getIri () 
			);
			
			String propValue = JENAUTILS.literal2Value ( row.getLiteral ( "value" ) ).get ();
			cyEnt.addPropValue ( propName, propValue );
		});
	}
	finally {
		if ( !wasInTnx && dataSet.isInTransaction () ) dataSet.end ();
	}
}
 
Example #11
Source Project: shacl   Author: TopQuadrant   File: JenaUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Turns a Binding into a QuerySolutionMap.
 * @param binding  the Binding to convert
 * @return a QuerySolutionMap
 */
public static QuerySolutionMap asQuerySolutionMap(Binding binding) {
	QuerySolutionMap map = new QuerySolutionMap();
	Iterator<Var> vars = binding.vars();
	while(vars.hasNext()) {
		Var var = vars.next();
		Node node = binding.get(var);
		if(node != null) {
			map.add(var.getName(), dummyModel.asRDFNode(node));
		}
	}
	return map;
}
 
Example #12
Source Project: shacl   Author: TopQuadrant   File: JSTarget.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addTargetNodes(Dataset dataset, Collection<RDFNode> results) {
	
	boolean nested = SHACLScriptEngineManager.begin();
	JSScriptEngine engine = SHACLScriptEngineManager.getCurrentEngine();

	Model model = dataset.getDefaultModel();
	JSGraph dataJSGraph = new JSGraph(model.getGraph(), engine);
	try {
		engine.executeLibraries(as);
		engine.put(SH.JS_DATA_VAR, dataJSGraph);
		
		QuerySolutionMap bindings = new QuerySolutionMap();
		if(parameterizableTarget != null) {
			parameterizableTarget.addBindings(bindings);
		}

		Object result = engine.invokeFunction(as.getFunctionName(), bindings);
		if(NashornUtil.isArray(result)) {
			for(Object obj : NashornUtil.asArray(result)) {
				Node node = JSFactory.getNode(obj);
				results.add(model.asRDFNode(node));
			}
		}
	}
	catch(Exception ex) {
		ExceptionUtil.throwUnchecked(ex);
	}
	finally {
		dataJSGraph.close();
		SHACLScriptEngineManager.end(nested);
	}
}
 
Example #13
Source Project: shacl   Author: TopQuadrant   File: Templates.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Takes an instance of dash:SPARQLConstructTemplate and parameter bindings and returns a Model with the triples
 * that result from the execution of all CONSTRUCT queries in the template using the given parameter bindings.
 * @param template  the template defining the sh:construct queries to run
 * @param bindings  the initial bindings for the CONSTRUCT queries
 * @param dataset  the Dataset to query over
 * @return a Model with the constructed triples
 */
public static Model construct(Resource template, QuerySolutionMap bindings, Dataset dataset) {
	Model result = JenaUtil.createDefaultModel();
	template.listProperties(SH.construct).filterKeep(s -> s.getObject().isLiteral()).forEachRemaining(s -> {			
		String queryString = s.getString();
		Query arqQuery = ARQFactory.get().createQuery(SPARQLSubstitutions.withPrefixes(queryString, template));
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(arqQuery, dataset, bindings)) {
			qexec.execConstruct(result);
		}
	});
	return result;
}
 
Example #14
Source Project: shacl   Author: TopQuadrant   File: SHParameterizableInstanceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void addBindings(QuerySolutionMap bindings) {
	for(SHParameter arg : getParameterizable().getParameters()) {
		Statement s = getProperty(arg.getPredicate());
		if(s != null) {
			bindings.add(arg.getVarName(), s.getObject());
		}
	}
}
 
Example #15
Source Project: shacl   Author: TopQuadrant   File: SHACLUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets any locally-defined label for a given property.
 * The labels are expected to be attached to shapes associated with a given
 * context resource (instance).
 * That context resource may for example be the subject of the current UI form.
 * @param property  the property to get the label of
 * @param context  the context instance
 * @return the local label or null if it should fall back to a global label
 */
public static String getLocalPropertyLabel(Resource property, Resource context) {
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("arg1", property);
	binding.add("arg2", context);
	try(QueryExecution qexec = ARQFactory.get().createQueryExecution(propertyLabelQuery, property.getModel(), binding)) {
	    ResultSet rs = qexec.execSelect();
	    if(rs.hasNext()) {
	        return rs.next().get("label").asLiteral().getLexicalForm();
	    }
	}
	return null;
}
 
Example #16
Source Project: shacl   Author: TopQuadrant   File: AbstractSPARQLExpression.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ExtendedIterator<RDFNode> eval(RDFNode focusNode, NodeExpressionContext context) {
	List<RDFNode> focusNodes;
	NodeExpression input = getInput();
	if(input != null) {
		focusNodes = input.eval(focusNode, context).toList();
	}
	else {
		focusNodes = Collections.singletonList(focusNode);
	}
	List<RDFNode> results = new LinkedList<>();
	for(RDFNode f : focusNodes) {
		QuerySolutionMap binding = new QuerySolutionMap();
		binding.add(SH.thisVar.getName(), f);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, focusNode.getModel(), binding)) {
			if(query.isAskType()) {
				results.add(qexec.execAsk() ? JenaDatatypes.TRUE : JenaDatatypes.FALSE);
			}
			else {
				ResultSet rs = qexec.execSelect();
				String varName = rs.getResultVars().get(0);
				while(rs.hasNext()) {
					RDFNode node = rs.next().get(varName);
					if(node != null) {
						results.add(node);
					}
				}
			}
		}
	}
	return WrappedIterator.create(results.iterator());
}
 
Example #17
Source Project: Processor   Author: AtomGraph   File: TemplateCallTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetQuerySolutionMap()
{
    QuerySolutionMap qsm = new QuerySolutionMap();
    qsm.add(predicate1.getLocalName(), QUERY_BINDING);
    
    assertEquals(qsm.asMap(), call.getQuerySolutionMap().asMap());
}
 
Example #18
Source Project: RDFstarTools   Author: RDFstar   File: TextOutputStarTest.java    License: Apache License 2.0 4 votes vote down vote up
public QuerySolution createQuerySolution( String varName, Node n ) {
	final RDFNode nn = ModelFactory.createDefaultModel().asRDFNode(n);
	final QuerySolutionMap s = new QuerySolutionMap();
	s.add(varName, nn);
	return s;
}
 
Example #19
Source Project: shacl   Author: TopQuadrant   File: AbstractSPARQLExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	
	QuerySolutionMap bindings = new QuerySolutionMap();
	addBindings(constraint, bindings);
	bindings.add(SH.currentShapeVar.getVarName(), constraint.getShapeResource());
	bindings.add(SH.shapesGraphVar.getVarName(), ResourceFactory.createResource(engine.getShapesGraphURI().toString()));
	
	Resource path = constraint.getShapeResource().getPath();
	if(path != null && path.isURIResource()) {
		bindings.add(SH.PATHVar.getName(), path);
	}
	
	URI oldShapesGraphURI = HasShapeFunction.getShapesGraphURI();
	ShapesGraph oldShapesGraph = HasShapeFunction.getShapesGraph();
	if(!engine.getShapesGraphURI().equals(oldShapesGraphURI)) {
		HasShapeFunction.setShapesGraph(engine.getShapesGraph(), engine.getShapesGraphURI());
	}
	
	Model oldNestedResults = HasShapeFunction.getResultsModel();
	Model nestedResults = JenaUtil.createMemoryModel();
	HasShapeFunction.setResultsModel(nestedResults);
	
	try {
		long startTime = System.currentTimeMillis();
		Resource messageHolder = getSPARQLExecutable(constraint);
		for(RDFNode focusNode : focusNodes) {
			bindings.add(SH.thisVar.getVarName(), focusNode); // Overwrite any previous binding
			QueryExecution qexec = SPARQLSubstitutions.createQueryExecution(query, engine.getDataset(), bindings);
			executeSelectQuery(engine, constraint, messageHolder, nestedResults, focusNode, qexec, bindings);
			engine.checkCanceled();
		}			
		if(ExecStatisticsManager.get().isRecording()) {
			long endTime = System.currentTimeMillis();
			long duration = endTime - startTime;
			String label = getLabel(constraint);
			Iterator<String> varNames = bindings.varNames();
			if(varNames.hasNext()) {
				queryString += "\nBindings:";
				while(varNames.hasNext()) {
					String varName = varNames.next();
					queryString += "\n- ?" + varName + ": " + bindings.get(varName);
				}
			}
			ExecStatistics stats = new ExecStatistics(label, queryString, duration, startTime, constraint.getComponent().asNode());
			ExecStatisticsManager.get().add(Collections.singletonList(stats));
		}
	}
	finally {
		HasShapeFunction.setShapesGraph(oldShapesGraph, oldShapesGraphURI);
		HasShapeFunction.setResultsModel(oldNestedResults);
	}
}
 
Example #20
Source Project: shacl   Author: TopQuadrant   File: SPARQLComponentExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void addBindings(Constraint constraint, QuerySolutionMap bindings) {
	constraint.addBindings(bindings);
}
 
Example #21
Source Project: shacl   Author: TopQuadrant   File: SPARQLConstraintExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void addBindings(Constraint constraint, QuerySolutionMap bindings) {
	// Do nothing
}
 
Example #22
Source Project: shacl   Author: TopQuadrant   File: AbstractJSExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine validationEngine, Collection<RDFNode> focusNodes) {
	
	JSScriptEngine jsEngine = SHACLScriptEngineManager.getCurrentEngine();
	
	Dataset dataset = validationEngine.getDataset();
	URI shapesGraphURI = validationEngine.getShapesGraphURI();
	String functionName = null;
	JSGraph shapesJSGraph = new JSGraph(validationEngine.getShapesModel().getGraph(), jsEngine);
	Model dataModel = dataset.getDefaultModel();
	Object oldSHACL = jsEngine.get(SHACL);
	jsEngine.put(SHACL, new SHACLObject(validationEngine.getShapesGraph(), shapesGraphURI, dataset));
	JSGraph dataJSGraph = new JSGraph(dataModel.getGraph(), jsEngine);
	try {
		
		jsEngine.put(SH.JS_SHAPES_VAR, shapesJSGraph);
		jsEngine.put(SH.JS_DATA_VAR, dataJSGraph);
		
		QuerySolutionMap bindings = new QuerySolutionMap();
		bindings.add(SH.currentShapeVar.getName(), constraint.getShapeResource());
		addBindings(constraint, bindings);

		SHJSExecutable executable = getExecutable(constraint);
		functionName = executable.getFunctionName();
		jsEngine.executeLibraries(executable);
		
		long startTime = System.currentTimeMillis();
		for(RDFNode theFocusNode : focusNodes) {
			validationEngine.checkCanceled();
			Object resultObj;
			bindings.add(SH.thisVar.getVarName(), theFocusNode);
			
			for(RDFNode valueNode : getValueNodes(validationEngine, constraint, bindings, theFocusNode)) {
				bindings.add("value", valueNode);
				resultObj = jsEngine.invokeFunction(functionName, bindings);
				handleJSResultObject(resultObj, validationEngine, constraint, theFocusNode, valueNode, executable, bindings);
			}
		}
		if(ExecStatisticsManager.get().isRecording()) {
			long endTime = System.currentTimeMillis();
			long duration = endTime - startTime;
			String label = getLabel(constraint);
			ExecStatistics stats = new ExecStatistics(label, null, duration, startTime, constraint.getComponent().asNode());
			ExecStatisticsManager.get().add(Collections.singletonList(stats));
		}
	}
	catch(Exception ex) {
		ex.printStackTrace();
		Resource result = validationEngine.createResult(DASH.FailureResult, constraint, null);
		result.addProperty(SH.resultMessage, "Could not execute JavaScript constraint");
		if(SH.JSConstraintComponent.equals(constraint.getComponent())) {
			result.addProperty(SH.sourceConstraint, constraint.getParameterValue());
		}
		FailureLog.get().logFailure("Could not execute JavaScript function \"" + functionName + "\": " + ex);
	}
	finally {
		dataJSGraph.close();
		shapesJSGraph.close();
		jsEngine.put(SHACL, oldSHACL);
	}
}
 
Example #23
Source Project: shacl   Author: TopQuadrant   File: JSConstraintExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void addBindings(Constraint constraint, QuerySolutionMap bindings) {
	// Do nothing
}
 
Example #24
Source Project: shacl   Author: TopQuadrant   File: JSConstraintExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Collection<RDFNode> getValueNodes(ValidationEngine validationEngine, Constraint constraint, QuerySolutionMap bindings, RDFNode focusNode) {
	return validationEngine.getValueNodes(constraint, focusNode);
}
 
Example #25
Source Project: shacl   Author: TopQuadrant   File: JSComponentExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void addBindings(Constraint constraint, QuerySolutionMap bindings) {
	constraint.addBindings(bindings);
}
 
Example #26
Source Project: incubator-taverna-language   Author: apache   File: CombineManifest.java    License: Apache License 2.0 4 votes vote down vote up
private static String nameForAgent(Resource agentResource) {
	logger.fine("Finding name of " + agentResource);
	String queryStr = sparqlPrefixes
			+ "SELECT ?name WHERE { \n"
			+ "		{ ?agent foaf:name ?name } \n"
			+ "	UNION  \n"
			+ "		{ ?agent vcard:fn ?name } \n"
			+ "	UNION  \n"
			+ "		{ ?agent vcard:FN ?name } \n"
			+ // legacy
			"	UNION  \n"
			+ "		{ ?agent rdfs:label ?name } \n"
			+ " UNION  \n"
			+ "     { \n"
			+ "         { ?agent vcard:n ?n } UNION { ?agent vcard:hasName ?n } \n"
			+ "         ?n vcard:family-name ?family ; \n"
			+ "            vcard:given-name ?given . \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + " UNION \n" + "     { "
			+ "         ?agent foaf:givenName ?given ; \n"
			+ "                foaf:familyName ?family \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + " UNION \n" + "     { "
			+ "         ?agent foaf:firstName ?given ; \n"
			+ "                foaf:surname ?family \n"
			+ "          BIND(CONCAT(?given, \" \", ?family) AS ?name) \n"
			+ "     } \n" + "	}  \n";
	logger.finer(QueryFactory.create(queryStr).toString());
	QueryExecution qexec = QueryExecutionFactory.create(queryStr,
			agentResource.getModel());
	QuerySolutionMap binding = new QuerySolutionMap();
	binding.add("agent", agentResource);
	qexec.setInitialBinding(binding);
	ResultSet select = qexec.execSelect();
	if (select.hasNext()) {
		String name = select.next().getLiteral("name").getString();
		logger.fine(name);
		return name;
	}
	logger.fine("(null)");
	return null;
}
 
Example #27
Source Project: Server.Java   Author: LinkedDataFragments   File: JenaTDBBasedRequestProcessorForTPFs.java    License: MIT License 4 votes vote down vote up
/**
 *
 * @param subject
 * @param predicate
 * @param object
 * @param offset
 * @param limit
 * @return
 */
@Override
protected ILinkedDataFragment createFragment(
           final ITriplePatternElement<RDFNode,String,String> subject,
           final ITriplePatternElement<RDFNode,String,String> predicate,
           final ITriplePatternElement<RDFNode,String,String> object,
           final long offset,
           final long limit )
{
    // FIXME: The following algorithm is incorrect for cases in which
    //        the requested triple pattern contains a specific variable
    //        multiple times;
    //        e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn)
    // see https://github.com/LinkedDataFragments/Server.Java/issues/24

    Model model;
    if (defaultGraph == null) {
        model = tdb.getDefaultModel();
    } else {
        model = tdb.getNamedModel(defaultGraph);
    }

    QuerySolutionMap map = new QuerySolutionMap();
    if ( ! subject.isVariable() ) {
        map.add("s", subject.asConstantTerm());
    }
    if ( ! predicate.isVariable() ) {
        map.add("p", predicate.asConstantTerm());
    }
    if ( ! object.isVariable() ) {
        map.add("o", object.asConstantTerm());
    }

    query.setOffset(offset);
    query.setLimit(limit);

    Model triples = ModelFactory.createDefaultModel();

    try (QueryExecution qexec = QueryExecutionFactory.create(query, model, map)) {
        qexec.execConstruct(triples);
    }

    if (triples.isEmpty()) {
        return createEmptyTriplePatternFragment();
    }

    // Try to get an estimate
    long size = triples.size();
    long estimate = -1;

    try (QueryExecution qexec = QueryExecutionFactory.create(countQuery, model, map)) {
        ResultSet results = qexec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.nextSolution() ;
            Literal literal = soln.getLiteral("count");
            estimate = literal.getLong();
        }
    }

    /*GraphStatisticsHandler stats = model.getGraph().getStatisticsHandler();
    if (stats != null) {
        Node s = (subject != null) ? subject.asNode() : null;
        Node p = (predicate != null) ? predicate.asNode() : null;
        Node o = (object != null) ? object.asNode() : null;
        estimate = stats.getStatistic(s, p, o);
    }*/

    // No estimate or incorrect
    if (estimate < offset + size) {
        estimate = (size == limit) ? offset + size + 1 : offset + size;
    }

    // create the fragment
    final boolean isLastPage = ( estimate < offset + limit );
    return createTriplePatternFragment( triples, estimate, isLastPage );
}
 
Example #28
Source Project: Server.Java   Author: LinkedDataFragments   File: SparqlBasedRequestProcessorForTPFs.java    License: MIT License 4 votes vote down vote up
/**
 *
 * @param subject
 * @param predicate
 * @param object
 * @param offset
 * @param limit
 * @return
 */
@Override
protected ILinkedDataFragment createFragment(
           final ITriplePatternElement<RDFNode,String,String> subject,
           final ITriplePatternElement<RDFNode,String,String> predicate,
           final ITriplePatternElement<RDFNode,String,String> object,
           final long offset,
           final long limit )
{
    // FIXME: The following algorithm is incorrect for cases in which
    //        the requested triple pattern contains a specific variable
    //        multiple times;
    //        e.g., (?x foaf:knows ?x ) or (_:bn foaf:knows _:bn)
    // see https://github.com/LinkedDataFragments/Server.Java/issues/24

    QuerySolutionMap map = new QuerySolutionMap();
    if ( ! subject.isVariable() ) {
        map.add("s", subject.asConstantTerm());
    }
    if ( ! predicate.isVariable() ) {
        map.add("p", predicate.asConstantTerm());
    }
    if ( ! object.isVariable() ) {
        map.add("o", object.asConstantTerm());
    }

    query.setOffset(offset);
    query.setLimit(limit);

    Model triples = ModelFactory.createDefaultModel();

    // Build the SPARQL-endpoint
    URIBuilder uriBuilder = new URIBuilder(endpointURI);
    addCredentials(uriBuilder);

    final String endpoint;
    try {
        endpoint = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    ParameterizedSparqlString queryWithParams = new ParameterizedSparqlString(query.serialize(), map);

    try (QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, queryWithParams.asQuery())) {
        qexec.execConstruct(triples);
    }

    if (triples.isEmpty()) {
        return createEmptyTriplePatternFragment();
    }

    // Try to get an estimate
    long size = triples.size();
    long estimate = -1;

    ParameterizedSparqlString countQueryWithParams = new ParameterizedSparqlString(countQuery.serialize(), map);

    try (QueryExecution qexec = QueryExecutionFactory.createServiceRequest(endpoint, countQueryWithParams.asQuery())) {
        ResultSet results = qexec.execSelect();
        if (results.hasNext()) {
            QuerySolution soln = results.nextSolution() ;
            Literal literal = soln.getLiteral("count");
            estimate = literal.getLong();
        }
    }

    /*GraphStatisticsHandler stats = model.getGraph().getStatisticsHandler();
    if (stats != null) {
        Node s = (subject != null) ? subject.asNode() : null;
        Node p = (predicate != null) ? predicate.asNode() : null;
        Node o = (object != null) ? object.asNode() : null;
        estimate = stats.getStatistic(s, p, o);
    }*/

    // No estimate or incorrect
    if (estimate < offset + size) {
        estimate = (size == limit) ? offset + size + 1 : offset + size;
    }

    // create the fragment
    final boolean isLastPage = ( estimate < offset + limit );
    return createTriplePatternFragment( triples, estimate, isLastPage );
}
 
Example #29
Source Project: shacl   Author: TopQuadrant   File: Templates.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Takes an instance of dash:SPARQLSelectTemplate and parameter bindings and returns a QueryExecution object for the
 * sh:select query in the template using the given parameter bindings.
 * @param template  the template defining the sh:select query to run
 * @param bindings  the initial bindings for the SELECT query
 * @param dataset  the Dataset to query over
 * @return a QueryExecution
 */
public static QueryExecution select(Resource template, QuerySolutionMap bindings, Dataset dataset) {
	String queryString = JenaUtil.getStringProperty(template, SH.select);
	Query arqQuery = ARQFactory.get().createQuery(SPARQLSubstitutions.withPrefixes(queryString, template));
	return ARQFactory.get().createQueryExecution(arqQuery, dataset, bindings);
}
 
Example #30
Source Project: shacl   Author: TopQuadrant   File: AbstractSPARQLExecutor.java    License: Apache License 2.0 votes vote down vote up
protected abstract void addBindings(Constraint constraint, QuerySolutionMap bindings);