001    /*
002     * (c) Copyright 2009 University of Bristol
003     * All rights reserved.
004     * [See end of file]
005     */
006    package net.rootdev.javardfa;
007    
008    import java.util.Collections;
009    import java.util.HashMap;
010    import java.util.LinkedList;
011    import java.util.List;
012    import java.util.Map;
013    
014    import org.slf4j.Logger;
015    import org.slf4j.LoggerFactory;
016    
017    
018    import com.hp.hpl.jena.datatypes.TypeMapper;
019    import com.hp.hpl.jena.graph.Node;
020    import com.hp.hpl.jena.graph.Triple;
021    import com.hp.hpl.jena.query.Query;
022    import com.hp.hpl.jena.rdf.model.AnonId;
023    import com.hp.hpl.jena.sparql.core.Var;
024    import com.hp.hpl.jena.sparql.syntax.Element;
025    import com.hp.hpl.jena.sparql.syntax.ElementGroup;
026    import com.hp.hpl.jena.sparql.syntax.ElementNamedGraph;
027    import com.hp.hpl.jena.sparql.syntax.TemplateGroup;
028    import com.hp.hpl.jena.vocabulary.RDF;
029    import java.util.Map.Entry;
030    
031    public class QueryCollector implements StatementSink {
032    
033        final static Logger log = LoggerFactory.getLogger(QueryCollector.class);
034        private static final Node FormType = Node.createURI("http://www.w3.org/1999/xhtml/vocab/#form");
035        private static final TypeMapper TMapper = TypeMapper.getInstance();
036        private final Map<String, Query> queries;
037        private List<Triple> currentQuery;
038        private String currentQueryName;
039        private final Map<String, String> prefixMapping;
040    
041        public QueryCollector() {
042            queries = new HashMap();
043            prefixMapping = new HashMap();
044        }
045    
046        public Map<String, Query> getQueries() {
047            return Collections.unmodifiableMap(queries);
048        }
049    
050        public void addLiteral(String arg0, String arg1, String arg2, String arg3,
051                String arg4) {
052            //log.info("Add literal");
053            Node subject = getNode(arg0);
054            Node predicate = getNode(arg1);
055            Node object = getLiteralNode(arg2, arg3, arg4);
056            addTriple(subject, predicate, object);
057        }
058    
059        public void addObject(String arg0, String arg1, String arg2) {
060            //log.info("Add object");
061            Node subject = getNode(arg0);
062            Node predicate = getNode(arg1);
063            Node object = getNode(arg2);
064            addTriple(subject, predicate, object);
065        }
066    
067        private void addTriple(Node subject, Node predicate, Node object) {
068            //log.info("Adding triple: " + subject + " " + predicate + " " + object);
069            if (RDF.type.asNode().equals(predicate) &&
070                    FormType.equals(object)) {
071                if (currentQueryName != null) {
072                    queries.put(currentQueryName, createQuery(currentQuery));
073                }
074                currentQueryName = subject.getURI();
075                currentQuery = new LinkedList<Triple>();
076                return;
077            }
078            if (currentQueryName == null) {
079                return; // good idea? not sure...
080            }
081            currentQuery.add(Triple.create(subject, predicate, object));
082        }
083    
084        private Node getLiteralNode(String arg2, String arg3, String arg4) {
085            if (arg3 == null && arg4 == null) {
086                return Node.createLiteral(arg2);
087            } else if (arg4 == null) { // has lang
088                return Node.createLiteral(arg2, arg3, false);
089            } else { // has datatype
090                return Node.createLiteral(arg2, null, TMapper.getSafeTypeByName(arg4));
091            }
092        }
093    
094        private Node getNode(String arg0) {
095            if (arg0.startsWith("_:")) // BNode
096            {
097                return Node.createAnon(AnonId.create(arg0.substring(2)));
098            }
099            if (arg0.startsWith("?")) // Var
100            {
101                return Var.alloc(arg0.substring(1));
102            } else {
103                return Node.createURI(arg0);
104            }
105        }
106    
107        public void end() {
108            if (currentQueryName != null) {
109                queries.put(currentQueryName, createQuery(currentQuery));
110            }
111        }
112    
113        public void start() {
114        }
115    
116        public Query createQuery(List<Triple> triples) {
117            log.info("Create query");
118            Query query = new Query();
119            ElementGroup body = new ElementGroup();
120            for (Triple t : triples) {
121                body.addTriplePattern(t);
122            }
123            // TODO make this switchable.
124            Element pattern = new ElementNamedGraph(Var.alloc("graph"), body);
125            query.setQueryPattern(pattern);
126            query.addProjectVars(Collections.singleton("s"));
127            //query.setQuerySelectType();
128            TemplateGroup templ = new TemplateGroup();
129            for (Triple triple : triples) {
130                templ.addTriple(triple);
131            }
132            query.setQuerySelectType();
133            query.setQueryResultStar(true);
134            query.setConstructTemplate(templ);
135            for (Entry<String, String> e: prefixMapping.entrySet())
136                query.setPrefix(e.getKey(), e.getValue());
137            return query;
138        }
139    
140        public void addPrefix(String prefix, String uri) {
141            prefixMapping.put(prefix, uri);
142        }
143    }
144    
145    /*
146     * (c) Copyright 2009 University of Bristol
147     * All rights reserved.
148     *
149     * Redistribution and use in source and binary forms, with or without
150     * modification, are permitted provided that the following conditions
151     * are met:
152     * 1. Redistributions of source code must retain the above copyright
153     *    notice, this list of conditions and the following disclaimer.
154     * 2. Redistributions in binary form must reproduce the above copyright
155     *    notice, this list of conditions and the following disclaimer in the
156     *    documentation and/or other materials provided with the distribution.
157     * 3. The name of the author may not be used to endorse or promote products
158     *    derived from this software without specific prior written permission.
159     *
160     * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
161     * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
162     * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
163     * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
164     * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
165     * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
166     * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
167     * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
168     * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
169     * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
170     */