Java Code Examples for org.eclipse.rdf4j.query.BindingSet#getBindingNames()

The following examples show how to use org.eclipse.rdf4j.query.BindingSet#getBindingNames() . 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: SPARQLQueryStringUtil.java    From semagrow with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve a modified queryString into which all bindings of the given
 * argument are replaced.
 *
 * @param queryString
 * @param bindings
 * @return the modified queryString
 */
public static String getQueryString(String queryString, BindingSet bindings) {
    if (bindings.size() == 0) {
        return queryString;
    }

    String qry = queryString;
    int b = qry.indexOf('{');
    String select = qry.substring(0, b);
    String where = qry.substring(b);
    for (String name : bindings.getBindingNames()) {
        String replacement = getReplacement(bindings.getValue(name));
        if (replacement != null) {
            String pattern = "[\\?\\$]" + name + "(?=\\W)";
            select = select.replaceAll(pattern, "(" + Matcher.quoteReplacement(replacement) + " as ?" + name
                    + ")");

            // we use Matcher.quoteReplacement to make sure things like newlines
            // in literal values
            // are preserved
            where = where.replaceAll(pattern, Matcher.quoteReplacement(replacement));
        }
    }
    return select + where;
}
 
Example 2
Source File: FederationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(LeftJoin leftJoin,
		final BindingSet bindings) throws QueryEvaluationException {
	// Check whether optional join is "well designed" as defined in section
	// 4.2 of "Semantics and Complexity of SPARQL", 2006, Jorge PĂ©rez et al.
	Set<String> boundVars = bindings.getBindingNames();
	Set<String> leftVars = leftJoin.getLeftArg().getBindingNames();
	Set<String> optionalVars = leftJoin.getRightArg().getBindingNames();

	final Set<String> problemVars = new HashSet<>(boundVars);
	problemVars.retainAll(optionalVars);
	problemVars.removeAll(leftVars);

	CloseableIteration<BindingSet, QueryEvaluationException> result;
	if (problemVars.isEmpty()) {
		// left join is "well designed"
		result = new ParallelLeftJoinCursor(this, leftJoin, bindings);
		executor.execute((Runnable) result);
	} else {
		result = new BadlyDesignedLeftJoinIterator(this, leftJoin, bindings, problemVars);
	}
	return result;
}
 
Example 3
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Retrieve a modified queryString into which all bindings of the given argument are replaced, with the binding
 * names included in the SELECT clause.
 *
 * @param queryString
 * @param bindings
 * @return the modified queryString
 */
public static String getTupleQueryString(String queryString, BindingSet bindings) {
	if (bindings.size() == 0) {
		return queryString;
	}

	String qry = queryString;
	int b = qry.indexOf('{');
	String select = qry.substring(0, b);
	String where = qry.substring(b);
	for (String name : bindings.getBindingNames()) {
		String replacement = valueToString(bindings.getValue(name));
		if (replacement != null) {
			String pattern = "[\\?\\$]" + name + "(?=\\W)";
			select = select.replaceAll(pattern, "(" + Matcher.quoteReplacement(replacement) + " as ?" + name + ")");

			// we use Matcher.quoteReplacement to make sure things like newlines
			// in literal values
			// are preserved
			where = where.replaceAll(pattern, Matcher.quoteReplacement(replacement));
		}
	}
	return select + where;
}
 
Example 4
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Retrieve a modified queryString into which all bindings of the given argument are replaced with their value.
 *
 * @param queryString
 * @param bindings
 * @return the modified queryString
 */
public static String getGraphQueryString(String queryString, BindingSet bindings) {
	if (bindings.size() == 0) {
		return queryString;
	}

	String qry = queryString;
	for (String name : bindings.getBindingNames()) {
		String replacement = valueToString(bindings.getValue(name));
		if (replacement != null) {
			String pattern = "[\\?\\$]" + name + "(?=\\W)";
			// we use Matcher.quoteReplacement to make sure things like newlines
			// in literal values are preserved
			qry = qry.replaceAll(pattern, Matcher.quoteReplacement(replacement));
		}
	}
	return qry;
}
 
Example 5
Source File: PCJKeyToCrossProductBindingSetIterator.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * This method compute the cross product of the BindingSet passed to the PCJ
 * and the PCJ BindingSet.  It verifies that only common variables are unassured
 * variables, and if leftBs and rightBs have distinct values for a given variable,
 * this method uses the value from leftBs in the cross product BindingSet - this
 * is effectively performing a LeftJoin.
 *
 * @param leftBs - BindingSet passed to PCJ
 * @param rightBs - PCJ BindingSet
 * @return - cross product BindingSet
 */
private BindingSet takeCrossProduct(BindingSet leftBs, BindingSet rightBs) {
	if (bindingSetsIntersect(leftBs, rightBs)) {
		return EMPTY_BINDINGSET;
	}
	QueryBindingSet bs = new QueryBindingSet(leftBs);

	//only add Bindings corresponding to variables that have no value
	//assigned.  This takes into account case where leftBs and rightBs
	//share a common, unAssuredVariable.  In this case, use value corresponding
	//to leftBs, which is effectively performing a LeftJoin.
	for(String s: rightBs.getBindingNames()) {
		if(bs.getValue(s) == null) {
			bs.addBinding(s, rightBs.getValue(s));
		}
	}
	return bs;
}
 
Example 6
Source File: PCJKeyToJoinBindingSetIterator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param key
 *            - Accumulo key obtained from scan
 * @return - Entry<String,BindingSet> satisfying the constant constraints
 * @throws BindingSetConversionException
 */
private Map.Entry<String, BindingSet> getBindingSetEntryAndMatchConstants(
		Key key) throws BindingSetConversionException {
	byte[] row = key.getRow().getBytes();
	String[] varOrder = key.getColumnFamily().toString()
			.split(ExternalTupleSet.VAR_ORDER_DELIM);

	BindingSet bindingSet = converter.convert(row, new VariableOrder(
			varOrder));

	QueryBindingSet bs = new QueryBindingSet();
	for (String var : bindingSet.getBindingNames()) {
		String mappedVar = pcjVarMap.get(var);
		if (VarNameUtils.isConstant(mappedVar)
				&& constantConstraints.containsKey(mappedVar)
				&& !constantConstraints.get(mappedVar).equals(
						bindingSet.getValue(var))) {
			return EMPTY_ENTRY;
		} else {
			bs.addBinding(mappedVar, bindingSet.getValue(var));
		}
	}

	String orderedValueString = bindingSet.getValue(varOrder[0]).toString();
	for (int i = 1; i < maxPrefixLen; i++) {
		Value value = bindingSet.getValue(varOrder[i]);
		if (value != null) {
			orderedValueString = orderedValueString
					+ ExternalTupleSet.VALUE_DELIM + value.toString();
		}
	}

	return new RdfCloudTripleStoreUtils.CustomEntry<String, BindingSet>(
			orderedValueString, bs);
}
 
Example 7
Source File: StarQuery.java    From rya with Apache License 2.0 5 votes vote down vote up
public static StarQuery getConstrainedStarQuery(final StarQuery query, final BindingSet bs) {

        if(bs.size() == 0) {
            return query;
        }

        final Set<String> bindingNames = bs.getBindingNames();
        final Set<String> unCommonVarNames = query.getUnCommonVars();
        final Set<String> intersectVar = Sets.intersection(bindingNames, unCommonVarNames);


        if (!query.commonVarConstant()) {

            final Value v = bs.getValue(query.getCommonVarName());

            if (v != null) {
                query.commonVar.setValue(v);
            }
        }

        for(final String s: intersectVar) {
            try {
                query.nodeColumnCond[query.varPos.get(s)] = query.setValue(query.nodeColumnCond[query.varPos.get(s)], bs.getValue(s));
            } catch (final RyaTypeResolverException e) {
                e.printStackTrace();
            }
        }

        return query;
    }
 
Example 8
Source File: PCJKeyToCrossProductBindingSetIterator.java    From rya with Apache License 2.0 5 votes vote down vote up
private boolean bindingSetsIntersect(BindingSet bs1, BindingSet bs2) {

		for(String s: bs1.getBindingNames()) {
			if(bs2.getValue(s) != null && !unAssuredVariables.contains(s)) {
				return true;
			}
		}
		return false;
	}
 
Example 9
Source File: PCJKeyToCrossProductBindingSetIterator.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param key
 *            - Accumulo key obtained from scan
 * @return - BindingSet satisfying any specified constant constraints
 * @throws BindingSetConversionException
 * @throws QueryEvaluationException
 */
private BindingSet getBindingSet(Key key)
		throws BindingSetConversionException, QueryEvaluationException {
	byte[] row = key.getRow().getBytes();
	String[] varOrder = key.getColumnFamily().toString()
			.split(ExternalTupleSet.VAR_ORDER_DELIM);

	BindingSet bindingSet = converter.convert(row, new VariableOrder(
			varOrder));

	QueryBindingSet bs = new QueryBindingSet();
	for (String var : bindingSet.getBindingNames()) {
		String mappedVar = null;
		if(pcjVarMap.containsKey(var)) {
			mappedVar = pcjVarMap.get(var);
		} else {
			throw new QueryEvaluationException("PCJ Variable has no mapping to query variable.");
		}
		if (constantConstraintsExist) {
			if (VarNameUtils.isConstant(mappedVar)
					&& constantConstraints.containsKey(mappedVar)
					&& !constantConstraints.get(mappedVar).equals(
							bindingSet.getValue(var))) {
				return EMPTY_BINDINGSET;
			}
		}

		if (!VarNameUtils.isConstant(mappedVar)) {
				bs.addBinding(mappedVar, bindingSet.getValue(var));
		}
	}
	return bs;
}
 
Example 10
Source File: BindingSetHashJoinIterator.java    From rya with Apache License 2.0 5 votes vote down vote up
private BindingSet removeConstants(BindingSet bs) {
	QueryBindingSet bSet = new QueryBindingSet();
	for (String s : bs.getBindingNames()) {
		if (!VarNameUtils.isConstant(s)) {
			bSet.addBinding(bs.getBinding(s));
		}
	}
	return bSet;
}
 
Example 11
Source File: SPARQLComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected static final void printBindingSet(BindingSet bs, StringBuilder appendable) {
	List<String> names = new ArrayList<>(bs.getBindingNames());
	Collections.sort(names);

	for (String name : names) {
		if (bs.hasBinding(name)) {
			appendable.append(bs.getBinding(name));
			appendable.append(' ');
		}
	}
	appendable.append("\n");
}
 
Example 12
Source File: CbSailProducer.java    From rya with Apache License 2.0 5 votes vote down vote up
protected Object performSelect(final String query, final String auth, final Boolean infer) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException {
    final TupleQuery tupleQuery = connection.prepareTupleQuery(
            QueryLanguage.SPARQL, query);
    if (auth != null && auth.length() > 0) {
        tupleQuery.setBinding(CONF_QUERY_AUTH, VALUE_FACTORY.createLiteral(auth));
    }
    if (infer != null) {
        tupleQuery.setBinding(CONF_INFER, VALUE_FACTORY.createLiteral(infer));
    }
    if (CbSailEndpoint.CbSailOutput.BINARY.equals(queryOutput)) {
        final List listOutput = new ArrayList();
        final AbstractTupleQueryResultHandler handler = new AbstractTupleQueryResultHandler() {
            @Override
            public void handleSolution(final BindingSet bindingSet) throws TupleQueryResultHandlerException {
                final Map<String, String> map = new HashMap<String, String>();
                for (final String s : bindingSet.getBindingNames()) {
                    map.put(s, bindingSet.getBinding(s).getValue().stringValue());
                }
                listOutput.add(map);
            }
        };
        tupleQuery.evaluate(handler);
        return listOutput;
    } else if (CbSailEndpoint.CbSailOutput.XML.equals(queryOutput)) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final SPARQLResultsXMLWriter sparqlWriter = new SPARQLResultsXMLWriter(baos);
        tupleQuery.evaluate(sparqlWriter);
        return new String(baos.toByteArray(), StandardCharsets.UTF_8);
    } else {
        throw new IllegalArgumentException("Query Output[" + queryOutput + "] is not recognized");
    }
}
 
Example 13
Source File: FedXBaseTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Add the {@link BindingSet} to the result.
 *
 * @param b
 * @return
 * @throws IllegalArgumentException if the provided binding names is not a subset of the defined result binding
 *                                  names
 */
public SimpleTupleQueryResultBuilder add(BindingSet b) throws IllegalArgumentException {

	// check if the binding names are a subset of defined binding names
	if (!bindingNames.containsAll(b.getBindingNames())) {
		throw new IllegalArgumentException(
				"Provided binding set does must be a subset of defined binding names: " + bindingNames
						+ ". Was: " + b.getBindingNames());
	}
	this.bindings.add(b);
	return this;
}
 
Example 14
Source File: SPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected final void printBindingSet(BindingSet bs, StringBuilder appendable) {
	List<String> names = new ArrayList<>(bs.getBindingNames());
	Collections.sort(names);

	for (String name : names) {
		if (bs.hasBinding(name)) {
			appendable.append(bs.getBinding(name));
			appendable.append(' ');
		}
	}
	appendable.append("\n");
}
 
Example 15
Source File: HashJoinIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected BindingSet getNextElement() throws QueryEvaluationException {
	Map<BindingSetHashKey, List<BindingSet>> nextHashTable = hashTable;
	if (nextHashTable == null) {
		synchronized (this) {
			nextHashTable = hashTable;
			if (nextHashTable == null) {
				nextHashTable = hashTable = setupHashTable();
			}
		}
	}
	Iterator<BindingSet> nextHashTableValues = hashTableValues;

	while (currentScanElem == null) {
		if (scanList.hasNext()) {
			currentScanElem = nextFromCache(scanList);
		} else {
			disposeCache(scanList); // exhausted so can free

			if (restIter.hasNext()) {
				currentScanElem = restIter.next();
			} else {
				// no more elements available
				return null;
			}
		}

		if (currentScanElem != null) {
			if (currentScanElem instanceof EmptyBindingSet) {
				// the empty bindingset should be merged with all bindingset in the
				// hash table
				Collection<List<BindingSet>> values = nextHashTable.values();
				boolean empty = values.isEmpty() || values.size() == 1 && values.contains(null);
				nextHashTableValues = hashTableValues = empty ? new EmptyIterator<>() : new UnionIterator<>(values);
				if (!nextHashTableValues.hasNext()) {
					currentScanElem = null;
					closeHashValue(nextHashTableValues);
					nextHashTableValues = hashTableValues = null;
				}
			} else {
				BindingSetHashKey key = BindingSetHashKey.create(joinAttributes, currentScanElem);
				List<BindingSet> hashValue = nextHashTable.get(key);
				if (hashValue != null && !hashValue.isEmpty()) {
					nextHashTableValues = hashTableValues = hashValue.iterator();
				} else if (leftJoin) {
					nextHashTableValues = hashTableValues = Collections.singletonList(EmptyBindingSet.getInstance())
							.iterator();
				} else {
					currentScanElem = null;
					closeHashValue(nextHashTableValues);
					nextHashTableValues = hashTableValues = null;
				}
			}
		}
	}

	if (nextHashTableValues != null) {
		BindingSet nextHashTableValue = nextHashTableValues.next();

		QueryBindingSet result = new QueryBindingSet(currentScanElem);

		for (String name : nextHashTableValue.getBindingNames()) {
			if (!result.hasBinding(name)) {
				Value v = nextHashTableValue.getValue(name);
				if (v != null) {
					result.addBinding(name, v);
				}
			}
		}

		if (!nextHashTableValues.hasNext()) {
			// we've exhausted the current scanlist entry
			currentScanElem = null;
			closeHashValue(nextHashTableValues);
			nextHashTableValues = hashTableValues = null;
		}
		return result;
	}

	return EmptyBindingSet.getInstance();
}
 
Example 16
Source File: StarQuery.java    From rya with Apache License 2.0 4 votes vote down vote up
public static Set<String> getCommonVars(final StarQuery query, final BindingSet bs) {

        final Set<String> starQueryVarNames = Sets.newHashSet();

        if(bs == null || bs.size() == 0) {
            return Sets.newHashSet();
        }

        final Set<String> bindingNames = bs.getBindingNames();
        starQueryVarNames.addAll(query.getUnCommonVars());
        if(!query.commonVarConstant()) {
            starQueryVarNames.add(query.getCommonVarName());
        }

        return Sets.intersection(bindingNames, starQueryVarNames);


    }
 
Example 17
Source File: BindingSetSerDe.java    From rya with Apache License 2.0 4 votes vote down vote up
private VariableOrder getVarOrder(final BindingSet bs) {
    return new VariableOrder(bs.getBindingNames());
}