Пример #1
0
        public void StorageSparqlUniformHttpProtocolAddTriples()
        {
            try
            {
                SetUriLoaderCaching(false);

                StorageSparqlUniformHttpProtocolSaveGraph();

                Graph g = new Graph();
                g.Retract(g.Triples.Where(t => !t.IsGroundTriple));
                FileLoader.Load(g, "resources\\InferenceTest.ttl");

                SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();
                sparql.UpdateGraph("http://example.org/sparqlTest", g.Triples, null);

                Graph h = new Graph();
                sparql.LoadGraph(h, "http://example.org/sparqlTest");

                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString(this._formatter));
                }

                Assert.IsTrue(g.IsSubGraphOf(h), "Retrieved Graph should have the added Triples as a Sub Graph");
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
Пример #2
0
        public void StorageSparqlUniformHttpProtocolRemoveTriples()
        {
            try
            {
                SetUriLoaderCaching(false);
                Graph g = new Graph();
                FileLoader.Load(g, "resources\\InferenceTest.ttl");

                try
                {
                    SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();
                    sparql.UpdateGraph("http://example.org/sparqlTest", null, g.Triples);

                    Assert.Fail("SPARQL Uniform HTTP Protocol does not support removing Triples");
                }
                catch (RdfStorageException storeEx)
                {
                    Console.WriteLine("Got an error as expected");
                    TestTools.ReportError("Storage Error", storeEx);
                }
                catch (NotSupportedException ex)
                {
                    Console.WriteLine("Got a Not Supported error as expected");
                    TestTools.ReportError("Not Supported", ex);
                }
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
Пример #3
0
        public void StorageSparqlUniformHttpProtocolDeleteGraph()
        {
            try
            {
                SetUriLoaderCaching(false);
                StorageSparqlUniformHttpProtocolSaveGraph();

                SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();
                sparql.DeleteGraph("http://example.org/sparqlTest");

                //Give SPARQL Uniform Protocol time to delete stuff
                Thread.Sleep(1000);

                try
                {
                    Graph g = new Graph();
                    sparql.LoadGraph(g, "http://example.org/sparqlTest");

                    //If we do get here without erroring then the Graph should be empty
                    Assert.IsTrue(g.IsEmpty, "If the Graph loaded without error then it should have been empty as we deleted it from the store");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Errored as expected since the Graph was deleted");
                    TestTools.ReportError("Error", ex);
                }
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
Пример #4
0
        public void StorageSparqlUniformHttpProtocolPostCreateMultiple()
        {
            SparqlHttpProtocolConnector connector = SparqlGraphStoreProtocolTest.GetConnection();

            Graph g = new Graph();

            FileLoader.Load(g, "resources\\InferenceTest.ttl");

            List <Uri> uris = new List <Uri>();

            for (int i = 0; i < 10; i++)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri));
                request.Method      = "POST";
                request.ContentType = "application/rdf+xml";

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
                    rdfxmlwriter.Save(g, writer);
                    writer.Close();
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    //Should get a 201 Created response
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        if (response.Headers["Location"] == null)
                        {
                            Assert.Fail("A Location: Header containing the URI of the newly created Graph should have been returned");
                        }
                        Uri graphUri = new Uri(response.Headers["Location"]);
                        uris.Add(graphUri);

                        Console.WriteLine("New Graph URI is " + graphUri.ToString());

                        Console.WriteLine("Now attempting to retrieve this Graph from the Store");
                        Graph h = new Graph();
                        connector.LoadGraph(h, graphUri);

                        Assert.AreEqual(g, h, "Graphs should have been equal");
                        Console.WriteLine("Graphs were equal as expected");
                    }
                    else
                    {
                        Assert.Fail("A 201 Created response should have been received but got a " + (int)response.StatusCode + " response");
                    }
                    response.Close();
                }
                Console.WriteLine();
            }

            Assert.IsTrue(uris.Distinct().Count() == 10, "Should have generated 10 distinct URIs");
        }
Пример #5
0
        public void StorageSparqlUniformHttpProtocolSaveGraph()
        {
            try
            {
                SetUriLoaderCaching(false);

                Graph g = new Graph();
                FileLoader.Load(g, "resources\\Turtle.ttl");
                g.BaseUri = new Uri("http://example.org/sparqlTest");

                //Save Graph to SPARQL Uniform Protocol
                SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();
                sparql.SaveGraph(g);
                Console.WriteLine("Graph saved to SPARQL Uniform Protocol OK");

                //Now retrieve Graph from SPARQL Uniform Protocol
                Graph h = new Graph();
                sparql.LoadGraph(h, "http://example.org/sparqlTest");

                Console.WriteLine();
                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString(this._formatter));
                }

                GraphDiffReport diff = g.Difference(h);
                if (!diff.AreEqual)
                {
                    Console.WriteLine();
                    Console.WriteLine("Graphs are different - should be 1 difference due to New Line Normalization");
                    Console.WriteLine("Added Triples");
                    foreach (Triple t in diff.AddedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }
                    Console.WriteLine("Removed Triples");
                    foreach (Triple t in diff.RemovedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }

                    Assert.IsTrue(diff.AddedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization");
                    Assert.IsTrue(diff.RemovedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization");
                    Assert.IsFalse(diff.AddedMSGs.Any(), "Should not be any MSG differences");
                    Assert.IsFalse(diff.RemovedMSGs.Any(), "Should not be any MSG differences");
                }
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
        public void StorageSparqlUniformHttpProtocolSaveGraph()
        {
            try
            {
                Options.UriLoaderCaching = false;

                Graph g = new Graph();
                FileLoader.Load(g, "Turtle.ttl");
                g.BaseUri = new Uri("http://example.org/sparqlTest");

                //Save Graph to SPARQL Uniform Protocol
                SparqlHttpProtocolConnector sparql = new SparqlHttpProtocolConnector(new Uri(ProtocolTestUri));
                sparql.SaveGraph(g);
                Console.WriteLine("Graph saved to SPARQL Uniform Protocol OK");

                //Now retrieve Graph from SPARQL Uniform Protocol
                Graph h = new Graph();
                sparql.LoadGraph(h, "http://example.org/sparqlTest");

                Console.WriteLine();
                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString(this._formatter));
                }

                GraphDiffReport diff = g.Difference(h);
                if (!diff.AreEqual)
                {
                    Console.WriteLine();
                    Console.WriteLine("Graphs are different - should be 1 difference due to New Line Normalization");
                    Console.WriteLine("Added Triples");
                    foreach (Triple t in diff.AddedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }
                    Console.WriteLine("Removed Triples");
                    foreach (Triple t in diff.RemovedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }

                    Assert.IsTrue(diff.AddedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization");
                    Assert.IsTrue(diff.RemovedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization");
                    Assert.IsFalse(diff.AddedMSGs.Any(), "Should not be any MSG differences");
                    Assert.IsFalse(diff.RemovedMSGs.Any(), "Should not be any MSG differences");
                }
            }
            finally
            {
                Options.UriLoaderCaching = true;
            }
        }
        public void StorageSparqlUniformHttpProtocolLoadGraph()
        {
            try
            {
                SetUriLoaderCaching(false);
                //Ensure that the Graph will be there using the SaveGraph() test
                StorageSparqlUniformHttpProtocolSaveGraph();

                Graph g = new Graph();
                FileLoader.Load(g, "resources\\Turtle.ttl");
                g.BaseUri = new Uri("http://example.org/sparqlTest");

                //Try to load the relevant Graph back from the Store
                SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();

                Graph h = new Graph();
                sparql.LoadGraph(h, "http://example.org/sparqlTest");

                Console.WriteLine();
                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString(this._formatter));
                }

                GraphDiffReport diff = g.Difference(h);
                if (!diff.AreEqual)
                {
                    Console.WriteLine();
                    Console.WriteLine("Graphs are different - should be 1 difference due to New Line Normalization");
                    Console.WriteLine("Added Triples");
                    foreach (Triple t in diff.AddedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }
                    Console.WriteLine("Removed Triples");
                    foreach (Triple t in diff.RemovedTriples)
                    {
                        Console.WriteLine(t.ToString(this._formatter));
                    }

                    Assert.True(diff.AddedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization (added)");
                    Assert.True(diff.RemovedTriples.Count() == 1, "Should only be 1 Triple difference due to New Line normalization (removed)");
                    Assert.False(diff.AddedMSGs.Any(), "Should not be any MSG differences");
                    Assert.False(diff.RemovedMSGs.Any(), "Should not be any MSG differences");
                }
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
        public void StorageSparqlUniformHttpProtocolPostCreate()
        {
            SparqlHttpProtocolConnector connector = SparqlGraphStoreProtocolTest.GetConnection();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(TestConfigManager.GetSetting(TestConfigManager.LocalGraphStoreUri));

            request.Method      = "POST";
            request.ContentType = "application/rdf+xml";

            Graph g = new Graph();

            FileLoader.Load(g, "resources\\InferenceTest.ttl");

            using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
            {
                RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
                rdfxmlwriter.Save(g, writer);
                writer.Close();
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                //Should get a 201 Created response
                if (response.StatusCode == HttpStatusCode.Created)
                {
                    if (response.Headers["Location"] == null)
                    {
                        Assert.True(false, "A Location: Header containing the URI of the newly created Graph should have been returned");
                    }
                    Uri graphUri = new Uri(response.Headers["Location"]);

                    Console.WriteLine("New Graph URI is " + graphUri.ToString());

                    Console.WriteLine("Now attempting to retrieve this Graph from the Store");
                    Graph h = new Graph();
                    connector.LoadGraph(h, graphUri);

                    TestTools.ShowGraph(h);

                    Assert.Equal(g, h);
                }
                else
                {
                    Assert.True(false, "A 201 Created response should have been received but got a " + (int)response.StatusCode + " response");
                }
                response.Close();
            }
        }
Пример #9
0
        public void StorageSparqlUniformHttpProtocolGraphExists()
        {
            try
            {
                SetUriLoaderCaching(false);
                //Ensure that the Graph will be there using the SaveGraph() test
                StorageSparqlUniformHttpProtocolSaveGraph();

                //Check the Graph exists in the Store
                SparqlHttpProtocolConnector sparql = SparqlGraphStoreProtocolTest.GetConnection();
                Assert.IsTrue(sparql.HasGraph("http://example.org/sparqlTest"));
            }
            finally
            {
                SetUriLoaderCaching(true);
            }
        }
Пример #10
0
        /// <summary>
        /// Tries to load a Generic IO Manager based on information from the Configuration Graph
        /// </summary>
        /// <param name="g">Configuration Graph</param>
        /// <param name="objNode">Object Node</param>
        /// <param name="targetType">Target Type</param>
        /// <param name="obj">Output Object</param>
        /// <returns></returns>
        public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
        {
            IGenericIOManager manager = null;
            obj = null;

            String server, user, pwd, store;
            bool isAsync;

            Object temp;
            INode storeObj;

            //Create the URI Nodes we're going to use to search for things
            INode propServer = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyServer),
                  propDb = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyDatabase),
                  propStore = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyStore),
                  propAsync = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyAsync);

            switch (targetType.FullName)
            {
                case AllegroGraph:
                    //Get the Server, Catalog and Store
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    String catalog = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyCatalog));
                    store = ConfigurationLoader.GetConfigurationString(g, objNode, propStore);
                    if (store == null) return false;

                    //Get User Credentials
                    ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                    if (user != null && pwd != null)
                    {
                        manager = new AllegroGraphConnector(server, catalog, store, user, pwd);
                    }
                    else
                    {
                        manager = new AllegroGraphConnector(server, catalog, store);
                    }
                    break;

                case DatasetFile:
                    //Get the Filename and whether the loading should be done asynchronously
                    String file = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromFile));
                    if (file == null) return false;
                    file = ConfigurationLoader.ResolvePath(file);
                    isAsync = ConfigurationLoader.GetConfigurationBoolean(g, objNode, propAsync, false);
                    manager = new DatasetFileManager(file, isAsync);
                    break;

                case Dydra:
                    //Get the Account Name and Store
                    String account = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyCatalog));
                    if (account == null) return false;
                    store = ConfigurationLoader.GetConfigurationString(g, objNode, propStore);
                    if (store == null) return false;

                    //Get User Credentials
                    ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                    if (user != null)
                    {
                        manager = new DydraConnector(account, store, user);
                    }
                    else
                    {
                        manager = new DydraConnector(account, store);
                    }
                    break;

                case FourStore:
                    //Get the Server and whether Updates are enabled
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    bool enableUpdates = ConfigurationLoader.GetConfigurationBoolean(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyEnableUpdates), true);
                    manager = new FourStoreConnector(server, enableUpdates);
                    break;

                case Fuseki:
                    //Get the Server URI
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    manager = new FusekiConnector(server);
                    break;

                case InMemory:
                    //Get the Dataset/Store
                    INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingDataset));
                    if (datasetObj != null)
                    {
                        temp = ConfigurationLoader.LoadObject(g, datasetObj);
                        if (temp is ISparqlDataset)
                        {
                            manager = new InMemoryManager((ISparqlDataset)temp);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load the In-Memory Manager identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingDataset property points to an Object that cannot be loaded as an object which implements the ISparqlDataset interface");
                        }
                    }
                    else
                    {
                        //If no dnr:usingDataset try dnr:usingStore instead
                        storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUsingStore));
                        if (storeObj != null)
                        {
                            temp = ConfigurationLoader.LoadObject(g, storeObj);
                            if (temp is IInMemoryQueryableStore)
                            {
                                manager = new InMemoryManager((IInMemoryQueryableStore)temp);
                            }
                            else
                            {
                                throw new DotNetRdfConfigurationException("Unable to load the In-Memory Manager identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:usingStore property points to an Object that cannot be loaded as an object which implements the IInMemoryQueryableStore interface");
                            }
                        }
                        else
                        {
                            //If no dnr:usingStore either then create a new empty store
                            manager = new InMemoryManager();
                        }
                    }
                    break;

                case Joseki:
                    //Get the Query and Update URIs
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    String queryService = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyQueryPath));
                    if (queryService == null) return false;
                    String updateService = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyUpdatePath));
                    if (updateService == null)
                    {
                        manager = new JosekiConnector(server, queryService);
                    }
                    else
                    {
                        manager = new JosekiConnector(server, queryService, updateService);
                    }
                    break;

                case ReadOnly:
                    //Get the actual Manager we are wrapping
                    storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyGenericManager));
                    temp = ConfigurationLoader.LoadObject(g, storeObj);
                    if (temp is IGenericIOManager)
                    {
                        manager = new ReadOnlyConnector((IGenericIOManager)temp);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the Read-Only Connector identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object which cannot be loaded as an object which implements the required IGenericIOManager interface");
                    }
                    break;

                case ReadOnlyQueryable:
                    //Get the actual Manager we are wrapping
                    storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyGenericManager));
                    temp = ConfigurationLoader.LoadObject(g, storeObj);
                    if (temp is IQueryableGenericIOManager)
                    {
                        manager = new QueryableReadOnlyConnector((IQueryableGenericIOManager)temp);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the Queryable Read-Only Connector identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object which cannot be loaded as an object which implements the required IQueryableGenericIOManager interface");
                    }
                    break;

                case Sesame:
                case SesameV5:
                case SesameV6:
                    //Get the Server and Store ID
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    store = ConfigurationLoader.GetConfigurationString(g, objNode, propStore);
                    if (store == null) return false;
                    ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);
                    if (user != null && pwd != null)
                    {
                        manager = (IGenericIOManager)Activator.CreateInstance(targetType, new Object[] { server, store, user, pwd });
                    }
                    else
                    {
                        manager = (IGenericIOManager)Activator.CreateInstance(targetType, new Object[] { server, store });
                    }
                    break;

                case Sparql:
                    //Get the Endpoint URI or the Endpoint
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyEndpointUri));

                    //What's the load mode?
                    String loadModeRaw = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyLoadMode));
                    SparqlConnectorLoadMethod loadMode = SparqlConnectorLoadMethod.Construct;
                    if (loadModeRaw != null)
                    {
                        try
                        {
#if SILVERLIGHT
                            loadMode = (SparqlConnectorLoadMethod)Enum.Parse(typeof(SparqlConnectorLoadMethod), loadModeRaw, false);
#else
                            loadMode = (SparqlConnectorLoadMethod)Enum.Parse(typeof(SparqlConnectorLoadMethod), loadModeRaw);
#endif
                        }
                        catch
                        {
                            throw new DotNetRdfConfigurationException("Unable to load the SparqlConnector identified by the Node '" + objNode.ToString() + "' as the value given for the property dnr:loadMode is not valid");
                        }
                    }

                    if (server == null)
                    {
                        INode endpointObj = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyEndpoint));
                        if (endpointObj == null) return false;
                        temp = ConfigurationLoader.LoadObject(g, endpointObj);
                        if (temp is SparqlRemoteEndpoint)
                        {
                            manager = new SparqlConnector((SparqlRemoteEndpoint)temp, loadMode);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load the SparqlConnector identified by the Node '" + objNode.ToString() + "' as the value given for the property dnr:endpoint points to an Object which cannot be loaded as an object which is of the type SparqlRemoteEndpoint");
                        }
                    }
                    else
                    {
                        //Are there any Named/Default Graph URIs
                        IEnumerable<Uri> defGraphs = from def in ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyDefaultGraphUri))
                                                     where def.NodeType == NodeType.Uri
                                                     select ((IUriNode)def).Uri;
                        IEnumerable<Uri> namedGraphs = from named in ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyNamedGraphUri))
                                                       where named.NodeType == NodeType.Uri
                                                       select ((IUriNode)named).Uri;
                        if (defGraphs.Any() || namedGraphs.Any())
                        {
                            manager = new SparqlConnector(new SparqlRemoteEndpoint(new Uri(server), defGraphs, namedGraphs), loadMode);
                        }
                        else
                        {
                            manager = new SparqlConnector(new Uri(server), loadMode);
                        }                        
                    }
                    break;

                case SparqlHttpProtocol:
                    //Get the Service URI
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    manager = new SparqlHttpProtocolConnector(new Uri(server));
                    break;

                case Stardog:
                    //Get the Server and Store
                    server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                    if (server == null) return false;
                    store = ConfigurationLoader.GetConfigurationString(g, objNode, propStore);
                    if (store == null) return false;

                    //Get User Credentials
                    ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                    //Get Reasoning Mode
                    StardogReasoningMode reasoning = StardogReasoningMode.None;
                    String mode = ConfigurationLoader.GetConfigurationString(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyLoadMode));
                    if (mode != null)
                    {
                        try
                        {
                            reasoning = (StardogReasoningMode)Enum.Parse(typeof(StardogReasoningMode), mode);
                        }
                        catch
                        {
                            reasoning = StardogReasoningMode.None;
                        }
                    }

                    if (user != null && pwd != null)
                    {
                        manager = new StardogConnector(server, store, reasoning, user, pwd);
                    }
                    else
                    {
                        manager = new StardogConnector(server, store, reasoning);
                    }
                    break;

                case Talis:
                    //Get the Store Name and User credentials
                    store = ConfigurationLoader.GetConfigurationString(g, objNode, propStore);
                    if (store == null) return false;
                    ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);
                    if (user != null && pwd != null)
                    {
                        manager = new TalisPlatformConnector(store, user, pwd);
                    }
                    else
                    {
                        manager = new TalisPlatformConnector(store);
                    }
                    break;
            }

            obj = manager;
            return (manager != null);
        }
        public void StorageSparqlUniformHttpProtocolPostCreateMultiple()
        {
            SparqlHttpProtocolConnector connector = new SparqlHttpProtocolConnector("http://localhost/demos/server/");

            Graph g = new Graph();
            FileLoader.Load(g, "InferenceTest.ttl");

            List<Uri> uris = new List<Uri>();
            for (int i = 0; i < 10; i++)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/demos/server/");
                request.Method = "POST";
                request.ContentType = "application/rdf+xml";

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    RdfXmlWriter rdfxmlwriter = new RdfXmlWriter();
                    rdfxmlwriter.Save(g, writer);
                    writer.Close();
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    //Should get a 201 Created response
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        if (response.Headers["Location"] == null) Assert.Fail("A Location: Header containing the URI of the newly created Graph should have been returned");
                        Uri graphUri = new Uri(response.Headers["Location"]);
                        uris.Add(graphUri);

                        Console.WriteLine("New Graph URI is " + graphUri.ToString());

                        Console.WriteLine("Now attempting to retrieve this Graph from the Store");
                        Graph h = new Graph();
                        connector.LoadGraph(h, graphUri);

                        Assert.AreEqual(g, h, "Graphs should have been equal");
                        Console.WriteLine("Graphs were equal as expected");
                    }
                    else
                    {
                        Assert.Fail("A 201 Created response should have been received but got a " + (int)response.StatusCode + " response");
                    }
                    response.Close();
                }
                Console.WriteLine();
            }

            Assert.IsTrue(uris.Distinct().Count() == 10, "Should have generated 10 distinct URIs");
        }
        public void StorageSparqlUniformHttpProtocolRemoveTriples()
        {
            try
            {
                Options.UriLoaderCaching = false;
                Graph g = new Graph();
                FileLoader.Load(g, "InferenceTest.ttl");

                try
                {
                    SparqlHttpProtocolConnector sparql = new SparqlHttpProtocolConnector(new Uri(ProtocolTestUri));
                    sparql.UpdateGraph("http://example.org/sparqlTest", null, g.Triples);

                    Assert.Fail("SPARQL Uniform HTTP Protocol does not support removing Triples");
                }
                catch (RdfStorageException storeEx)
                {
                    Console.WriteLine("Got an error as expected");
                    TestTools.ReportError("Storage Error", storeEx, false);
                }
                catch (NotSupportedException ex)
                {
                    Console.WriteLine("Got a Not Supported error as expected");
                    TestTools.ReportError("Not Supported", ex, false);
                }
            }
            finally
            {
                Options.UriLoaderCaching = true;
            }
        }
        public void StorageSparqlUniformHttpProtocolAddTriples()
        {
            try
            {
                Options.UriLoaderCaching = false;

                StorageSparqlUniformHttpProtocolSaveGraph();

                Graph g = new Graph();
                g.Retract(g.Triples.Where(t => !t.IsGroundTriple));
                FileLoader.Load(g, "InferenceTest.ttl");

                SparqlHttpProtocolConnector sparql = new SparqlHttpProtocolConnector(new Uri(ProtocolTestUri));
                sparql.UpdateGraph("http://example.org/sparqlTest", g.Triples, null);

                Graph h = new Graph();
                sparql.LoadGraph(h, "http://example.org/sparqlTest");

                foreach (Triple t in h.Triples)
                {
                    Console.WriteLine(t.ToString(this._formatter));
                }

                Assert.IsTrue(g.IsSubGraphOf(h), "Retrieved Graph should have the added Triples as a Sub Graph");
            }
            finally
            {
                Options.UriLoaderCaching = true;
            }
        }
        public void StorageSparqlUniformHttpProtocolDeleteGraph()
        {
            try
            {
                Options.UriLoaderCaching = false;
                StorageSparqlUniformHttpProtocolSaveGraph();

                SparqlHttpProtocolConnector sparql = new SparqlHttpProtocolConnector(new Uri(ProtocolTestUri));
                sparql.DeleteGraph("http://example.org/sparqlTest");

                //Give SPARQL Uniform Protocol time to delete stuff
                Thread.Sleep(1000);

                try
                {
                    Graph g = new Graph();
                    sparql.LoadGraph(g, "http://example.org/sparqlTest");

                    //If we do get here without erroring then the Graph should be empty
                    Assert.IsTrue(g.IsEmpty, "If the Graph loaded without error then it should have been empty as we deleted it from the store");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Errored as expected since the Graph was deleted");
                    TestTools.ReportError("Error", ex, false);
                }
            }
            finally
            {
                Options.UriLoaderCaching = true;
            }
        }
        public void StorageSparqlUniformHttpProtocolGraphExists()
        {
            try
            {
                Options.UriLoaderCaching = false;
                //Ensure that the Graph will be there using the SaveGraph() test
                StorageSparqlUniformHttpProtocolSaveGraph();

                //Check the Graph exists in the Store
                SparqlHttpProtocolConnector sparql = new SparqlHttpProtocolConnector(new Uri(ProtocolTestUri));
                Assert.IsTrue(sparql.GraphExists("http://example.org/sparqlTest"));
            }
            finally
            {
                Options.UriLoaderCaching = true;
            }
        }
Пример #16
0
        static void DoProtocol(Dictionary<String, String> arguments)
        {
            String method;
            SparqlHttpProtocolConnector endpoint;
            bool verbose = arguments.ContainsKey("verbose") || arguments.ContainsKey("v");
            if (verbose) Options.HttpDebugging = true;
            Options.UriLoaderCaching = !arguments.ContainsKey("nocache");
            String dataFile;

            //First Argument must be HTTP Method
            if (arguments.ContainsKey("$1") && !arguments["$1"].Equals(String.Empty))
            {
                method = arguments["$1"].ToUpper();
            }
            else
            {
                Console.Error.WriteLine("soh: Error: First argument must be one of head, get, put or post - type soh --help for details");
                Environment.Exit(-1);
                return;
            }

            try
            {
                if (arguments.ContainsKey("$2") && !arguments["$2"].Equals(String.Empty))
                {
                    endpoint = new SparqlHttpProtocolConnector(new Uri(arguments["$2"]));
                }
                else
                {
                    Console.Error.WriteLine("soh: Error: Second argument is required and must be the Dataset URI");
                    Environment.Exit(-1);
                    return;
                }
            }
            catch (UriFormatException uriEx)
            {
                Console.Error.WriteLine("soh: Error: Malformed SPARQL Endpoint URI");
                Console.Error.WriteLine(uriEx.Message);
                Environment.Exit(-1);
                return;
            }
            if (verbose) Console.Error.WriteLine("soh: Connection to SPARQL Uniform HTTP Protocol endpoint created OK");

            Uri graphUri;
            try
            {
                if (arguments.ContainsKey("$3") && !arguments["$3"].Equals(String.Empty))
                {
                    if (arguments["$3"].Equals("default"))
                    {
                        graphUri = null;
                        if (verbose) Console.Error.WriteLine("soh: Graph URI for Protocol request is 'default' (indicates the default unnamed graph)");
                    }
                    else
                    {
                        graphUri = new Uri(arguments["$3"]);
                        if (verbose) Console.Error.WriteLine("soh: Graph URI for Protocol request is '" + graphUri.ToString() + "'");
                    }
                }
                else
                {
                    Console.Error.WriteLine("soh: Error: Third argument is required and must be the Graph URI or default to indicate the default unnamed Graph");
                    Environment.Exit(-1);
                    return;
                }
            }
            catch (UriFormatException uriEx)
            {
                Console.Error.WriteLine("soh: Error: Malformed Graph URI");
                Console.Error.WriteLine(uriEx.Message);
                Environment.Exit(-1);
                return;
            }

            try
            {
                switch (method)
                {
                    case "GET":
                        if (arguments.ContainsKey("$4"))
                        {
                            Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the get method");
                            Environment.Exit(-1);
                            return;
                        }

                        if (verbose) Console.Error.WriteLine("soh: Making a GET request to the Protocol endpoint");
                        Graph g = new Graph();
                        endpoint.LoadGraph(g, graphUri);
                        if (verbose) Console.Error.WriteLine("soh: Received a Graph with " + g.Triples.Count + " Triples");

                        //Use users choice of output format otherwise RDF/XML
                        MimeTypeDefinition definition = null;
                        if (arguments.ContainsKey("accept"))
                        {
                            definition = MimeTypesHelper.GetDefinitions(arguments["accept"]).FirstOrDefault(d => d.CanWriteRdf);
                        }

                        if (definition != null)
                        {
                            Console.OutputEncoding = definition.Encoding;
                            IRdfWriter writer = definition.GetRdfWriter();
                            writer.Save(g, new StreamWriter(Console.OpenStandardOutput(), definition.Encoding));
                        }
                        else
                        {
                            if (arguments.ContainsKey("accept") && verbose) Console.Error.WriteLine("soh: Warning: You wanted output in format '" + arguments["accept"] + "' but dotNetRDF does not support this format so RDF/XML will be returned instead");

                            RdfXmlWriter rdfXmlWriter = new RdfXmlWriter();
                            rdfXmlWriter.Save(g, new StreamWriter(Console.OpenStandardOutput(), Encoding.UTF8));
                        }

                        break;

                    case "HEAD":
                        if (arguments.ContainsKey("$4"))
                        {
                            Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the head method");
                            Environment.Exit(-1);
                            return;
                        }

                        if (verbose) Console.Error.WriteLine("soh: Making a HEAD request to the Protocol endpoint");

                        bool exists = endpoint.GraphExists(graphUri);
                        Console.WriteLine(exists.ToString().ToLower());
                        break;

                    case "PUT":
                        //Parse in the Graph to be PUT first
                        if (arguments.ContainsKey("$4") && !arguments["$4"].Equals(String.Empty))
                        {
                            dataFile = arguments["$4"];
                        }
                        else
                        {
                            Console.Error.WriteLine("soh: Error: The file argument for protocol mode is required when using the put method");
                            Environment.Exit(-1);
                            return;
                        }
                        Graph toPut = new Graph();
                        FileLoader.Load(toPut, dataFile);
                        toPut.BaseUri = graphUri;

                        if (verbose)
                        {
                            Console.Error.WriteLine("soh: Graph to be uploaded has " + toPut.Triples.Count + " Triples");
                            Console.Error.WriteLine("soh: Making a PUT request to the Protocol endpoint");
                        }

                        endpoint.SaveGraph(toPut);
                        Console.WriteLine("soh: Graph saved to Protocol endpoint OK");
                        break;

                    case "POST":
                        //Parse in the Graph to be PUT first
                        if (arguments.ContainsKey("$4") && !arguments["$4"].Equals(String.Empty))
                        {
                            dataFile = arguments["$4"];
                        }
                        else
                        {
                            Console.Error.WriteLine("soh: Error: The file argument for protocol mode is required when using the post method");
                            Environment.Exit(-1);
                            return;
                        }
                        Graph toPost = new Graph();
                        FileLoader.Load(toPost, dataFile);

                        if (verbose)
                        {
                            Console.Error.WriteLine("soh: Graph to be uploaded has " + toPost.Triples.Count + " Triples");
                            Console.Error.WriteLine("soh: Making a POST request to the Protocol endpoint");
                        }

                        endpoint.UpdateGraph(graphUri, toPost.Triples, null);
                        Console.WriteLine("soh: Graph updated to Protocol endpoint OK");
                        break;

                    case "DELETE":
                        if (arguments.ContainsKey("$4"))
                        {
                            Console.Error.WriteLine("soh: Error: Optional file argument for protocol mode is not permitted with the head method");
                            Environment.Exit(-1);
                            return;
                        }
                        endpoint.DeleteGraph(graphUri);
                        Console.WriteLine("soh: Graph deleted from Protocol endpoint OK");
                        break;

                    default:
                        Console.Error.WriteLine("soh: Error: " + method + " is not a HTTP Method supported by this tool");
                        Environment.Exit(-1);
                        return;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("soh: Error: Error processing HTTP Protocol request");
                Console.Error.WriteLine(ex.Message);
                while (ex.InnerException != null)
                {
                    Console.Error.WriteLine();
                    Console.Error.WriteLine(ex.InnerException.Message);
                    Console.Error.WriteLine(ex.InnerException.StackTrace);
                    ex = ex.InnerException;
                }
                Environment.Exit(-1);
                return;
            }
        }