Java Code Examples for org.apache.jena.query.QuerySolutionMap#add()

The following examples show how to use org.apache.jena.query.QuerySolutionMap#add() . 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: TestCaseWithTarget.java    From RDFUnit with 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 2
Source File: CombineManifest.java    From incubator-taverna-language with 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 3
Source File: CombineManifest.java    From incubator-taverna-language with 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 4
Source File: SPARQLTarget.java    From shacl with 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 5
Source File: TemplateCall.java    From Processor with 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 File: JSComponentExecutor.java    From shacl with 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 7
Source File: SPARQLRule.java    From shacl with 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 8
Source File: SHACLUtil.java    From shacl with 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 9
Source File: TemplateCallTest.java    From Processor with 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 10
Source File: AbstractSPARQLExpression.java    From shacl with 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 11
Source File: SHParameterizableInstanceImpl.java    From shacl with 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 12
Source File: JenaUtil.java    From shacl with 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 13
Source File: RdfDataManager.java    From rdf2neo with 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 14
Source File: RdfDataManager.java    From rdf2neo with 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 15
Source File: TextOutputStarTest.java    From RDFstarTools with 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 16
Source File: AbstractJSExecutor.java    From shacl with 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 17
Source File: AbstractSPARQLExecutor.java    From shacl with 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 18
Source File: CombineManifest.java    From incubator-taverna-language with 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 19
Source File: JenaTDBBasedRequestProcessorForTPFs.java    From Server.Java with 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 20
Source File: SparqlBasedRequestProcessorForTPFs.java    From Server.Java with 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 );
}