001/** 002 * Copyright (C) 2007 - 2016, Jens Lehmann 003 * 004 * This file is part of DL-Learner. 005 * 006 * DL-Learner is free software; you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation; either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * DL-Learner is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with this program. If not, see <http://www.gnu.org/licenses/>. 018 */ 019package org.dllearner.utilities; 020 021import org.apache.jena.query.ParameterizedSparqlString; 022import org.apache.jena.query.Query; 023import org.apache.jena.query.QueryExecution; 024import org.apache.jena.query.ResultSet; 025import org.apache.jena.vocabulary.RDFS; 026import org.aksw.jena_sparql_api.core.QueryExecutionFactory; 027import org.semanticweb.owlapi.model.OWLEntity; 028import org.semanticweb.owlapi.util.ShortFormProvider; 029import org.semanticweb.owlapi.util.SimpleIRIShortFormProvider; 030 031import javax.annotation.Nonnull; 032 033/** 034 * A short form provider for OWL entities which uses the English rdfs:label if exist. 035 * 036 * @author Lorenz Buehmann 037 */ 038public class LabelShortFormProvider implements ShortFormProvider{ 039 040 private final ParameterizedSparqlString queryTemplate = new ParameterizedSparqlString( 041 "SELECT ?label WHERE {?entity ?labelProperty ?label. FILTER(LANGMATCHES(LANG(?label),'en'))} LIMIT 1"); 042 private String labelProperty = RDFS.label.getURI(); 043 044 private final SimpleIRIShortFormProvider fallback = new SimpleIRIShortFormProvider(); 045 046 private final QueryExecutionFactory qef; 047 048 public LabelShortFormProvider(QueryExecutionFactory qef) { 049 this.qef = qef; 050 } 051 052 public void setLabelProperty(String labelProperty) { 053 this.labelProperty = labelProperty; 054 } 055 056 @Override 057 public void dispose() { 058 try { 059 qef.close(); 060 } catch (Exception e) { 061 e.printStackTrace(); 062 } 063 } 064 065 @Nonnull 066 @Override 067 public String getShortForm(@Nonnull OWLEntity entity) { 068 queryTemplate.clearParams(); 069 queryTemplate.setIri("entity", entity.toStringID()); 070 queryTemplate.setIri("labelProperty", labelProperty); 071 Query query = queryTemplate.asQuery(); 072 try(QueryExecution qe = qef.createQueryExecution(query)) { 073 ResultSet rs = qe.execSelect(); 074 String label = null; 075 if(rs.hasNext()){ 076 label = rs.next().getLiteral("label").asLiteral().getLexicalForm(); 077 } else { 078 label = fallback.getShortForm(entity.getIRI()); 079 } 080 return label; 081 } 082 } 083}