001/* 002 * (C) Copyright 2006-2015 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Alexandre Russel 018 * Florent Guillaume 019 */ 020 021package org.nuxeo.ecm.platform.annotations.service; 022 023import java.net.URI; 024import java.util.ArrayList; 025import java.util.HashMap; 026import java.util.List; 027import java.util.Map; 028 029import org.nuxeo.ecm.platform.annotations.api.Annotation; 030import org.nuxeo.ecm.platform.annotations.api.AnnotationManager; 031import org.nuxeo.ecm.platform.annotations.api.AnnotationsConstants; 032import org.nuxeo.ecm.platform.relations.api.Graph; 033import org.nuxeo.ecm.platform.relations.api.Node; 034import org.nuxeo.ecm.platform.relations.api.QueryResult; 035import org.nuxeo.ecm.platform.relations.api.Statement; 036import org.nuxeo.ecm.platform.relations.api.impl.StatementImpl; 037 038public class AnnotationQuery { 039 040 private final AnnotationManager manager = new AnnotationManager(); 041 042 public List<Annotation> getAnnotationsForURIs(URI uri, Graph graph) { 043 List<Annotation> annotations = new ArrayList<Annotation>(); 044 String query = "SELECT ?s ?p ?o WHERE { ?s ?p ?o . " // 045 + "?s <" + AnnotationsConstants.A_ANNOTATES + "> <" + uri.toString() + "> . }"; 046 QueryResult results = graph.query(query, "sparql", null); 047 Map<String, List<Statement>> mapann = new HashMap<String, List<Statement>>(); 048 for (Map<String, Node> map : results.getResults()) { 049 Node subject = map.get("s"); 050 Node predicate = map.get("p"); 051 Node object = map.get("o"); 052 List<Statement> statements = mapann.get(subject.toString()); 053 if (statements == null) { 054 statements = new ArrayList<Statement>(); 055 mapann.put(subject.toString(), statements); 056 } 057 statements.add(new StatementImpl(subject, predicate, object)); 058 } 059 for (List<Statement> stats : mapann.values()) { 060 annotations.add(manager.getAnnotation(stats)); 061 } 062 return annotations; 063 } 064 065 public int getAnnotationsCountForURIs(URI uri, Graph graph) { 066 String query = "SELECT ?s WHERE { ?s <" + AnnotationsConstants.A_ANNOTATES + "> <" + uri.toString() + "> }"; 067 return graph.queryCount(query, "sparql", null); 068 } 069 070}