Search in sources :

Example 1 with NoURIException

use of utility.NoURIException in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalizeValueExprHelper.

/**
 * A helper function to check if a Var is an actual variable.
 *
 * @param var The Var to check.
 */
/*
  private void checkForVariable(Var var)
  {
    if (var != null) {
      if (!var.isConstant()) {
        this.simpleOrComplex = QueryHandler.Complexity.COMPLEX;
      }
    }
  }
  */
/**
 * A helper function to find the fitting replacement value for wikidata uri normalization.
 *
 * @param valueExpr      The ValueExpr to be normalized.
 * @param valueConstants The list of already found names.
 * @return The normalized name (if applicable)
 */
private ValueExpr normalizeValueExprHelper(ValueExpr valueExpr, Map<String, Integer> valueConstants) {
    String uri;
    try {
        uri = getURI(valueExpr);
    } catch (NoURIException e) {
        return valueExpr;
    }
    if (!valueConstants.containsKey(uri)) {
        valueConstants.put(uri, valueConstants.size());
    }
    try {
        uri = normalizedURI(uri, valueConstants);
    } catch (NoURIException e) {
        return valueExpr;
    }
    ((ValueConstant) valueExpr).setValue(new URIImpl(uri));
    return valueExpr;
}
Also used : NoURIException(utility.NoURIException) URIImpl(org.openrdf.model.impl.URIImpl)

Example 2 with NoURIException

use of utility.NoURIException in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalize.

/**
 * Normalizes a given query by:
 * - replacing all wikidata uris at subject and object positions with sub1, sub2 ... (obj1, obj2 ...).
 *
 * @param queryToNormalize the query to be normalized
 * @return the normalized query
 * @throws MalformedQueryException If the query was malformed (would be a bug since the input was a parsed query)
 * @throws VisitorException        If there is an error during normalization
 */
private ParsedQuery normalize(ParsedQuery queryToNormalize) throws MalformedQueryException, VisitorException {
    ParsedQuery normalizedQuery = new StandardizingSPARQLParser().parseNormalizeQuery(queryToNormalize.getSourceString(), BASE_URI);
    final Map<String, Integer> valueConstants = new HashMap<>();
    final Set<String> subjectsAndObjects = new HashSet<String>();
    final Set<String> predicates = new HashSet<String>();
    final Set<String> predicateVariables = new HashSet<String>();
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            Var predicate = statementPattern.getPredicateVar();
            if (!predicate.isConstant() && !predicate.isAnonymous()) {
                predicateVariables.add(predicate.getName());
            }
            meetNode(statementPattern);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(ExtensionElem extensionElem) throws VisitorException {
            if (!predicateVariables.contains(extensionElem.getName())) {
                extensionElem.setExpr(normalizeValueExprHelper(extensionElem.getExpr(), valueConstants));
            }
            meetNode(extensionElem);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(BindingSetAssignment bindingSetAssignment) throws VisitorException {
            List<BindingSet> bindingSets = new ArrayList<BindingSet>();
            for (BindingSet bindingSet : bindingSetAssignment.getBindingSets()) {
                List<String> names = new ArrayList<String>();
                List<Value> values = new ArrayList<Value>();
                for (Binding binding : bindingSet) {
                    String name = binding.getName();
                    if (!predicateVariables.contains(name)) {
                        names.add(name);
                        values.add(normalizeValueHelper(binding.getValue(), valueConstants));
                    } else {
                        names.add(name);
                        values.add(binding.getValue());
                    }
                }
                bindingSets.add(new ListBindingSet(names, values));
            }
            bindingSetAssignment.setBindingSets(bindingSets);
            meetNode(bindingSetAssignment);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            statementPattern.setSubjectVar(normalizeSubjectsAndObjectsHelper(statementPattern.getSubjectVar(), valueConstants, subjectsAndObjects));
            statementPattern.setObjectVar(normalizeSubjectsAndObjectsHelper(statementPattern.getObjectVar(), valueConstants, subjectsAndObjects));
            try {
                String uri = getURI(statementPattern.getPredicateVar());
                predicates.add(uri);
            } catch (NoURIException e) {
            // NoURIException is used to notify us that there is no URI in this predicate, so we just don't add it.
            }
            // checkForVariable(statementPattern.getPredicateVar());
            meetNode(statementPattern);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(ArbitraryLengthPath arbitraryLengthPath) throws VisitorException {
            arbitraryLengthPath.setSubjectVar(normalizeSubjectsAndObjectsHelper(arbitraryLengthPath.getSubjectVar(), valueConstants, subjectsAndObjects));
            arbitraryLengthPath.setObjectVar(normalizeSubjectsAndObjectsHelper(arbitraryLengthPath.getObjectVar(), valueConstants, subjectsAndObjects));
            meetNode(arbitraryLengthPath);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(Compare compare) throws VisitorException {
            compare.setLeftArg(normalizeValueExprHelper(compare.getLeftArg(), valueConstants));
            compare.setRightArg(normalizeValueExprHelper(compare.getRightArg(), valueConstants));
            meetBinaryValueOperator(compare);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(IsLiteral isLiteral) throws VisitorException {
            isLiteral.setArg(normalizeValueExprHelper(isLiteral.getArg(), valueConstants));
            meetUnaryValueOperator(isLiteral);
        }
    });
    normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() {

        @Override
        public void meet(StatementPattern statementPattern) throws VisitorException {
            statementPattern.setSubjectVar(normalizeNonConstAnonymousHelper(statementPattern.getSubjectVar(), valueConstants));
            statementPattern.setObjectVar(normalizeNonConstAnonymousHelper(statementPattern.getObjectVar(), valueConstants));
            meetNode(statementPattern);
        }
    });
    this.setqIDs(subjectsAndObjects);
    this.setpIDs(predicates);
    return normalizedQuery;
}
Also used : ParsedQuery(org.openrdf.query.parser.ParsedQuery) NoURIException(utility.NoURIException) Binding(org.openrdf.query.Binding) BindingSet(org.openrdf.query.BindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) ListBindingSet(org.openrdf.query.impl.ListBindingSet) StandardizingSPARQLParser(openrdffork.StandardizingSPARQLParser) Value(org.openrdf.model.Value)

Example 3 with NoURIException

use of utility.NoURIException in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalizedURI.

/**
 * @param uri        The URI to be normalized
 * @param foundNames The list of already found entities.
 * @return The normalized string based on the already found entities.
 * @throws NoURIException If the supplied string was not a URI.
 */
private String normalizedURI(String uri, Map<String, Integer> foundNames) throws NoURIException {
    String lastIndexOf;
    if (uri.contains("/")) {
        lastIndexOf = "/";
    } else if (uri.contains(":")) {
        lastIndexOf = ":";
    } else {
        logger.error("Variable with uri " + uri + " could not be normalized because the urn formatting is not recognized.\n" + "Query was: " + this.getQueryStringWithoutPrefixes());
        throw new NoURIException();
    }
    String normalizedURI = uri.substring(0, uri.lastIndexOf(lastIndexOf)) + lastIndexOf + "QNumber" + foundNames.get(uri);
    return normalizedURI;
}
Also used : NoURIException(utility.NoURIException)

Example 4 with NoURIException

use of utility.NoURIException in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalizeSubjectsAndObjectsHelper.

/**
 * A helper function to find the fitting replacement value for wikidata uri normalization.
 *
 * @param var                The variable to be normalized
 * @param foundNames         The list of already found names
 * @param subjectsAndObjects The set to save all found subjects and objects.
 * @return the normalized name (if applicable)
 */
private Var normalizeSubjectsAndObjectsHelper(Var var, Map<String, Integer> foundNames, Set<String> subjectsAndObjects) {
    String uri;
    try {
        uri = getURI(var);
    } catch (NoURIException e) {
        return var;
    }
    if (!foundNames.containsKey(uri)) {
        foundNames.put(uri, foundNames.size() + 1);
        subjectsAndObjects.add(uri);
    }
    try {
        uri = normalizedURI(uri, foundNames);
    } catch (NoURIException e) {
        return var;
    }
    String name = normalizedVariableName(var.getName(), foundNames);
    return new Var(name, new URIImpl(uri));
}
Also used : NoURIException(utility.NoURIException) URIImpl(org.openrdf.model.impl.URIImpl)

Example 5 with NoURIException

use of utility.NoURIException in project QueryAnalysis by Wikidata.

the class OpenRDFQueryHandler method normalizedVariableName.

/**
 * @param variableName The variable name containing the URI.
 * @param foundNames The list of already found names.
 * @return the normalized name (if applicable)
 */
private String normalizedVariableName(String variableName, Map<String, Integer> foundNames) {
    Map<String, String> replacementMap = new HashMap<String, String>();
    Matcher matcher = variableNameURIs.matcher(variableName);
    while (matcher.find()) {
        String uri = matcher.group(1);
        if (!foundNames.containsKey(uri)) {
            foundNames.put(uri, foundNames.size() + 1);
        }
        try {
            replacementMap.put(uri, normalizedURI(uri, foundNames));
        } catch (NoURIException e) {
            logger.error("Found string " + uri + " in uri position but could not normalize it.", e);
        }
    }
    String result = variableName;
    for (Map.Entry<String, String> entry : replacementMap.entrySet()) {
        String toReplace = entry.getKey();
        String replacingValue = entry.getValue();
        result = result.replaceFirst(Pattern.quote(toReplace), Matcher.quoteReplacement(replacingValue));
    }
    return result;
}
Also used : Matcher(java.util.regex.Matcher) NoURIException(utility.NoURIException)

Aggregations

NoURIException (utility.NoURIException)5 URIImpl (org.openrdf.model.impl.URIImpl)2 Matcher (java.util.regex.Matcher)1 StandardizingSPARQLParser (openrdffork.StandardizingSPARQLParser)1 Value (org.openrdf.model.Value)1 Binding (org.openrdf.query.Binding)1 BindingSet (org.openrdf.query.BindingSet)1 ListBindingSet (org.openrdf.query.impl.ListBindingSet)1 ParsedQuery (org.openrdf.query.parser.ParsedQuery)1