podd.triples.SesameOracleUnitTest.java Source code

Java tutorial

Introduction

Here is the source code for podd.triples.SesameOracleUnitTest.java

Source

/*
 * Copyright (c) 2009 - 2010. School of Information Technology and Electrical
 * Engineering, The University of Queensland.  This software is being developed
 * for the "Phenomics Ontoogy Driven Data Management Project (PODD)" project.
 * PODD is a National e-Research Architecture Taskforce (NeAT) project
 * co-funded by ANDS and ARCS.
 *
 * PODD is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PODD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PODD.  If not, see <http://www.gnu.org/licenses/>.
 */

package podd.triples;

import info.aduna.collections.iterators.CloseableIterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openrdf.model.Graph;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.GraphImpl;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.resultio.TupleQueryResultWriter;
import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriter;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import podd.triples.impl.SesameLocalRepoWrapperImpl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;

import static java.util.Collections.singleton;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static podd.dataaccess.fedora.FedoraDAOTestUtil.getIteratorContent;

/**
 * @author Yuan-Fang Li
 * @version $Id$
 */
public class SesameOracleUnitTest {
    private SesameOracle oracle;
    private SesameRepoWrapper wrapper;

    @Before
    public void setUp() throws RepositoryException, IOException {
        wrapper = new SesameLocalRepoWrapperImpl();
        oracle = new SesameOracle(wrapper, new TripleStoreCacheManager(5, wrapper));
    }

    @After
    public void tearDown() throws Exception {
        clearRepo();
        wrapper.close();
    }

    private void clearRepo() throws RepositoryException {
        final RepositoryConnection conn = wrapper.getConnection();
        try {
            conn.clear();
            conn.commit();
        } finally {
            conn.close();
        }
    }

    @Test
    public void testGetTriplesFromContext() throws RepositoryException, TripleStoreQueryException {
        final String context = "http://www.example.org#";
        addTriplesToRepo(3, context);
        CloseableIterator<Statement> iterator = oracle.getRDFFromContext(context);
        Set<Statement> set = getIteratorContent(iterator);
        assertEquals(3, set.size());

        iterator = oracle.getRDFFromContext(context + "random");
        set = getIteratorContent(iterator);
        assertEquals(0, set.size());

        clearRepo();
        addTriplesToRepo(6);
        iterator = oracle.getRDFFromContext(context);
        set = getIteratorContent(iterator);
        assertEquals(0, set.size());
    }

    @Test
    public void testContextlessQuery() throws Exception {
        addTriplesToRepo(3);

        final TupleQueryResult queryResult = oracle.queryTripleStore("SELECT * WHERE { ?s ?p ?o }");
        int count = countResult(queryResult);
        assertEquals(3, count);
    }

    @Test
    public void testContextQuery() throws RepositoryException, TripleStoreQueryException, QueryEvaluationException {
        final String queryString = "SELECT * WHERE { ?s ?p ?o }";

        final String context = "http://www.example.org#";
        addTriplesToRepo(3, context);
        String randomContext1 = context + "random1/";
        addTriplesToRepo(2, randomContext1);

        TupleQueryResult queryResult = oracle.queryContextualGraph(queryString, singleton(randomContext1));
        int count = countResult(queryResult);
        assertEquals("query result from context: " + randomContext1, 2, count);

        queryResult = oracle.queryContextualGraph(queryString, singleton(context));
        count = countResult(queryResult);
        assertEquals("query result from context: " + context, 3, count);

        queryResult = oracle.queryTripleStore(queryString);
        count = countResult(queryResult);
        assertEquals("query result from all contexts", 5, count);

        queryResult = oracle.queryTripleStore("SELECT * WHERE { ?s ?p ?o FILTER (?s = ?p && ?p = ?o) }");
        count = countResult(queryResult);
        assertEquals("query result from all contexts using filters", 5, count);

        queryResult = oracle.queryTripleStore("SELECT * WHERE { ?s ?p ?o FILTER (?s != ?p) }");
        count = countResult(queryResult);
        assertEquals(0, count);

        queryResult = oracle.queryContextualGraph(queryString, singleton(context + "random/"));
        count = countResult(queryResult);
        assertEquals(0, count);
    }

    @Test
    public void testJSONResult() throws RepositoryException, TripleStoreQueryException, IOException, JSONException {
        final String context = "http://www.example.org#";
        final String queryString = "SELECT * WHERE { ?s ?p ?o }";
        addTriplesToRepo(3, context);
        OutputStream out = new ByteArrayOutputStream(512);
        try {
            TupleQueryResultWriter writer = new SPARQLResultsJSONWriter(out);
            oracle.queryContextualGraph(queryString, singleton(context), writer);
            JSONObject obj = new JSONObject(out.toString());
            final Object header = obj.get("head");
            assertTrue(header instanceof JSONObject);
            assertEquals(1, ((JSONObject) header).length());
            final Object vars = ((JSONObject) header).get("vars");
            assertTrue(vars instanceof JSONArray);
            assertEquals(3, ((JSONArray) vars).length());
            final Object bindings = ((JSONObject) obj.get("results")).get("bindings");
            assertTrue(bindings instanceof JSONArray);
            assertEquals(3, ((JSONArray) bindings).length());
        } finally {
            out.close();
        }
    }

    private void addTriplesToRepo(int count, String... contexts) throws RepositoryException {
        final RepositoryConnection conn = wrapper.getConnection();
        final ValueFactory valueFactory = conn.getValueFactory();
        long timestamp = System.currentTimeMillis();
        try {
            Graph graph = new GraphImpl();
            final String namespace = "http://www.example.org#";
            for (int i = 0; i < count; i++) {
                final org.openrdf.model.URI ind1 = valueFactory.createURI(namespace + (timestamp + i));
                graph.add(ind1, ind1, ind1);
            }
            if (contexts.length > 0) {
                for (String context : contexts) {
                    org.openrdf.model.URI uri = valueFactory.createURI(context);
                    conn.add(graph, uri);
                }
            } else {
                conn.add(graph);
            }
            conn.commit();
        } finally {
            conn.close();
        }
    }

    private int countResult(TupleQueryResult queryResult) throws QueryEvaluationException {
        int count = 0;
        try {
            while (queryResult.hasNext()) {
                queryResult.next();
                count++;
            }
        } finally {
            queryResult.close();
        }
        return count;
    }
}