Search in sources :

Example 11 with Constraint

use of org.apache.stanbol.entityhub.servicesapi.query.Constraint in project stanbol by apache.

the class FieldQueryReader method parseTextConstraint.

/**
     * @param jConstraint
     * @return
     * @throws JSONException
     */
private static Constraint parseTextConstraint(JSONObject jConstraint) throws JSONException {
    final TextConstraint constraint;
    boolean caseSensitive = jConstraint.optBoolean("caseSensitive", false);
    //parse patternType
    PatternType patternType;
    String jPatternType = jConstraint.optString("patternType", null);
    if (jPatternType == null) {
        patternType = PatternType.none;
    } else {
        try {
            patternType = PatternType.valueOf(jPatternType);
        } catch (IllegalArgumentException e) {
            log.warn("Encountered unknown patternType for TextConstraint!", e);
            patternType = PatternType.none;
            StringBuilder message = new StringBuilder();
            message.append("Illegal value for field 'patternType'.\n");
            message.append("Supported values are: ");
            message.append(Arrays.toString(PatternType.values()));
            message.append('\n');
            message.append("Parsed Constraint: \n");
            message.append(jConstraint.toString(4));
            throw new IllegalArgumentException(message.toString());
        }
    }
    //parse languages
    Collection<String> languages;
    //support both "languages" and "language"
    String languageKey = null;
    if (jConstraint.has("language")) {
        languageKey = "language";
    } else if (jConstraint.has("languages")) {
        log.warn("The key \"languages\" is deprecated. Use \"language\" instead.");
        languageKey = "languages";
    }
    if (languageKey != null) {
        JSONArray jLanguages = jConstraint.optJSONArray(languageKey);
        if (jLanguages != null && jLanguages.length() > 0) {
            languages = new ArrayList<String>(jLanguages.length());
            for (int i = 0; i < jLanguages.length(); i++) {
                String lang = jLanguages.getString(i);
                if (lang != null && !lang.isEmpty()) {
                    languages.add(lang);
                } else if (!languages.contains(null)) {
                    languages.add(null);
                }
            }
            if (languages.isEmpty()) {
                //if no one was successfully added set the list back to null
                languages = null;
            }
        } else {
            String language = jConstraint.getString(languageKey);
            if (language.isEmpty()) {
                languages = null;
            } else {
                //add the single language
                languages = Collections.singletonList(language);
            }
        }
    } else {
        languages = null;
    }
    //parse text and create constraint
    if (jConstraint.has("text") && !jConstraint.isNull("text")) {
        List<String> textConstraints;
        JSONArray jTextConstraints = jConstraint.optJSONArray("text");
        if (jTextConstraints != null) {
            textConstraints = new ArrayList<String>(jTextConstraints.length());
            for (int i = 0; i < jTextConstraints.length(); i++) {
                String text = jTextConstraints.getString(i);
                if (text != null && !text.isEmpty()) {
                    textConstraints.add(jTextConstraints.getString(i));
                }
            }
        } else {
            String text = jConstraint.getString("text");
            if (text == null || text.isEmpty()) {
                textConstraints = Collections.emptyList();
            } else {
                textConstraints = Collections.singletonList(text);
            }
        }
        if (textConstraints.isEmpty()) {
            StringBuilder message = new StringBuilder();
            message.append("Parsed TextConstraint doese not define a valid (none empty) value for the 'text' property !\n");
            message.append("Parsed Constraint: \n");
            message.append(jConstraint.toString(4));
            throw new IllegalArgumentException(message.toString());
        }
        constraint = new TextConstraint(textConstraints, patternType, caseSensitive, languages == null ? null : languages.toArray(new String[languages.size()]));
        //finally parse the optional termProximity
        if (jConstraint.has("proximityRanking")) {
            constraint.setProximityRanking(jConstraint.optBoolean("proximityRanking", false));
        }
    } else {
        StringBuilder message = new StringBuilder();
        message.append("Parsed TextConstraint doese not define the required field 'text'!\n");
        message.append("Parsed Constraint: \n");
        message.append(jConstraint.toString(4));
        throw new IllegalArgumentException(message.toString());
    }
    return constraint;
}
Also used : PatternType(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint.PatternType) JSONArray(org.codehaus.jettison.json.JSONArray) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ValueConstraint(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) RangeConstraint(org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)

Example 12 with Constraint

use of org.apache.stanbol.entityhub.servicesapi.query.Constraint in project stanbol by apache.

the class FieldQueryReader method parseReferenceConstraint.

/**
     * @param jConstraint
     * @return
     * @throws JSONException
     */
private static Constraint parseReferenceConstraint(JSONObject jConstraint, NamespacePrefixService nsPrefixService) throws JSONException {
    final List<String> refList;
    if (jConstraint.has("value") && !jConstraint.isNull("value")) {
        Object value = jConstraint.get("value");
        if (value instanceof JSONArray) {
            refList = new ArrayList<String>(((JSONArray) value).length());
            for (int i = 0; i < ((JSONArray) value).length(); i++) {
                String field = ((JSONArray) value).getString(i);
                field = field != null ? nsPrefixService.getFullName(field) : null;
                if (field != null && !field.isEmpty()) {
                    refList.add(field);
                }
            }
        } else if (value instanceof JSONObject) {
            log.warn("Parsed ValueConstraint does define illegal values (values={})!", value);
            StringBuilder message = new StringBuilder();
            message.append("Parsed ValueConstraint does define illegal value for field 'value'" + "(value MUST NOT be an JSON object. Only values and JSONArray to parse" + "multiple values are allowed)!\n");
            message.append("Parsed Constraint: \n");
            message.append(jConstraint.toString(4));
            throw new IllegalArgumentException(message.toString());
        } else {
            String field = jConstraint.getString("value");
            field = field != null ? nsPrefixService.getFullName(field) : null;
            if (field != null) {
                refList = Collections.singletonList(field);
            } else {
                refList = Collections.emptyList();
            }
        }
        if (refList.isEmpty()) {
            log.warn("Parsed ReferenceConstraint does not define a single valid \"value\"!");
            StringBuilder message = new StringBuilder();
            message.append("Parsed ReferenceConstraint does not define a single valid 'value'!\n");
            message.append("This means values where only null, empty string or '{prefix}:{localname}' values with unknown {prefix}\n");
            message.append("Parsed Constraint: \n");
            message.append(jConstraint.toString(4));
            throw new IllegalArgumentException(message.toString());
        }
        MODE mode = parseConstraintValueMode(jConstraint);
        return new ReferenceConstraint(refList, mode);
    } else {
        log.warn("Parsed ReferenceConstraint does not define the required field \"value\"!");
        StringBuilder message = new StringBuilder();
        message.append("Parsed ReferenceConstraint does not define the required field 'value'!\n");
        message.append("Parsed Constraint: \n");
        message.append(jConstraint.toString(4));
        throw new IllegalArgumentException(message.toString());
    }
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) MODE(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint.MODE) JSONArray(org.codehaus.jettison.json.JSONArray) JSONObject(org.codehaus.jettison.json.JSONObject) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) ValueConstraint(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) RangeConstraint(org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)

Example 13 with Constraint

use of org.apache.stanbol.entityhub.servicesapi.query.Constraint in project stanbol by apache.

the class FieldQueryReader method fromJSON.

/**
     * 
     * @param queryFactory
     * @param jsonQueryString
     * @param acceptedMediaType used to add the accept header to Error responses
     * @return
     * @throws JSONException
     * @throws WebApplicationException
     */
public static FieldQuery fromJSON(String jsonQueryString, MediaType acceptedMediaType, NamespacePrefixService nsPrefixService) throws JSONException, WebApplicationException {
    if (jsonQueryString == null) {
        throw new IllegalArgumentException("The parsed JSON object MUST NOT be NULL!");
    }
    JSONObject jQuery = new JSONObject(jsonQueryString);
    FieldQuery query;
    if (jQuery.has("ldpath")) {
        //STANBOL-417: support for using LDPath as select
        LDPathFieldQueryImpl ldPathQuery = new LDPathFieldQueryImpl();
        ldPathQuery.setLDPathSelect(jQuery.getString("ldpath"));
        query = ldPathQuery;
    } else {
        query = new FieldQueryImpl();
    }
    if (!jQuery.has("constraints")) {
        StringBuilder message = new StringBuilder();
        message.append("The parsed Field Query MUST contain at least a single 'constraints'\n");
        message.append("Parsed Query:\n");
        message.append(jQuery.toString(4));
        log.warn(message.toString());
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message.toString()).header(HttpHeaders.ACCEPT, acceptedMediaType.toString()).build());
    }
    JSONArray constraints = jQuery.getJSONArray("constraints");
    //collect all parsing Errors to report a complete set of all errors
    boolean parsingError = false;
    StringBuilder parsingErrorMessages = new StringBuilder();
    parsingErrorMessages.append("Constraint parsing Errors:\n");
    for (int i = 0; i < constraints.length(); i++) {
        JSONObject jConstraint = constraints.getJSONObject(i);
        if (jConstraint.has("field")) {
            String field = jConstraint.getString("field");
            //check if there is already a constraint for that field
            if (field == null || field.isEmpty()) {
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("Each Field Query Constraint MUST define a value for 'field'\n");
                parsingErrorMessages.append("Parsed Constraint:\n");
                parsingErrorMessages.append(jConstraint.toString(4));
                parsingErrorMessages.append('\n');
                parsingError = true;
                continue;
            }
            String fieldUri = nsPrefixService.getFullName(field);
            if (fieldUri == null) {
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("The 'field' '").append(field).append("uses an unknown namespace prefix '");
                parsingErrorMessages.append(NamespaceMappingUtils.getPrefix(field)).append("'\n");
                parsingErrorMessages.append("Parsed Constraint:\n");
                parsingErrorMessages.append(jConstraint.toString(4));
                parsingErrorMessages.append('\n');
                parsingError = true;
                continue;
            } else if (query.isConstrained(fieldUri)) {
                parsingErrorMessages.append('\n');
                parsingErrorMessages.append("The parsed Query defines multiple constraints fr the field '").append(fieldUri).append("'!\n");
                parsingErrorMessages.append("FieldQuery allows only a single Constraint for a field\n");
                parsingErrorMessages.append("Parsed Constraints:\n");
                parsingErrorMessages.append(constraints.toString(4));
                parsingErrorMessages.append('\n');
                parsingError = true;
                continue;
            } else {
                try {
                    query.setConstraint(fieldUri, parseConstraint(jConstraint, nsPrefixService));
                } catch (IllegalArgumentException e) {
                    parsingErrorMessages.append('\n');
                    parsingErrorMessages.append(e.getMessage());
                    parsingErrorMessages.append('\n');
                    parsingError = true;
                    continue;
                }
            }
        } else {
            //empty field
            parsingErrorMessages.append('\n');
            parsingErrorMessages.append("Constraints MUST define a value for 'field'\n");
            parsingErrorMessages.append("Parsed Constraint:\n");
            parsingErrorMessages.append(jConstraint.toString(4));
            parsingErrorMessages.append('\n');
            parsingError = true;
            continue;
        }
    }
    if (parsingError) {
        String message = parsingErrorMessages.toString();
        log.warn(message);
        throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType.toString()).build());
    }
    //parse selected fields
    JSONArray selected = jQuery.optJSONArray("selected");
    if (selected != null) {
        for (int i = 0; i < selected.length(); i++) {
            String selectedField = selected.getString(i);
            selectedField = nsPrefixService.getFullName(selectedField);
            if (selectedField != null && !selectedField.isEmpty()) {
                query.addSelectedField(selectedField);
            }
        }
    }
    //parse limit and offset
    if (jQuery.has("limit") && !jQuery.isNull("limit")) {
        try {
            query.setLimit(jQuery.getInt("limit"));
        } catch (JSONException e) {
            parsingErrorMessages.append('\n');
            parsingErrorMessages.append("Property \"limit\" MUST BE a valid integer number!\n");
            parsingErrorMessages.append("Parsed Value:");
            parsingErrorMessages.append(jQuery.get("init"));
            parsingErrorMessages.append('\n');
            parsingError = true;
        }
    }
    if (jQuery.has("offset") && !jQuery.isNull("offset")) {
        try {
            query.setOffset(jQuery.getInt("offset"));
        } catch (JSONException e) {
            parsingErrorMessages.append('\n');
            parsingErrorMessages.append("Property \"offset\" MUST BE a valid integer number!\n");
            parsingErrorMessages.append("Parsed Value:");
            parsingErrorMessages.append(jQuery.get("init"));
            parsingErrorMessages.append('\n');
            parsingError = true;
        }
    }
    return query;
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) FieldQueryImpl(org.apache.stanbol.entityhub.core.query.FieldQueryImpl) LDPathFieldQueryImpl(org.apache.stanbol.entityhub.ldpath.query.LDPathFieldQueryImpl) JSONObject(org.codehaus.jettison.json.JSONObject) WebApplicationException(javax.ws.rs.WebApplicationException) LDPathFieldQueryImpl(org.apache.stanbol.entityhub.ldpath.query.LDPathFieldQueryImpl) JSONArray(org.codehaus.jettison.json.JSONArray) JSONException(org.codehaus.jettison.json.JSONException) ValueConstraint(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) RangeConstraint(org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)

Example 14 with Constraint

use of org.apache.stanbol.entityhub.servicesapi.query.Constraint in project stanbol by apache.

the class FieldQueryReader method parseValueConstraint.

/**
     * @param jConstraint
     * @return
     * @throws JSONException
     */
private static Constraint parseValueConstraint(JSONObject jConstraint, NamespacePrefixService nsPrefixService) throws JSONException {
    Collection<String> dataTypes = parseDatatypeProperty(jConstraint, nsPrefixService);
    final List<Object> valueList;
    if (jConstraint.has("value") && !jConstraint.isNull("value")) {
        Object value = jConstraint.get("value");
        if (value instanceof JSONArray) {
            valueList = new ArrayList<Object>(((JSONArray) value).length());
            for (int i = 0; i < ((JSONArray) value).length(); i++) {
                Object v = ((JSONArray) value).get(i);
                if (v == null || v instanceof JSONArray || v instanceof JSONObject) {
                    log.warn("Parsed ValueConstraint does define illegal values (values={})!", value);
                    StringBuilder message = new StringBuilder();
                    message.append("Parsed ValueConstraint does define illegal values for field 'value'" + "(value MUST NOT contain NULL, JSONObject nor JSONArray values)!\n");
                    message.append("Parsed Constraint: \n");
                    message.append(jConstraint.toString(4));
                    throw new IllegalArgumentException(message.toString());
                }
                valueList.add(v);
            }
        } else if (value instanceof JSONObject) {
            log.warn("Parsed ValueConstraint does define illegal values (values={})!", value);
            StringBuilder message = new StringBuilder();
            message.append("Parsed ValueConstraint does define illegal value for field 'value'" + "(value MUST NOT be an JSON object. Only values and JSONArray to parse" + "multiple values are allowed)!\n");
            message.append("Parsed Constraint: \n");
            message.append(jConstraint.toString(4));
            throw new IllegalArgumentException(message.toString());
        } else {
            valueList = Collections.singletonList(jConstraint.get("value"));
        }
    } else {
        log.warn("Parsed ValueConstraint does not define the required field \"value\"!");
        StringBuilder message = new StringBuilder();
        message.append("Parsed ValueConstraint does not define the required field 'value'!\n");
        message.append("Parsed Constraint: \n");
        message.append(jConstraint.toString(4));
        throw new IllegalArgumentException(message.toString());
    }
    MODE mode = parseConstraintValueMode(jConstraint);
    return new ValueConstraint(valueList, dataTypes, mode);
}
Also used : JSONObject(org.codehaus.jettison.json.JSONObject) MODE(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint.MODE) ValueConstraint(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint) JSONArray(org.codehaus.jettison.json.JSONArray) JSONObject(org.codehaus.jettison.json.JSONObject) ValueConstraint(org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) ReferenceConstraint(org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) RangeConstraint(org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)

Example 15 with Constraint

use of org.apache.stanbol.entityhub.servicesapi.query.Constraint in project stanbol by apache.

the class DisambiguatorEngine method query.

/*
     * Is used to query the Dbpedia with a entity as main constraint and then add string of all other entities
     * detected as similarity constraints
     */
protected QueryResultList<Entity> query(Site dbpediaSite, String savedEntityLabel, String language, String extractionContext) throws SiteException {
    FieldQuery query = dbpediaSite.getQueryFactory().createFieldQuery();
    if (savedEntityLabel != null && !savedEntityLabel.isEmpty()) {
        Constraint labelConstraint;
        if (language != null) {
            labelConstraint = new TextConstraint(savedEntityLabel, false, language, null);
        } else {
            labelConstraint = new TextConstraint(savedEntityLabel, false);
        }
        // TODO: what happens if a recommendation was not based on rdfs:label?
        query.setConstraint(RDFS_LABEL.getUnicodeString(), labelConstraint);
    } else {
        log.warn("parsed label {} was empty or NULL. Will use Similarity constraint only!", savedEntityLabel);
    }
    query.setConstraint(SpecialFieldEnum.fullText.getUri(), new SimilarityConstraint(extractionContext));
    query.setLimit(25);
    return dbpediaSite.findEntities(query);
}
Also used : FieldQuery(org.apache.stanbol.entityhub.servicesapi.query.FieldQuery) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) SimilarityConstraint(org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint) Constraint(org.apache.stanbol.entityhub.servicesapi.query.Constraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint) TextConstraint(org.apache.stanbol.entityhub.servicesapi.query.TextConstraint)

Aggregations

Constraint (org.apache.stanbol.entityhub.servicesapi.query.Constraint)15 TextConstraint (org.apache.stanbol.entityhub.servicesapi.query.TextConstraint)15 ValueConstraint (org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint)12 ReferenceConstraint (org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint)11 SimilarityConstraint (org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint)11 RangeConstraint (org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)10 JSONArray (org.codehaus.jettison.json.JSONArray)6 JSONObject (org.codehaus.jettison.json.JSONObject)5 FieldQuery (org.apache.stanbol.entityhub.servicesapi.query.FieldQuery)4 ArrayList (java.util.ArrayList)2 Entity (org.apache.stanbol.entityhub.servicesapi.model.Entity)2 FieldQueryFactory (org.apache.stanbol.entityhub.servicesapi.query.FieldQueryFactory)2 MODE (org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint.MODE)2 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Entry (java.util.Map.Entry)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 SolrQuery (org.apache.solr.client.solrj.SolrQuery)1 FieldQueryImpl (org.apache.stanbol.entityhub.core.query.FieldQueryImpl)1 LDPathFieldQueryImpl (org.apache.stanbol.entityhub.ldpath.query.LDPathFieldQueryImpl)1