use of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery 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);
}
use of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery in project stanbol by apache.
the class ReferencedSiteSearcher method lookup.
@Override
public Collection<? extends Entity> lookup(IRI field, Set<IRI> includeFields, List<String> search, String[] languages, Integer limit, Integer offset) throws IllegalStateException {
//build the query and than return the result
Site site = getSearchService();
if (site == null) {
throw new IllegalStateException("ReferencedSite " + siteId + " is currently not available");
}
queryStats.begin();
FieldQuery query = EntitySearcherUtils.createFieldQuery(site.getQueryFactory(), field, includeFields, search, languages);
if (limit != null && limit > 0) {
query.setLimit(limit);
} else if (this.limit != null) {
query.setLimit(this.limit);
}
if (offset != null && offset.intValue() > 0) {
query.setOffset(offset.intValue());
}
QueryResultList<Representation> results;
try {
results = site.find(query);
} catch (SiteException e) {
throw new IllegalStateException("Exception while searchign for " + search + '@' + Arrays.toString(languages) + "in the ReferencedSite " + site.getId(), e);
}
queryStats.complete();
if (!results.isEmpty()) {
Set<String> languagesSet = new HashSet<String>(Arrays.asList(languages));
Collection<Entity> entities = new ArrayList<Entity>(results.size());
for (Representation result : results) {
resultStats.begin();
entities.add(new EntityhubEntity(result, null, languagesSet));
resultStats.complete();
}
return entities;
} else {
return Collections.emptyList();
}
}
use of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery in project stanbol by apache.
the class SiteManagerRootResource method findEntity.
@POST
@Path("/find")
public Response findEntity(@FormParam(value = "name") String name, @FormParam(value = "field") String parsedField, @FormParam(value = "lang") String language, // @FormParam(value="select") String select,
@FormParam(value = "limit") Integer limit, @FormParam(value = "offset") Integer offset, @FormParam(value = "ldpath") String ldpath, @Context HttpHeaders headers) {
log.debug("findEntity() Request");
Collection<String> supported = new HashSet<String>(JerseyUtils.QUERY_RESULT_SUPPORTED_MEDIA_TYPES);
supported.add(TEXT_HTML);
final MediaType acceptedMediaType = getAcceptableMediaType(headers, supported, MediaType.APPLICATION_JSON_TYPE);
if (name == null || name.isEmpty()) {
if (MediaType.TEXT_HTML_TYPE.isCompatible(acceptedMediaType)) {
ResponseBuilder rb = Response.ok(new Viewable("find", this));
rb.header(HttpHeaders.CONTENT_TYPE, TEXT_HTML + "; charset=utf-8");
//addCORSOrigin(servletContext, rb, headers);
return rb.build();
} else {
return Response.status(Status.BAD_REQUEST).entity("The name must not be null nor empty for find requests. Missing parameter name.\n").header(HttpHeaders.ACCEPT, acceptedMediaType).build();
}
}
final String property;
if (parsedField == null) {
property = DEFAULT_FIND_FIELD;
} else {
parsedField = parsedField.trim();
if (parsedField.isEmpty()) {
property = DEFAULT_FIND_FIELD;
} else {
property = nsPrefixService.getFullName(parsedField);
if (property == null) {
String messsage = String.format("The prefix '%s' of the parsed field '%' is not " + "mapped to any namespace. Please parse the full URI instead!\n", NamespaceMappingUtils.getPrefix(parsedField), parsedField);
return Response.status(Status.BAD_REQUEST).entity(messsage).header(HttpHeaders.ACCEPT, acceptedMediaType).build();
}
}
}
FieldQuery query = JerseyUtils.createFieldQueryForFindRequest(name, property, language, limit == null || limit < 1 ? DEFAULT_FIND_RESULT_LIMIT : limit, offset, ldpath);
return executeQuery(referencedSiteManager, query, acceptedMediaType, headers);
}
use of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery 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;
}
use of org.apache.stanbol.entityhub.servicesapi.query.FieldQuery in project stanbol by apache.
the class SparqlQueryUtilsTest method generateSparqlQueryString.
/**
* Utility function for generating SparqlQuery
* @param textWithDoubleQuote
* @param patternType
*/
private String generateSparqlQueryString(String textWithDoubleQuote, PatternType patternType) {
int limit = 10;
FieldQueryFactory qf = DefaultQueryFactory.getInstance();
FieldQuery query = qf.createFieldQuery();
String DEFAULT_AUTOCOMPLETE_SEARCH_FIELD = NamespaceEnum.rdfs + "label";
Collection<String> selectedFields = new ArrayList<String>();
selectedFields.add(DEFAULT_AUTOCOMPLETE_SEARCH_FIELD);
query.addSelectedFields(selectedFields);
query.setConstraint(DEFAULT_AUTOCOMPLETE_SEARCH_FIELD, new TextConstraint(textWithDoubleQuote, patternType, true, "en", null));
query.setLimit(10);
query.setOffset(0);
final SparqlFieldQuery sparqlQuery = SparqlFieldQueryFactory.getSparqlFieldQuery(query);
return SparqlQueryUtils.createSparqlSelectQuery(sparqlQuery, false, limit, SparqlEndpointTypeEnum.Standard);
}
Aggregations