001/*
002 * (C) Copyright 2011 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 *     Florent Guillaume
018 */
019package org.nuxeo.ecm.platform.relations.jena;
020
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.core.api.CoreSession;
024import org.nuxeo.ecm.platform.relations.CoreGraphFactory;
025import org.nuxeo.ecm.platform.relations.api.Graph;
026import org.nuxeo.ecm.platform.relations.api.GraphDescription;
027import org.nuxeo.ecm.platform.relations.api.GraphFactory;
028import org.nuxeo.ecm.platform.relations.services.RelationService;
029import org.nuxeo.runtime.api.Framework;
030
031/**
032 * A factory that detects if a Jena graph or a core graph should be used, and remembers it for future invocations.
033 * <p>
034 * A Jena graph is used if it contains at least one relation for the given graph.
035 */
036public class JenaOrCoreGraphFactory implements GraphFactory {
037
038    private static final Log log = LogFactory.getLog(JenaOrCoreGraphFactory.class);
039
040    // used for tests
041    protected static JenaGraph testJenaGraph;
042
043    @Override
044    public Graph createGraph(GraphDescription graphDescription, CoreSession session) {
045        RelationService service = (RelationService) Framework.getRuntime().getComponent(RelationService.NAME);
046        String name = graphDescription.getName();
047
048        Graph graph;
049        if (testJenaGraph == null) {
050            graph = new JenaGraph();
051        } else {
052            // test mode, allows reuse of in-memory graph
053            graph = testJenaGraph;
054        }
055        graph.setDescription(graphDescription);
056        if (graph.size().longValue() > 0) {
057            // Jena graph already contains data, use it
058            service.graphFactories.remove(name);
059            service.graphRegistry.put(name, graph);
060            log.info("Graph " + name + " using Jena");
061        } else {
062            // use a core graph and remember this factory
063            GraphFactory factory = new CoreGraphFactory();
064            service.graphFactories.put(name, factory);
065            graph = factory.createGraph(graphDescription, session);
066            log.info("Graph " + name + " using Core");
067        }
068        return graph;
069    }
070
071}