Search in sources :

Example 1 with FieldQueryImpl

use of org.apache.stanbol.entityhub.core.query.FieldQueryImpl in project stanbol by apache.

the class RdfResultListTest method testRdfResultSorting.

/**
     * Providing a sorted Iteration over query results stored in an RDF
     * graph is not something trivial. Therefore this test
     */
@Test
public void testRdfResultSorting() {
    SortedMap<Double, RdfRepresentation> sorted = new TreeMap<Double, RdfRepresentation>();
    Graph resultGraph = new IndexedGraph();
    RdfValueFactory vf = new RdfValueFactory(resultGraph);
    IRI resultListNode = new IRI(RdfResourceEnum.QueryResultSet.getUri());
    IRI resultProperty = new IRI(RdfResourceEnum.queryResult.getUri());
    for (int i = 0; i < 100; i++) {
        Double rank;
        do {
            //avoid duplicate keys
            rank = Math.random();
        } while (sorted.containsKey(rank));
        RdfRepresentation r = vf.createRepresentation("urn:sortTest:rep." + i);
        //link the representation with the query result set
        resultGraph.add(new TripleImpl(resultListNode, resultProperty, r.getNode()));
        r.set(RdfResourceEnum.resultScore.getUri(), rank);
        sorted.put(rank, r);
    }
    RdfQueryResultList resultList = new RdfQueryResultList(new FieldQueryImpl(), resultGraph);
    if (log.isDebugEnabled()) {
        log.debug("---DEBUG Sorting ---");
        for (Iterator<Representation> it = resultList.iterator(); it.hasNext(); ) {
            Representation r = it.next();
            log.debug("{}: {}", r.getFirst(RdfResourceEnum.resultScore.getUri()), r.getId());
        }
    }
    log.debug("---ASSERT Sorting ---");
    for (Iterator<Representation> it = resultList.iterator(); it.hasNext(); ) {
        Representation r = it.next();
        Double lastkey = sorted.lastKey();
        Representation last = sorted.get(lastkey);
        Assert.assertEquals("score: " + r.getFirst(RdfResourceEnum.resultScore.getUri()) + " of Representation " + r.getId() + " is not as expected " + last.getFirst(RdfResourceEnum.resultScore.getUri()) + " of Representation " + last.getId() + "!", r, last);
        sorted.remove(lastkey);
    }
    Assert.assertTrue(sorted.isEmpty());
}
Also used : IRI(org.apache.clerezza.commons.rdf.IRI) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation) TreeMap(java.util.TreeMap) FieldQueryImpl(org.apache.stanbol.entityhub.core.query.FieldQueryImpl) SimpleGraph(org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph) Graph(org.apache.clerezza.commons.rdf.Graph) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) RdfRepresentation(org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation) TripleImpl(org.apache.clerezza.commons.rdf.impl.utils.TripleImpl) IndexedGraph(org.apache.stanbol.commons.indexedgraph.IndexedGraph) RdfValueFactory(org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory) Test(org.junit.Test)

Example 2 with FieldQueryImpl

use of org.apache.stanbol.entityhub.core.query.FieldQueryImpl 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)

Aggregations

FieldQueryImpl (org.apache.stanbol.entityhub.core.query.FieldQueryImpl)2 TreeMap (java.util.TreeMap)1 WebApplicationException (javax.ws.rs.WebApplicationException)1 Graph (org.apache.clerezza.commons.rdf.Graph)1 IRI (org.apache.clerezza.commons.rdf.IRI)1 TripleImpl (org.apache.clerezza.commons.rdf.impl.utils.TripleImpl)1 SimpleGraph (org.apache.clerezza.commons.rdf.impl.utils.simple.SimpleGraph)1 IndexedGraph (org.apache.stanbol.commons.indexedgraph.IndexedGraph)1 LDPathFieldQueryImpl (org.apache.stanbol.entityhub.ldpath.query.LDPathFieldQueryImpl)1 RdfRepresentation (org.apache.stanbol.entityhub.model.clerezza.RdfRepresentation)1 RdfValueFactory (org.apache.stanbol.entityhub.model.clerezza.RdfValueFactory)1 Representation (org.apache.stanbol.entityhub.servicesapi.model.Representation)1 Constraint (org.apache.stanbol.entityhub.servicesapi.query.Constraint)1 FieldQuery (org.apache.stanbol.entityhub.servicesapi.query.FieldQuery)1 RangeConstraint (org.apache.stanbol.entityhub.servicesapi.query.RangeConstraint)1 ReferenceConstraint (org.apache.stanbol.entityhub.servicesapi.query.ReferenceConstraint)1 SimilarityConstraint (org.apache.stanbol.entityhub.servicesapi.query.SimilarityConstraint)1 TextConstraint (org.apache.stanbol.entityhub.servicesapi.query.TextConstraint)1 ValueConstraint (org.apache.stanbol.entityhub.servicesapi.query.ValueConstraint)1 JSONArray (org.codehaus.jettison.json.JSONArray)1