public StarDogLinkedDataSource(string uri, string db, Credential cred)
 {
     root                       = new Graph();
     theConnector               = new StardogConnector(uri, db, cred.User, cred.Pass);
     Options.InternUris         = false;
     Options.FullTripleIndexing = false;
 }
 public void Init()
 {
     _stardogGraphConnector = new StardogConnector(_sdConnData.Url, _sdConnData.StoreId, _sdConnData.User, _sdConnData.Pass);
     _repository            = new PersistentTripleStore(_stardogGraphConnector);
     _rdf4jMapper           = new DotNetRdfMapper();
     _logger.LogInformation("[CONFIG] The triple store repository configured correctly.");
 }
Esempio n. 3
0
        public IEnumerable <Provenance> Get(string title)
        {
            using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin"))
            {
                SparqlResultSet provResults = dog.Query(
                    "SELECT distinct ?provenanceLabel ?location ?dateAcquired ?ownerLabel ?dispayOrder WHERE  {" +
                    "?artwork a dbo:Artwork ." +
                    "?artwork rdfs:label ?label . " +
                    "?artwork :provenance ?provenance ." +
                    "?provenance :dateAcquired ?dateAcquired ." +
                    "?provenance rdfs:label ?provenanceLabel ." +
                    "?provenance schema:location ?city ." +
                    "?city rdfs:label ?location ." +
                    "?provenance gvp:displayOrder ?dispayOrder." +
                    "?provenance gvp:ulan2779_owned_by ?owner. " +
                    "?owner rdfs:label ?ownerLabel. " +
                    "FILTER regex(str(?label), \"" + title + "\") ." +
                    "FILTER(LANG(?ownerLabel) = \"\" || LANGMATCHES(LANG(?ownerLabel), \"en\")) ." +
                    "FILTER(lang(?location) = \"en\")} " +
                    "ORDER BY ASC(xsd:integer(?dispayOrder))") as SparqlResultSet;

                var provenance = provResults?
                                 .Select(x => new Provenance(x))
                                 .GroupBy(x => x.DispayOrder, (key, g) => g.OrderBy(e => e.DispayOrder).First());
                return(provenance);
            }
        }
Esempio n. 4
0
        // GET api/<controller>?title="any"
        public Artwork Get(string title)
        {
            using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin"))
            {
                SparqlResultSet artworkResults = dog.Query(
                    "SELECT distinct ?label ?abstract ?depiction ?museumlabel ?authorLabel WHERE {" +
                    "?artwork a dbo:Artwork ." +
                    "?artwork rdfs:label ?label . " +
                    "?artwork dbo:abstract ?abstract ." +
                    "?artwork foaf:depiction ?depiction ." +
                    "?artwork dbo:author ?author ." +
                    "?author foaf:name ?authorLabel ." +
                    "?artwork dbo:museum ?museum ." +
                    "?museum rdfs:label ?museumlabel ." +
                    "FILTER regex(str(?label), \"" + title + "\")" +
                    "FILTER(lang(?museumlabel) = \"en\") ." +
                    "FILTER(lang(?abstract) = \"en\")}") as SparqlResultSet;

                if (!artworkResults.Any())
                {
                    return(null);
                }

                var result = artworkResults[0];
                return(new Artwork(
                           result.Value("label").ToString(),
                           result.Value("museumlabel").ToString(),
                           result.Value("abstract").ToString(),
                           result.Value("depiction").ToString(),
                           result.Value("authorLabel").ToString()));
            }
        }
Esempio n. 5
0
        public void Initialise()
        {
            Dictionary <string, string> configs   = AppHelper.ReadConfigs();
            StardogReasoningMode        reasoning = StardogReasoningMode.QL;

            Enum.TryParse(configs[AppHelper.StardogReasoningMode], out reasoning);
            Context = new StardogConnector(configs[AppHelper.Server], configs[AppHelper.DbName], reasoning,
                                           configs[AppHelper.Username], configs[AppHelper.Password]);
        }
        /// <inheritdoc cref="ITransaction"/>
        public StardogTransaction(StardogConnector connector)
        {
            _connector = connector;
#if !NET35
            _connector.Begin(true);
#else
            _connector.Begin();
#endif
            IsActive = true;
        }
Esempio n. 7
0
        public List <ProductType> PopulateProducts(StardogConnector context)
        {
            var factory         = new Factory();
            var productTypeList = new List <ProductType>();

            var resultsQuery =
                context.Query(
                    "PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#>SELECT ?s WHERE {?s rdfs:subClassOf <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#Type> .}")
                as SparqlResultSet;

            if (resultsQuery != null)
            {
                resultsQuery.Results.ForEach(item =>
                {
                    var link          = item["s"];
                    var productResult = context.Query(
                        "PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#>SELECT ?s WHERE {?s rdfs:subClassOf <" +
                        link.ToString() + "> .}") as SparqlResultSet;
                    if (productResult != null && productResult.Results.Count > 2)
                    {
                        var product = factory.CreateProductTypes(productResult.Results, link);
                        if (product != null)
                        {
                            productTypeList.Add(product);
                        }
                    }
                });
            }

            foreach (var productType in productTypeList)
            {
                foreach (var subCategory in productType.SubCategories)
                {
                    var query = context.Query("SELECT * WHERE { ?subject rdfs:subClassOf <" + subCategory.URI + "> . ?instance a ?subject . }") as SparqlResultSet;
                    subCategory.Products = new List <ProductInstance>();
                    if (query != null)
                    {
                        foreach (var res in query.Results)
                        {
                            if (res["instance"].ToString().ToLower() != subCategory.URI.ToLower())
                            {
                                subCategory.Products.Add(new ProductInstance
                                {
                                    URI  = res["instance"].ToString(),
                                    Name = res["instance"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length)
                                });
                            }
                        }
                    }
                }
            }
            return(productTypeList);
        }
Esempio n. 8
0
 public static StardogConnector GetConnector(StardogServerDetails details)
 {
     if (connector == null)
     {
         lock (connectorLock)
             if (connector == null)
             {
                 connector = new StardogConnector(details.URI, details.KnowledgeBase, details.UserName, details.Password);
             }
     }
     return(connector);
 }
        // GET api/<controller>
        public IEnumerable <Artist> Get()
        {
            using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin"))
            {
                SparqlResultSet artistsResults = dog.Query(
                    "SELECT distinct ?label ?abstract WHERE {" +
                    "?person rdf:type dbo:Artist ." +
                    "?person rdfs:label ?label . " +
                    "?person dbo:abstract ?abstract ." +
                    "FILTER(lang(?abstract) = 'en') ." +
                    "FILTER(lang(?label) = \"en\") }") as SparqlResultSet;

                var artists = artistsResults?.Select(x => new Artist(x));
                return(artists);
            }
        }
Esempio n. 10
0
        private StardogConnector getConnector(Session session)
        {
            checkDetailsPresent(session);
            string serverToUse = (session.StardogServerDetails.StardogServer == null) ? server : session.StardogServerDetails.StardogServer.ToString();
            //serverToUse = serverToUse.Replace(@"http://","");
            //serverToUse = serverToUse.Replace(@"/", "");
            string dbToUse = string.IsNullOrEmpty(session.StardogServerDetails.StardogDB) ? datastore : session.StardogServerDetails.StardogDB;

            StardogConnector theConnector = new StardogConnector(
                serverToUse,
                dbToUse,
                session.StardogServerDetails.StardogUserName,
                session.StardogServerDetails.StardogPassword
                );

            return(theConnector);
        }
        // GET api/<controller>?artist="any"
        public IEnumerable <Artwork> Get(string artist)
        {
            using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin"))
            {
                SparqlResultSet artworkResults = dog.Query(
                    "SELECT distinct ?label ?depiction ?abstract WHERE {" +
                    "?artwork a dbo:Artwork ." +
                    "?artwork rdfs:label ?label . " +
                    "?artwork dbo:abstract ?abstract ." +
                    "?artwork foaf:depiction ?depiction ." +
                    "?artwork dbo:author ?author ." +
                    "?author foaf:name ?authorLabel ." +
                    "FILTER regex(str(?authorLabel), \"" + artist + "\")" +
                    "FILTER(lang(?label) = \"en\") ." +
                    "FILTER(lang(?abstract) = \"en\")}") as SparqlResultSet;

                var artworks = artworkResults?.Select(x => new Artwork(x));
                return(artworks);
            }
        }
Esempio n. 12
0
        public void ExecuteInsert(IEnumerable <MiddlewareParameter> parameters, Session session)
        {
            StardogConnector          theConnector = getConnector(session);
            SparqlParameterizedString query        = getQuery(parameters, sparql);

            try
            {
#if DEBUG
                Console.WriteLine(query.ToString());
#endif
                theConnector.Update(query.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Querry Failed -------------------------------------");
                Console.WriteLine(query);
                Console.WriteLine("----------------------------");
                Console.WriteLine(ex);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Executes the referencing queries
        /// </summary>
        private static void AddReferenceGraph()
        {
            Log("Executing AddReferenceGraph()");
            Log("Connecting to Movie store...");
            var movieStore = new StardogConnector(settings.ServerIp, MoviesDbName, settings.Login, settings.Password);

            movieStore.Timeout = int.MaxValue;
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/references#");

            Log("Inserting film references...");
            movieStore.Query(File.ReadAllText(ReferenceFilmsQuery));

            Log("Inserting Song references...");
            movieStore.Query(File.ReadAllText(ReferenceSongsQuery));

            Log("Inserting Artists references...");
            movieStore.Query(File.ReadAllText(ReferenceArtistsQuery));

            Log("Inserting Chart song references...");
            movieStore.Query(File.ReadAllText(ReferenceChartsDe1Query));
        }
        // GET api/<controller>/?artistName="any"
        public IEnumerable <Artwork> Get(string artistName)
        {
            using (StardogConnector dog = new StardogConnector(StarDogUrl, DbName, "admin", "admin"))
            {
                SparqlResultSet artworksResults = dog.Query(
                    "SELECT distinct ?label ?abstract?depiction ?labelArtwork WHERE {" +
                    "?person rdf:type dbo:Artist ." +
                    "?person rdfs:label ?label ." +
                    "?artwork a dbo:Artwork ." +
                    "?artwork foaf:depiction ?depiction ." +
                    "?person dbo:abstract ?abstract ." +
                    "?artwork dbo:author ?person ." +
                    "?artwork rdfs:label ?labelArtwork . " +
                    " FILTER(lang(?abstract) = 'en') ." +
                    "FILTER(lang(?label) = 'en') ." +
                    "FILTER regex(str(?labelArtwork),   \"" + artistName + "\")" +
                    "FILTER(lang(?labelArtwork) = 'en') }")
                                                  as SparqlResultSet;

                var artworks = artworksResults?.Select(x => new Artwork(x));
                return(artworks);
            }
        }
        /// <summary>
        /// Connects to a stardog store using the entered data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            var ip       = this.IpTextBox.Text;
            var db       = this.DbTextBox.Text;
            var login    = this.LoginTextBox.Text;
            var password = this.PasswordTextbox.Password;

            if (string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(db) || string.IsNullOrEmpty(login) ||
                string.IsNullOrEmpty(password))
            {
                MessageBox.Show(this, "Missing informations!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                this.connector = new StardogConnector(ip, db, login, password);
                this.ExecuteButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Esempio n. 16
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)
            {
#if !NO_SYNC_HTTP
            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;
#endif

            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;

#if !NO_SYNC_HTTP
            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;
#endif

            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;

#if !NO_SYNC_HTTP
            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;
#endif

            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;

#if !NO_SYNC_HTTP
            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(UriFactory.Create(server), defGraphs, namedGraphs), loadMode);
                    }
                    else
                    {
                        manager = new SparqlConnector(UriFactory.Create(server), loadMode);
                    }
                }
                break;

            case SparqlHttpProtocol:
                //Get the Service URI
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                manager = new SparqlHttpProtocolConnector(UriFactory.Create(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;
#endif
            }

#if !NO_PROXY
            //Check whether this is a proxyable manager and if we need to load proxy settings
            if (manager is BaseHttpConnector)
            {
                INode proxyNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyProxy));
                if (proxyNode != null)
                {
                    temp = ConfigurationLoader.LoadObject(g, proxyNode);
                    if (temp is WebProxy)
                    {
                        ((BaseHttpConnector)manager).Proxy = (WebProxy)temp;
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load Generic Manager identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:proxy property pointed to an Object which could not be loaded as an object of the required type WebProxy");
                    }
                }
            }
#endif

            obj = manager;
            return(manager != null);
        }
        /// <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)
        {
            IStorageProvider          storageProvider = null;
            IStorageServer            storageServer   = null;
            SparqlConnectorLoadMethod loadMode;

            obj = null;

            String server, user, pwd, store, catalog, loadModeRaw;

            Object temp;
            INode  storeObj;

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

            switch (targetType.FullName)
            {
            case AllegroGraph:
                // Get the Server, Catalog and Store
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                catalog = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(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)
                {
                    storageProvider = new AllegroGraphConnector(server, catalog, store, user, pwd);
                }
                else
                {
                    storageProvider = new AllegroGraphConnector(server, catalog, store);
                }
                break;

            case AllegroGraphServer:
                // Get the Server, Catalog and User Credentials
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                catalog = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyCatalog)));
                ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                if (user != null && pwd != null)
                {
                    storageServer = new AllegroGraphServer(server, catalog, user, pwd);
                }
                else
                {
                    storageServer = new AllegroGraphServer(server, catalog);
                }
                break;

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

            case Dydra:
                throw new DotNetRdfConfigurationException("DydraConnector is no longer supported by dotNetRDF and is considered obsolete");

            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, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEnableUpdates)), true);
                storageProvider = new FourStoreConnector(server, enableUpdates);
                break;

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

            case InMemory:
                // Get the Dataset/Store
                INode datasetObj = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingDataset)));
                if (datasetObj != null)
                {
                    temp = ConfigurationLoader.LoadObject(g, datasetObj);
                    if (temp is ISparqlDataset)
                    {
                        storageProvider = 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, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingStore)));
                    if (storeObj != null)
                    {
                        temp = ConfigurationLoader.LoadObject(g, storeObj);
                        if (temp is IInMemoryQueryableStore)
                        {
                            storageProvider = 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
                        storageProvider = new InMemoryManager();
                    }
                }
                break;

            case ReadOnly:
                // Get the actual Manager we are wrapping
                storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider);
                temp     = ConfigurationLoader.LoadObject(g, storeObj);
                if (temp is IStorageProvider)
                {
                    storageProvider = new ReadOnlyConnector((IStorageProvider)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 IStorageProvider interface");
                }
                break;

            case ReadOnlyQueryable:
                // Get the actual Manager we are wrapping
                storeObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider);
                temp     = ConfigurationLoader.LoadObject(g, storeObj);
                if (temp is IQueryableStorage)
                {
                    storageProvider = new QueryableReadOnlyConnector((IQueryableStorage)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 IQueryableStorage 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)
                {
                    storageProvider = (IStorageProvider)Activator.CreateInstance(targetType, new Object[] { server, store, user, pwd });
                }
                else
                {
                    storageProvider = (IStorageProvider)Activator.CreateInstance(targetType, new Object[] { server, store });
                }
                break;

            case SesameServer:
                // Get the Server and User Credentials
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                if (user != null && pwd != null)
                {
                    storageServer = new SesameServer(server, user, pwd);
                }
                else
                {
                    storageServer = new SesameServer(server);
                }
                break;

            case Sparql:
                // Get the Endpoint URI or the Endpoint
                server = ConfigurationLoader.GetConfigurationString(g, objNode, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryEndpointUri)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpointUri)) });

                // What's the load mode?
                loadModeRaw = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyLoadMode)));
                loadMode    = SparqlConnectorLoadMethod.Construct;
                if (loadModeRaw != null)
                {
                    try
                    {
                        loadMode = (SparqlConnectorLoadMethod)Enum.Parse(typeof(SparqlConnectorLoadMethod), loadModeRaw);
                    }
                    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, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryEndpoint)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpoint)) });
                    if (endpointObj == null)
                    {
                        return(false);
                    }
                    temp = ConfigurationLoader.LoadObject(g, endpointObj);
                    if (temp is SparqlRemoteEndpoint)
                    {
                        storageProvider = 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, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDefaultGraphUri)))
                                                  where def.NodeType == NodeType.Uri
                                                  select((IUriNode)def).Uri;

                    IEnumerable <Uri> namedGraphs = from named in ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyNamedGraphUri)))
                                                    where named.NodeType == NodeType.Uri
                                                    select((IUriNode)named).Uri;

                    if (defGraphs.Any() || namedGraphs.Any())
                    {
                        storageProvider = new SparqlConnector(new SparqlRemoteEndpoint(UriFactory.Create(server), defGraphs, namedGraphs), loadMode);
                    }
                    else
                    {
                        storageProvider = new SparqlConnector(UriFactory.Create(server), loadMode);
                    }
                }
                break;

            case ReadWriteSparql:
                SparqlRemoteEndpoint       queryEndpoint;
                SparqlRemoteUpdateEndpoint updateEndpoint;

                // Get the Query Endpoint URI or the Endpoint
                server = ConfigurationLoader.GetConfigurationString(g, objNode, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateEndpointUri)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpointUri)) });

                // What's the load mode?
                loadModeRaw = ConfigurationLoader.GetConfigurationString(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyLoadMode)));
                loadMode    = SparqlConnectorLoadMethod.Construct;
                if (loadModeRaw != null)
                {
                    try
                    {
                        loadMode = (SparqlConnectorLoadMethod)Enum.Parse(typeof(SparqlConnectorLoadMethod), loadModeRaw);
                    }
                    catch
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the ReadWriteSparqlConnector 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, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyQueryEndpoint)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpoint)) });
                    if (endpointObj == null)
                    {
                        return(false);
                    }
                    temp = ConfigurationLoader.LoadObject(g, endpointObj);
                    if (temp is SparqlRemoteEndpoint)
                    {
                        queryEndpoint = (SparqlRemoteEndpoint)temp;
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the ReadWriteSparqlConnector identified by the Node '" + objNode.ToString() + "' as the value given for the property dnr:queryEndpoint/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, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyDefaultGraphUri)))
                                                  where def.NodeType == NodeType.Uri
                                                  select((IUriNode)def).Uri;

                    IEnumerable <Uri> namedGraphs = from named in ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyNamedGraphUri)))
                                                    where named.NodeType == NodeType.Uri
                                                    select((IUriNode)named).Uri;

                    if (defGraphs.Any() || namedGraphs.Any())
                    {
                        queryEndpoint = new SparqlRemoteEndpoint(UriFactory.Create(server), defGraphs, namedGraphs);
                        ;
                    }
                    else
                    {
                        queryEndpoint = new SparqlRemoteEndpoint(UriFactory.Create(server));
                    }
                }

                // Find the Update Endpoint or Endpoint URI
                server = ConfigurationLoader.GetConfigurationString(g, objNode, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateEndpointUri)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpointUri)) });

                if (server == null)
                {
                    INode endpointObj = ConfigurationLoader.GetConfigurationNode(g, objNode, new INode[] { g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUpdateEndpoint)), g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyEndpoint)) });
                    if (endpointObj == null)
                    {
                        return(false);
                    }
                    temp = ConfigurationLoader.LoadObject(g, endpointObj);
                    if (temp is SparqlRemoteUpdateEndpoint)
                    {
                        updateEndpoint = (SparqlRemoteUpdateEndpoint)temp;
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the ReadWriteSparqlConnector identified by the Node '" + objNode.ToString() + "' as the value given for the property dnr:updateEndpoint/dnr:endpoint points to an Object which cannot be loaded as an object which is of the type SparqlRemoteUpdateEndpoint");
                    }
                }
                else
                {
                    updateEndpoint = new SparqlRemoteUpdateEndpoint(UriFactory.Create(server));
                }
                storageProvider = new ReadWriteSparqlConnector(queryEndpoint, updateEndpoint, loadMode);
                break;

            case SparqlHttpProtocol:
                // Get the Service URI
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                storageProvider = new SparqlHttpProtocolConnector(UriFactory.Create(server));
                break;

            case Stardog:
            case StardogV1:
            case StardogV2:
            case StardogV3:
                // 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, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyLoadMode)));
                if (mode != null)
                {
                    try
                    {
                        reasoning = (StardogReasoningMode)Enum.Parse(typeof(StardogReasoningMode), mode, true);
                    }
                    catch
                    {
                        reasoning = StardogReasoningMode.None;
                    }
                }

                if (user != null && pwd != null)
                {
                    switch (targetType.FullName)
                    {
                    case StardogV1:
                        storageProvider = new StardogV1Connector(server, store, reasoning, user, pwd);
                        break;

                    case StardogV2:
                        storageProvider = new StardogV2Connector(server, store, reasoning, user, pwd);
                        break;

                    case StardogV3:
                        storageProvider = new StardogV3Connector(server, store, user, pwd);
                        break;

                    case Stardog:
                    default:
                        storageProvider = new StardogConnector(server, store, user, pwd);
                        break;
                    }
                }
                else
                {
                    switch (targetType.FullName)
                    {
                    case StardogV1:
                        storageProvider = new StardogV1Connector(server, store, reasoning);
                        break;

                    case StardogV2:
                        storageProvider = new StardogV2Connector(server, store, reasoning);
                        break;

                    case StardogV3:
                        storageProvider = new StardogV3Connector(server, store);
                        break;

                    case Stardog:
                    default:
                        storageProvider = new StardogConnector(server, store);
                        break;
                    }
                }
                break;

            case StardogServer:
            case StardogServerV1:
            case StardogServerV2:
            case StardogServerV3:
                // Get the Server and User Credentials
                server = ConfigurationLoader.GetConfigurationString(g, objNode, propServer);
                if (server == null)
                {
                    return(false);
                }
                ConfigurationLoader.GetUsernameAndPassword(g, objNode, true, out user, out pwd);

                if (user != null && pwd != null)
                {
                    switch (targetType.FullName)
                    {
                    case StardogServerV1:
                        storageServer = new StardogV1Server(server, user, pwd);
                        break;

                    case StardogServerV2:
                        storageServer = new StardogV2Server(server, user, pwd);
                        break;

                    case StardogServerV3:
                        storageServer = new StardogV3Server(server, user, pwd);
                        break;

                    case StardogServer:
                    default:
                        storageServer = new StardogServer(server, user, pwd);
                        break;
                    }
                }
                else
                {
                    switch (targetType.FullName)
                    {
                    case StardogServerV1:
                        storageServer = new StardogV1Server(server);
                        break;

                    case StardogServerV2:
                        storageServer = new StardogV2Server(server);
                        break;

                    case StardogServerV3:
                        storageServer = new StardogV3Server(server);
                        break;

                    case StardogServer:
                    default:
                        storageServer = new StardogServer(server);
                        break;
                    }
                }
                break;
            }

            // Set the return object if one has been loaded
            if (storageProvider != null)
            {
                obj = storageProvider;
            }
            else if (storageServer != null)
            {
                obj = storageServer;
            }

            // Check whether this is a standard HTTP manager and if so load standard configuration
            if (obj is BaseHttpConnector)
            {
                BaseHttpConnector connector = (BaseHttpConnector)obj;

                int timeout = ConfigurationLoader.GetConfigurationInt32(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyTimeout)), 0);
                if (timeout > 0)
                {
                    connector.Timeout = timeout;
                }
                INode proxyNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyProxy)));
                if (proxyNode != null)
                {
                    temp = ConfigurationLoader.LoadObject(g, proxyNode);
                    if (temp is IWebProxy)
                    {
                        connector.Proxy = (IWebProxy)temp;
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load storage provider/server identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:proxy property pointed to an Object which could not be loaded as an object of the required type WebProxy");
                    }
                }
            }

            return(obj != null);
        }
Esempio n. 18
0
 public SecService(StardogConnector _context)
 {
     bingContainer = new BingSearchContainer(new Uri(rootUrl));
     Context       = _context;
 }
Esempio n. 19
0
 /// <summary>
 /// Create a new instance of the <c>StardogStore</c> class.
 /// </summary>
 /// <param name="host">URL of the host to connect to.</param>
 /// <param name="username">Username to be used when connecting.</param>
 /// <param name="password">Password to be used when connecting.</param>
 /// <param name="storeId">Knowledge base / database identifier.</param>
 public StardogStore(string host, string username, string password, string storeId)
 {
     _connector  = new StardogConnector(host, storeId, username, password);
     _rdfHandler = new StardogRdfHandler();
 }
Esempio n. 20
0
        /// <summary>
        /// This executes the saved SPARQL against the passed server and with the passed parameters
        /// </summary>
        /// <param name="parameters">Parameters to pass on to the SPARQL query. Can be any of the types that extend MiddlewareParameter</param>
        /// <param name="session">This holds server details, including username and password</param>
        /// <returns></returns>
        public IEnumerable <MiddlewareParameter> ExecuteSelect(IEnumerable <MiddlewareParameter> parameters, Session session, ParameterTypeEnum returnTypeWanted)
        {
            StardogConnector          theConnector = getConnector(session);
            SparqlParameterizedString query        = getQuery(parameters, sparql);

            try
            {
                IEnumerable <SparqlResult> queryResult = theConnector.Query(query.ToString()) as SparqlResultSet;//actually fire the query
                if (queryResult.Count <SparqlResult>() == 0)
                {
                    return(Enumerable.Empty <MiddlewareParameter>());//Don't do unnecessary processing, but returning null causes crashes further up
                }
                List <MiddlewareParameter> Result = new List <MiddlewareParameter>();
                bool linkParams = returnTypeWanted.HasFlag(ParameterTypeEnum.Multivalue);
                //I stay null if not doing multivalue requests
                MiddlewareParameter <List <MiddlewareParameter> > multiValue = null;
                int lineNumber = 1;
                foreach (SparqlResult res in queryResult)//for each line
                {
                    if (linkParams)
                    {
                        multiValue            = new MiddlewareParameter <List <MiddlewareParameter> >(MiddlewareParameterDirection.Out);
                        multiValue.ParamName  = lineNumber++.ToString();
                        multiValue.ParamValue = new List <MiddlewareParameter>();
                        returnTypeWanted     &= ~ParameterTypeEnum.Multivalue;   //The effect of this is allowing us to switch on the return type wanted
                    }
                    foreach (KeyValuePair <string, INode> parameterValue in res) //each parameter
                    {
                        if (linkParams)
                        {
                            handleLanguageTags(multiValue, parameterValue);
                        }
                        MiddlewareParameter toAdd = null;
                        switch (returnTypeWanted)
                        {
                        case ParameterTypeEnum.AsSource:
                            toAdd = createAsPerSourceType(parameterValue);
                            break;

                        case ParameterTypeEnum.String:
                            toAdd = createStringParameter(parameterValue);
                            break;

                        case ParameterTypeEnum.ByteArray:
                            toAdd = createByteParameter(parameterValue);
                            break;

                        case ParameterTypeEnum.Uri:
                            toAdd = createUriParameter(parameterValue);
                            break;

                        default:
                            throw new ArgumentException("Invalid return parameter type specified");
                        }
                        if ((toAdd != null) && (!linkParams))
                        {
                            Result.Add(toAdd);
                        }
                        else if (linkParams)
                        {
                            multiValue.ParamValue.Add(toAdd);
                        }
                    }
                    if (linkParams)
                    {
                        Result.Add(multiValue);
                    }
                }

                return(Result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(query.CommandText);
                throw ex;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Merges the graphs from IMDb, LastFM and Charts_de into a new database
        /// </summary>
        private static void MergeGraphs()
        {
            Log("Executing MergeGraphs()");
            Log("Connecting to Movie store...");
            var movieStore = new StardogConnector(settings.ServerIp, MoviesDbName, settings.Login, settings.Password);

            movieStore.Timeout = int.MaxValue;

            #region Tunefind
            Log("Connecting to Tunefind store...");
            var tuneFindStore = new StardogConnector(settings.ServerIp, TuneFindDbName, settings.Login, settings.Password);
            var tuneFindGraph = new Graph();
            tuneFindGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/tunefind#");
            tuneFindStore.LoadGraph(tuneFindGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/tunefind#");
            movieStore.SaveGraph(tuneFindGraph);
            #endregion

            #region IMDB
            Log("Connecting to IMDB store...");
            var imdbStore = new StardogConnector(settings.ServerIp, ImdbDbName, settings.Login, settings.Password);
            var imdbGraph = new Graph();
            imdbGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/imdb#");
            imdbStore.LoadGraph(imdbGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/imdb#");
            movieStore.SaveGraph(imdbGraph);
            #endregion

            #region LastFM
            Log("Connecting to LastFm store...");
            var lastFmStore = new StardogConnector(settings.ServerIp, LastFmDbName, settings.Login, settings.Password);
            var lastFmGraph = new Graph();
            lastFmGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/lastfm#");
            lastFmStore.LoadGraph(lastFmGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/lastfm#");
            movieStore.SaveGraph(lastFmGraph);
            #endregion

            #region Charts_de
            Log("Connecting to Chart_De store...");
            var chartsDeStore = new StardogConnector(settings.ServerIp, ChartsDeDbName, settings.Login, settings.Password);
            var chartsDeGraph = new Graph();
            chartsDeGraph.BaseUri = new Uri("http://imn.htwk-leipzig.de/pbachman/ontologies/charts_de#");
            chartsDeStore.LoadGraph(chartsDeGraph, string.Empty);

            Log("Uploading Graph...");
            movieStore.DeleteGraph("http://imn.htwk-leipzig.de/pbachman/ontologies/charts_de#");
            movieStore.SaveGraph(chartsDeGraph);
            #endregion

            Log("Merging Graphs...");
            var movieGraph = SetupMovieGraph();
            movieGraph.Merge(tuneFindGraph);
            movieGraph.Merge(imdbGraph);
            movieGraph.Merge(lastFmGraph);
            movieGraph.Merge(chartsDeGraph);

            Log("Writing Graph...");
            var writer = new CompressingTurtleWriter(TurtleSyntax.W3C);
            writer.Save(movieGraph, @"01_Movies.ttl");
        }
 public StarDogLinkedDataSource(string uri, string db, Credential cred)
 {
     root         = new Graph();
     theConnector = new StardogConnector(uri, db, cred.User, cred.Pass);
 }
Esempio n. 23
0
 public void InitializeContext(StardogConnector c)
 {
     myContext = c;
 }
Esempio n. 24
0
        public void PopulateProductsInfoBySubcategory(StardogConnector context, SubCategory s)
        {
            var queryUrl = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?url WHERE { ?ind t:Has_URL ?url. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryUrl != null)
            {
                foreach (var res in queryUrl.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        p.Url = res["url"].ToString();
                    }
                }
            }
            var queryBuyUrl = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?url WHERE { ?ind t:Has_buy_url ?url. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryBuyUrl != null)
            {
                foreach (var res in queryBuyUrl.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        p.BuyUrl = res["url"].ToString();
                    }
                }
            }
            var queryColours = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?c WHERE { ?ind t:Has_colour ?c. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryColours != null)
            {
                foreach (var res in queryColours.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        if (p.Colour == null)
                        {
                            p.Colour = new List <string>();
                        }
                        p.Colour.Add(res["c"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length));
                    }
                }
            }
            var querySeason = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?s WHERE { ?ind t:Is_from_season ?s. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (querySeason != null)
            {
                foreach (var res in querySeason.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        if (p.Season == null)
                        {
                            p.Season = new List <string>();
                        }
                        p.Season.Add(res["s"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length));
                    }
                }
            }
            var queryBrand = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?s WHERE { ?ind t:Is_from ?s. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryBrand != null)
            {
                foreach (var res in queryBrand.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        if (p.Brand == null)
                        {
                            p.Brand = new List <string>();
                        }
                        p.Brand.Add(res["s"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length));
                    }
                }
            }
            var queryStyle = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?s WHERE { ?ind t:Has_style ?s. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryStyle != null)
            {
                foreach (var res in queryStyle.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        if (p.Style == null)
                        {
                            p.Style = new List <string>();
                        }
                        p.Style.Add(res["s"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length));
                    }
                }
            }
            var queryGender = context.Query("PREFIX t: <http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#> SELECT ?ind ?s WHERE { ?ind t:For_gender ?s. ?ind rdf:type t:" + s.SubCategoryName + " } ") as SparqlResultSet;

            if (queryGender != null)
            {
                foreach (var res in queryGender.Results)
                {
                    var p = s.Products.FirstOrDefault(f => f.URI.ToLower() == res["ind"].ToString().ToLower());
                    if (p != null)
                    {
                        if (p.Gender == null)
                        {
                            p.Gender = new List <string>();
                        }
                        p.Gender.Add(res["s"].ToString().Substring("http://www.semanticweb.org/bobo/ontologies/2015/0/Adriana#".Length));
                    }
                }
            }
        }