001/* 002 * (C) Copyright 2006-2015 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Alexandre Russel 016 * Florent Guillaume 017 */ 018 019package org.nuxeo.ecm.platform.annotations.service; 020 021import java.net.URI; 022import java.util.ArrayList; 023import java.util.HashMap; 024import java.util.List; 025import java.util.Map; 026 027import org.nuxeo.ecm.platform.annotations.api.Annotation; 028import org.nuxeo.ecm.platform.annotations.api.AnnotationManager; 029import org.nuxeo.ecm.platform.annotations.api.AnnotationsConstants; 030import org.nuxeo.ecm.platform.relations.api.Graph; 031import org.nuxeo.ecm.platform.relations.api.Node; 032import org.nuxeo.ecm.platform.relations.api.QueryResult; 033import org.nuxeo.ecm.platform.relations.api.Statement; 034import org.nuxeo.ecm.platform.relations.api.impl.StatementImpl; 035 036public class AnnotationQuery { 037 038 private final AnnotationManager manager = new AnnotationManager(); 039 040 public List<Annotation> getAnnotationsForURIs(URI uri, Graph graph) { 041 List<Annotation> annotations = new ArrayList<Annotation>(); 042 String query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . " // 043 + "?s <" + AnnotationsConstants.A_ANNOTATES + "> <" + uri.toString() + "> . }"; 044 QueryResult results = graph.query(query, "sparql", null); 045 Map<String, List<Statement>> mapann = new HashMap<String, List<Statement>>(); 046 for (Map<String, Node> map : results.getResults()) { 047 Node subject = map.get("s"); 048 Node predicate = map.get("p"); 049 Node object = map.get("o"); 050 List<Statement> statements = mapann.get(subject.toString()); 051 if (statements == null) { 052 statements = new ArrayList<Statement>(); 053 mapann.put(subject.toString(), statements); 054 } 055 statements.add(new StatementImpl(subject, predicate, object)); 056 } 057 for (List<Statement> stats : mapann.values()) { 058 annotations.add(manager.getAnnotation(stats)); 059 } 060 return annotations; 061 } 062 063 public int getAnnotationsCountForURIs(URI uri, Graph graph) { 064 String query = "SELECT ?s WHERE { ?s <" + AnnotationsConstants.A_ANNOTATES + "> <" + uri.toString() + "> }"; 065 return graph.queryCount(query, "sparql", null); 066 } 067 068}