public string GraphToSerialization(VDS.RDF.IGraph model, object rdfFormat)
 {
     if (rdfFormat is VDS.RDF.IStoreWriter)
     {
         var ts = new VDS.RDF.TripleStore();
         ts.Add(model);
         return(VDS.RDF.Writing.StringWriter.Write(ts, (VDS.RDF.IStoreWriter)rdfFormat));
     }
     return(VDS.RDF.Writing.StringWriter.Write(model, (VDS.RDF.IRdfWriter)rdfFormat));
 }
        public HashSet <Triple> GraphToTriples(VDS.RDF.IGraph model)
        {
            HashSet <Triple> triples = new HashSet <Triple>();

            foreach (var statement in model.Triples)
            {
                triples.Add(StatementToTriple(statement));
            }

            return(triples);
        }
        public void RunBenchmark(Dictionary <string, string> filesContent)
        {
            foreach (var fileContentEntry in filesContent)
            {
                try
                {
                    VDS.RDF.IGraph deserializedModel = rdf4jSerializationHandler.DeserializeGraph(
                        fileContentEntry.Key,
                        fileContentEntry.Value,
                        RdfFormat.TURTLE);
                    HashSet <Triple> triples = rdf4jMapper.GraphToTriples(deserializedModel);

                    _hashingService.CalculateHash(triples);
                }
                catch (RdfSerializationException ex)
                {
                    throw new BenchmarkException("Exception: ", ex);
                }
                catch (CalculatingHashException ex)
                {
                    throw new BenchmarkException("Exception: ", ex);
                }
            }
        }
 public override void SaveToGraph(VDS.RDF.IGraph target, VDS.RDF.IUriNode provCreatingAction)
 {
     base.SaveToGraph(target, provCreatingAction);
 }
 /// <summary>
 /// Attempts to load an Object of the given type identified by the given Node and returned as the Type that this loader generates
 /// </summary>
 /// <param name="g">Configuration Graph</param>
 /// <param name="objNode">Object Node</param>
 /// <param name="targetType">Target Type</param>
 /// <param name="obj">Created Object</param>
 /// <returns>True if the loader succeeded in creating an Object</returns>
 /// <remarks>The Factory should not throw an error if some required configuration is missing as another factory further down the processing chain may still be able to create the object.  If the factory encounters errors and all the required configuration information is present then that error should be thrown i.e. class instantiation throws an error or a call to load an object that this object requires fails.</remarks>
 public bool TryLoadObject(VDS.RDF.IGraph g, VDS.RDF.INode objNode, Type targetType, out object obj)
 {
     obj = StorageWrapper.Storage;
     return(true);
 }
 /// <summary>
 /// Creates a new Store Graph Persistence Wrapper for Virtualized Nodes
 /// </summary>
 /// <param name="manager">Generic IO Manager</param>
 /// <param name="provider">Virtual RDF Provider</param>
 /// <param name="g">Graph with virtualized Nodes to wrap</param>
 /// <param name="graphUri">Graph URI (the URI the Graph will be persisted as)</param>
 /// <param name="writeOnly">Whether to operate in write-only mode</param>
 /// <remarks>
 /// <para>
 /// <strong>Note:</strong> In order to operate in write-only mode the <see cref="IStorageProvider">IStorageProvider</see> must support triple level updates indicated by it returning true to its <see cref="IStorageProvider.UpdateSupported">UpdateSupported</see> property and the Graph to be wrapped must be an empty Graph
 /// </para>
 /// </remarks>
 public StoreVirtualGraphPersistenceWrapper(VDS.RDF.Storage.IStorageProvider manager, IVirtualRdfProvider <TNodeID, TGraphID> provider, VDS.RDF.IGraph g, System.Uri graphUri, bool writeOnly)
     : base(manager, g, graphUri, writeOnly)
 {
     if (provider == null)
     {
         throw new ArgumentNullException("provider", "Cannot persist virtual nodes without a virtual RDF provider");
     }
     this._provider = provider;
 }
 private HashSet <Triple> GetTriplesFromSerializedModel(String serializedModel, RdfFormat rdfFormat)
 {
     VDS.RDF.IGraph deserializeModel = _rdf4jSerializationHandler.DeserializeGraph(serializedModel, rdfFormat);
     return(_rdf4jMapper.GraphToTriples(deserializeModel));
 }
Esempio n. 8
0
        public Response Pull(string scope, string app, string graph, Request request)
        {
            Response response = new Response();

            response.Level = StatusLevel.Success;

            Status status = new Status();

            status.Messages = new Messages();

            try
            {
                status.Identifier = String.Format("{0}.{1}", scope, app);

                InitializeScope(scope, app);

                if (_settings["ReadOnlyDataLayer"] != null && _settings["ReadOnlyDataLayer"].ToString().ToLower() == "true")
                {
                    string message = "Can not perform post on read-only data layer of [" + scope + "." + app + "].";
                    _logger.Error(message);

                    status.Level = StatusLevel.Error;
                    status.Messages.Add(message);
                }
                else
                {
                    InitializeDataLayer();

                    DateTime startTime = DateTime.Now;

                    #region move this portion to dotNetRdfEngine?
                    if (!request.ContainsKey("targetEndpointUri"))
                    {
                        throw new Exception("Target Endpoint Uri is required");
                    }

                    string targetEndpointUri = request["targetEndpointUri"];

                    if (!request.ContainsKey("targetGraphBaseUri"))
                    {
                        throw new Exception("Target graph uri is required");
                    }

                    string targetGraphBaseUri = request["targetGraphBaseUri"];
                    _settings["TargetGraphBaseUri"] = targetGraphBaseUri;

                    if (targetGraphBaseUri.ToLower() == "[default graph]")
                    {
                        targetGraphBaseUri = String.Empty;
                    }

                    SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(targetEndpointUri), targetGraphBaseUri);

                    if (request.ContainsKey("targetCredentials"))
                    {
                        string         targetCredentialsXML = request["targetCredentials"];
                        WebCredentials targetCredentials    = Utility.Deserialize <WebCredentials>(targetCredentialsXML, true);

                        if (targetCredentials.isEncrypted)
                        {
                            targetCredentials.Decrypt();
                        }

                        endpoint.SetCredentials(targetCredentials.GetNetworkCredential().UserName, targetCredentials.GetNetworkCredential().Password, targetCredentials.GetNetworkCredential().Domain);
                    }

                    string proxyHost       = _settings["ProxyHost"];
                    string proxyPort       = _settings["ProxyPort"];
                    string proxyCredsToken = _settings["ProxyCredentialToken"];

                    if (!String.IsNullOrEmpty(proxyHost) && !String.IsNullOrEmpty(proxyPort) && !String.IsNullOrEmpty(proxyCredsToken))
                    {
                        WebProxyCredentials proxyCreds = _settings.GetWebProxyCredentials();
                        endpoint.Proxy            = proxyCreds.GetWebProxy() as WebProxy;
                        endpoint.ProxyCredentials = proxyCreds.GetNetworkCredential();
                    }

                    VDS.RDF.IGraph resultGraph = endpoint.QueryWithResultGraph("CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}");
                    #endregion

                    if (resultGraph != null && resultGraph.Triples.Count > 0)
                    {
                        // call RdfProjectionEngine to fill data objects from a given graph
                        _projectionEngine = _kernel.Get <IProjectionLayer>("rdf");

                        System.Text.StringBuilder sb           = new System.Text.StringBuilder();
                        TextWriter textWriter                  = new StringWriter(sb);
                        VDS.RDF.Writing.RdfXmlWriter rdfWriter = new VDS.RDF.Writing.RdfXmlWriter();
                        rdfWriter.Save(resultGraph, textWriter);
                        XDocument xDocument = XDocument.Parse(sb.ToString());

                        if (xDocument != null && xDocument.Root != null)
                        {
                            _logger.Debug(xDocument.Root.ToString());
                            _dataObjects = _projectionEngine.ToDataObjects(graph, ref xDocument);

                            if (_dataObjects != null && _dataObjects.Count > 0)
                            {
                                status.Messages.Add("Query target endpoint completed successfully.");
                                status.Messages.Add(String.Format("Number of data objects created [{0}].", _dataObjects.Count));

                                // post data objects to data layer
                                response.Append(_dataLayer.Post(_dataObjects));

                                DateTime endTime  = DateTime.Now;
                                TimeSpan duration = endTime.Subtract(startTime);

                                status.Messages.Add(String.Format("Execution time [{0}:{1}.{2}] minutes.",
                                                                  duration.Minutes, duration.Seconds, duration.Milliseconds));
                            }
                            else
                            {
                                status.Messages.Add(string.Format("No data objects being created."));
                            }
                        }
                        else
                        {
                            throw new Exception("Facade document is empty.");
                        }
                    }
                    else
                    {
                        throw new Exception("Facade graph is empty.");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Error in Pull(): ", ex);

                status.Level = StatusLevel.Error;
                status.Messages.Add(string.Format("Error pulling graph: {0}", ex));
            }

            response.Append(status);
            return(response);
        }
Esempio n. 9
0
        public Response Pull(string projectName, string applicationName, string graphName, Request request)
        {
            Status status = new Status();

            status.Messages = new Messages();

            try
            {
                status.Identifier = String.Format("{0}.{1}", projectName, applicationName);

                InitializeScope(projectName, applicationName);
                InitializeDataLayer();

                DateTime startTime = DateTime.Now;

                if (!request.ContainsKey("targetEndpointUri"))
                {
                    throw new Exception("Target Endpoint Uri is required");
                }

                string targetEndpointUri = request["targetEndpointUri"];

                if (!request.ContainsKey("targetGraphBaseUri"))
                {
                    throw new Exception("Target graph uri is required");
                }

                string targetGraphBaseUri = request["targetGraphBaseUri"];
                _settings["TargetGraphBaseUri"] = targetGraphBaseUri;

                SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri(targetEndpointUri), targetGraphBaseUri);

                if (request.ContainsKey("targetCredentials"))
                {
                    string         targetCredentialsXML = request["targetCredentials"];
                    WebCredentials targetCredentials    = Utility.Deserialize <WebCredentials>(targetCredentialsXML, true);

                    if (targetCredentials.isEncrypted)
                    {
                        targetCredentials.Decrypt();
                    }

                    endpoint.SetCredentials(
                        targetCredentials.GetNetworkCredential().UserName,
                        targetCredentials.GetNetworkCredential().Password,
                        targetCredentials.GetNetworkCredential().Domain);
                }

                string proxyHost = _settings["ProxyHost"];
                string proxyPort = _settings["ProxyPort"];
                if (!String.IsNullOrEmpty(proxyHost) && !String.IsNullOrEmpty(proxyPort))
                {
                    WebProxy webProxy = new WebProxy(proxyHost, Int32.Parse(proxyPort));

                    WebProxyCredentials proxyCrendentials = _settings.GetWebProxyCredentials();
                    if (proxyCrendentials != null)
                    {
                        webProxy.Credentials = _settings.GetProxyCredential();
                    }

                    endpoint.SetProxyCredentials(proxyCrendentials.userName, proxyCrendentials.password, proxyCrendentials.domain);
                    endpoint.SetProxy(webProxy.Address);
                }

                String         query = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}";
                VDS.RDF.IGraph graph = endpoint.QueryWithResultGraph(query);

                System.Text.StringBuilder sb           = new System.Text.StringBuilder();
                TextWriter textWriter                  = new StringWriter(sb);
                VDS.RDF.Writing.RdfXmlWriter rdfWriter = new VDS.RDF.Writing.RdfXmlWriter();
                rdfWriter.Save(graph, textWriter);
                XDocument xDocument = XDocument.Parse(sb.ToString());

                // call RdfProjectionEngine to fill data objects from a given graph
                _projectionEngine = _kernel.Get <IProjectionLayer>("rdf");
                _dataObjects      = _projectionEngine.ToDataObjects(graphName, ref xDocument);

                // post data objects to data layer
                _dataLayer.Post(_dataObjects);

                DateTime endTime  = DateTime.Now;
                TimeSpan duration = endTime.Subtract(startTime);

                status.Messages.Add(string.Format("Graph [{0}] has been posted to legacy system successfully.", graphName));

                status.Messages.Add(String.Format("Execution time [{0}:{1}.{2}] minutes.",
                                                  duration.Minutes, duration.Seconds, duration.Milliseconds));
            }
            catch (Exception ex)
            {
                _logger.Error("Error in Pull(): ", ex);

                status.Level = StatusLevel.Error;
                status.Messages.Add(string.Format("Error pulling graph: {0}", ex));
            }

            _response.Append(status);
            return(_response);
        }