001/*
002 * (C) Copyright 2006-2007 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.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 *     <a href="mailto:at@nuxeo.com">Anahide Tchertchian</a>
016 *
017 * $Id: IORelationGraphHelper.java 25081 2007-09-18 14:57:22Z atchertchian $
018 */
019
020package org.nuxeo.ecm.platform.relations.io;
021
022import java.io.InputStream;
023import java.io.OutputStream;
024import java.util.List;
025import java.util.Map;
026
027import org.nuxeo.ecm.platform.relations.api.Graph;
028import org.nuxeo.ecm.platform.relations.api.Statement;
029import org.nuxeo.ecm.platform.relations.jena.JenaGraph;
030
031/**
032 * Relation graph importer/exporter.
033 * <p>
034 * relies on Jena memory graphs to perform serialization and deserialization of memory graphs.
035 *
036 * @author <a href="mailto:at@nuxeo.com">Anahide Tchertchian</a>
037 */
038public class IORelationGraphHelper {
039
040    protected final Map<String, String> namespaces;
041
042    protected List<Statement> statements;
043
044    public IORelationGraphHelper(Map<String, String> namespaces, List<Statement> statements) {
045        this.namespaces = namespaces;
046        this.statements = statements;
047    }
048
049    public List<Statement> getStatements() {
050        return statements;
051    }
052
053    protected Graph createMemoryGraph() {
054        JenaGraph graph = new JenaGraph();
055        graph.setNamespaces(namespaces);
056        return graph;
057    }
058
059    public void write(OutputStream out) {
060        Graph graph = createMemoryGraph();
061        if (statements != null) {
062            graph.add(statements);
063        }
064        graph.write(out, null, null);
065    }
066
067    public void read(InputStream in) {
068        Graph graph = createMemoryGraph();
069        if (statements != null) {
070            graph.add(statements);
071        }
072        graph.read(in, null, null);
073        // update current statements with new ones
074        statements = graph.getStatements();
075    }
076
077    public Graph getGraph() {
078        Graph graph = createMemoryGraph();
079        if (statements != null) {
080            graph.add(statements);
081        }
082        return graph;
083    }
084
085}