public virtual async Task<IEnumerable<Uri>> Commit(DateTime commitTimeStamp, IGraph commitMetadata, CancellationToken cancellationToken)
        {
            if (!_open)
            {
                throw new ObjectDisposedException(GetType().Name);
            }

            if (_batch.Count == 0)
            {
                return Enumerable.Empty<Uri>();
            }

            //  the commitId is only used for tracing and trouble shooting

            Guid commitId = Guid.NewGuid();

            //  save items

            IDictionary<string, CatalogItemSummary> newItemEntries = await SaveItems(commitId, commitTimeStamp, cancellationToken);

            //  save index pages - this is abstract as the derived class determines the index pagination

            IDictionary<string, CatalogItemSummary> pageEntries = await SavePages(commitId, commitTimeStamp, newItemEntries, cancellationToken);

            //  save index root

            await SaveRoot(commitId, commitTimeStamp, pageEntries, commitMetadata, cancellationToken);

            _batch.Clear();

            return newItemEntries.Keys.Select(s => new Uri(s));
        }
Example #2
0
        public override object HydrateValue(string nodeText, IGraph uow)
        {
            if (string.IsNullOrEmpty(nodeText))
                return null;

            return base.Decorated.HydrateValue(nodeText, uow);
        }
Example #3
0
        /// <summary>
        /// decorate so that if an object is null, we can't handle it by default, otherwise ask the decorated value manager
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="uow"></param>
        /// <returns></returns>
        public override bool CanHandle(object obj, IGraph uow)
        {
            if (obj == null)
                return false;

            return base.Decorated.CanHandle(obj, uow);
        }
Example #4
0
        public ExpansionDataset(IGraph expansionDescription, INode datasetSubj)
            : base(expansionDescription, datasetSubj)
        {
            //Check for aat:ignoreDataset
            IEnumerable<Triple> ts = expansionDescription.GetTriplesWithSubjectPredicate(datasetSubj, expansionDescription.CreateUriNode("aat:ignoreDataset"));
            Triple t = ts.FirstOrDefault();
            if (t != null)
            {
                if (t.Object.NodeType == NodeType.Literal)
                {
                    ILiteralNode l = (ILiteralNode)t.Object;
                    if (l.DataType != null && l.DataType.ToString().Equals(XmlSpecsHelper.XmlSchemaDataTypeBoolean))
                    {
                        this._ignore = Boolean.Parse(l.Value);
                    }
                }
            }

            //Find URI Discovery Endpoints
            ts = expansionDescription.GetTriplesWithSubjectPredicate(datasetSubj, expansionDescription.CreateUriNode("aat:uriDiscoveryEndpoint"));
            foreach (Triple endpoint in ts)
            {
                if (endpoint.Object.NodeType == NodeType.Uri)
                {
                    this._discoveryEndpoints.Add(((IUriNode)endpoint.Object).Uri);
                }
            }
        }
Example #5
0
        public override string DehydrateValue(object obj, IGraph uow)
        {
            if (obj == null)
                return null;

            return base.Decorated.DehydrateValue(obj, uow);
        }
Example #6
0
 /// <summary>
 /// Converts a dotNetRDF Graph to a Sesame Graph
 /// </summary>
 /// <param name="g">dotNetRDF Graph</param>
 /// <param name="mapping">Blank Node Mapping</param>
 /// <param name="target">Sesame Graph</param>
 public static void ToSesame(IGraph g, SesameMapping mapping, dotSesame.Graph target)
 {
     foreach (Triple t in g.Triples)
     {
         target.add(ToSesameResource(t.Subject, mapping), ToSesameUri(t.Predicate, mapping), ToSesameValue(t.Object, mapping));
     }
 }
Example #7
0
 public QuickRemove(ToolStripMenuItem menu, IGraph g, INode objNode, String file)
 {
     this._menu = menu;
     this._g = g;
     this._objNode = objNode;
     this._file = file;
 }
Example #8
0
 /// <summary>
 /// Creates a new Construct Context
 /// </summary>
 /// <param name="g">Graph to construct Triples in</param>
 /// <param name="s">Set to construct from</param>
 /// <param name="preserveBNodes">Whether Blank Nodes bound to variables should be preserved as-is</param>
 /// <remarks>
 /// <para>
 /// Either the <paramref name="s">Set</paramref>  or <paramref name="g">Graph</paramref> parameters may be null if required
 /// </para>
 /// </remarks>
 public ConstructContext(IGraph g, ISet s, bool preserveBNodes)
 {
     this._g = g;
     this._factory = (this._g != null ? (INodeFactory)this._g : _globalFactory.Value);
     this._s = s;
     this._preserveBNodes = preserveBNodes;
 }
        public bool CanHandle(object obj, IGraph uow)
        {
            if (obj == null)
                return false;

            return obj is IHasHydrationMap;
        }
Example #10
0
 protected void SetDefaultPheramone(IGraph input)
 {
     foreach (var edge in input.EdgesList)
     {
         edge.Mark.Pheromone = new Pheromone() {Value = 10};
     }
 }
        public void Save(IGraph g, TextWriter output)
        {
            JToken flattened = MakeExpandedForm(g);

            output.Write(flattened.ToString(Formatting.None, new JsonConverter[0]));
            output.Flush();
        }
        private void CheckCompressionRoundTrip(IGraph g)
        {
            foreach (KeyValuePair<IRdfWriter, IRdfReader> kvp in this._compressers)
            {

                IRdfWriter writer = kvp.Key;
                if (writer is ICompressingWriter)
                {
                    ((ICompressingWriter)writer).CompressionLevel = WriterCompressionLevel.High;
                }
                if (writer is IHighSpeedWriter)
                {
                    ((IHighSpeedWriter)writer).HighSpeedModePermitted = false;
                }
                System.IO.StringWriter strWriter = new System.IO.StringWriter();
                writer.Save(g, strWriter);

                Console.WriteLine("Compressed Output using " + kvp.Key.GetType().Name);
                Console.WriteLine(strWriter.ToString());
                Console.WriteLine();

                Graph h = new Graph();
                StringParser.Parse(h, strWriter.ToString(), kvp.Value);

                Assert.AreEqual(g, h, "Graphs should be equal after round trip to and from serialization using " + kvp.Key.GetType().Name);
            }
        }
Example #13
0
        private static IDictionary<INode, List<INode>> GetLists(IGraph graph)
        {
            INode first = graph.CreateUriNode(new Uri(First));
            INode rest = graph.CreateUriNode(new Uri(Rest));
            INode nil = graph.CreateUriNode(new Uri(Nil));

            IDictionary<INode, List<INode>> lists = new Dictionary<INode, List<INode>>();
            IEnumerable<Triple> ends = graph.GetTriplesWithPredicateObject(rest, nil);
            foreach (Triple end in ends)
            {
                List<INode> list = new List<INode>();
                Triple iterator = graph.GetTriplesWithSubjectPredicate(end.Subject, first).First();
                INode head = iterator.Subject;
                while (true)
                {
                    list.Add(iterator.Object);
                    IEnumerable<Triple> restTriples = graph.GetTriplesWithPredicateObject(rest, iterator.Subject);
                    if (!restTriples.Any())
                    {
                        break;
                    }

                    iterator = graph.GetTriplesWithSubjectPredicate(restTriples.First().Subject, first).First();
                    head = iterator.Subject;
                }

                list.Reverse();
                lists.Add(head, list);
            }

            return lists;
        }
Example #14
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="source"></param>
 /// <param name="target"></param>
 /// <param name="g"></param>
 /// <returns></returns>
 public static ConnectsEdgePredicate Connects(
     IVertex source,
     IVertex target,
     IGraph g)
 {
     return new ConnectsEdgePredicate(source,target,g);
 }
 /// <summary>
 /// Creates a new RDF/XML Writer Context
 /// </summary>
 /// <param name="g">Graph</param>
 /// <param name="output">Output destination</param>
 public RdfXmlWriterContext(IGraph g, TextWriter output)
 {
     this._g = g;
     this._output = output;
     this._writer = XmlWriter.Create(this._output, this.GetSettings());
     this._nsmapper.Import(this._g.NamespaceMap);
 }
        public void Save(IGraph g, TextWriter output)
        {
            JToken flattened = MakeExpandedForm(g);

            output.Write(flattened);
            output.Flush();
        }
Example #17
0
        /// <summary>
        /// The Find-Negative-Weight-Cycle() procedure to determine whether a graph has a negative-weight cycle,
        /// and how to construct one if it does.
        /// </summary>
        /// <param name="graph">A directed graph containing a set V of n vertices and a set E of m directed edges with arbitrary weights on which
        /// the BellmanFord() procedure has already been run.</param>
        /// <returns>
        /// Either a list of vertices in a negative-weight cycle, in order,
        /// or an empty list if the graph has no negative-weight cycles.
        /// </returns>
        public List<int> FindNegativeWeightCycle(IGraph directedGraph)
        {
            foreach (var u in directedGraph.Vertices)
                foreach (var v in directedGraph[u])
                    if (Shortest[u] + directedGraph.Weight(u, v) < Shortest[v])
                    {
                        int vTemp = v;
                        bool[] visited = new bool[directedGraph.N];         // Initialized by default to false //

                        int x = v;
                        while (!visited[x])
                        {
                            visited[x] = true;
                            x = (int)Graph.Predecessors[x];
                        }
                        vTemp = (int)Graph.Predecessors[x];

                        var cycle = new List<int>() { x };
                        while (vTemp != x)
                        {
                            cycle.Insert(0, vTemp);
                            vTemp = (int)Graph.Predecessors[vTemp];
                        }
                        return cycle;
                    }

            /**
             *  No negative edges, return empty list .. (P.104).
             */
            return new List<int>();
        }
Example #18
0
        private INode Emit(AST a, IGraph to)
        {
            String text = a.getText();
            int iType = a.Type;
            String type = parserpackage.GetTypeName(iType);
            NodeType currentNodeType = GetNodeType(type, to);
            INode currentNode = to.AddNode(currentNodeType);
            currentNode.SetAttribute("value", text);

            if (a.getNumberOfChildren() > 0)
            {
                List<AST> l = GetChildren(a);
                INode previousChild = null;
                foreach (AST current in l)
                {
                    INode childNode = Emit(current, to);
                    EdgeType childType = GetEdgeType("child", to);
                    to.AddEdge(childType, currentNode, childNode);

                    if (previousChild != null)
                    {
                        EdgeType nextType = GetEdgeType("next", to);
                        to.AddEdge(nextType, previousChild, childNode);
                    }
                    previousChild = childNode;
                }
            }
            return currentNode;
        }
    ManageTextWrapBeforeImport
    (
        IGraph sourceGraph,
        Microsoft.Office.Interop.Excel.Workbook destinationNodeXLWorkbook,
        Boolean notifyUser
    )
    {
        Debug.Assert(sourceGraph != null);
        Debug.Assert(destinationNodeXLWorkbook != null);

        if (sourceGraph.Edges.Count > RowThreshold ||
            sourceGraph.Vertices.Count > RowThreshold)
        {
            if ( notifyUser && !NotifyUser() )
            {
                return (false);
            }

            ExcelTableUtil.SetTableWrapText(destinationNodeXLWorkbook,
                WorksheetNames.Edges, TableNames.Edges, false);

            ExcelTableUtil.SetTableWrapText(destinationNodeXLWorkbook,
                WorksheetNames.Vertices, TableNames.Vertices, false);
        }

        return (true);
    }
                /// <summary>
                /// Returns the lightest set of edges that would divide the graph in two components should they be removed.
                /// </summary>
                /// <param name="graph">The flow graph to calculate the minimum cut of.</param>
                /// <param name="source">The source of the flow.</param>
                /// <param name="sink">The sink of the flow.</param>
                /// <returns>A list containing the edges that make up the minimum cut.</returns>
                public static List<IFlowGraphEdge> MinCut(IGraph<IFlowGraphEdge> graph, uint source, uint sink)
                {
                    Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = BuildFlowGraph(graph);
                    MaxFlow(flowGraph, source, sink);

                    List<IFlowGraphEdge> cut = new List<IFlowGraphEdge>();
                    HashSet<uint> reachable = new HashSet<uint>();
                    Queue<uint> open = new Queue<uint>();

                    open.Enqueue(source);
                    reachable.Add(source);
                    while (open.Count > 0)
                    {
                        uint i = open.Dequeue();
                        foreach (uint j in flowGraph[i].Keys)
                            if (!reachable.Contains(j) && flowGraph[i][j].Residual > 0)
                            {
                                open.Enqueue(j);
                                reachable.Add(j);
                            }
                    }

                    foreach (uint i in reachable)
                    {
                        foreach (uint j in flowGraph[i].Keys)
                            if (!reachable.Contains(j))
                                cut.Add(flowGraph[i][j].Original);
                    }

                    return cut;
                }
                private static Dictionary<uint, Dictionary<uint, FlowEdge>> BuildFlowGraph(IGraph<IFlowGraphEdge> graph)
                {
                    Dictionary<uint, Dictionary<uint, FlowEdge>> flowGraph = new Dictionary<uint, Dictionary<uint, FlowEdge>>();
                    Dictionary<uint, FlowEdge> dict;

                    foreach (IGraphNode<IFlowGraphEdge> n in graph.Nodes.Values)
                        foreach (IFlowGraphEdge e in n.Neighbours)
                        {
                            if (!flowGraph.TryGetValue(e.From, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.From, dict);
                            }
                            dict.Add(e.To, new FlowEdge(e.From, e.To, e.Capacity, e));

                            if (!flowGraph.TryGetValue(e.To, out dict))
                            {
                                dict = new Dictionary<uint, FlowEdge>();
                                flowGraph.Add(e.To, dict);
                            }
                            dict.Add(e.From, new FlowEdge(e.To, e.From, e.Capacity, e));
                        }

                    return flowGraph;
                }
 public static Uri GetPackageRegistrationUri(IGraph graph)
 {
     return ((IUriNode)graph.GetTriplesWithPredicateObject(
         graph.CreateUriNode(new Uri("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
         graph.CreateUriNode(new Uri("http://schema.nuget.org/schema#PackageRegistration")))
         .First().Subject).Uri;
 }
Example #23
0
 public Arc(IGraph graph, object head, object tail)
 {
     this.Graph = graph;
     ((IEdge)this).Vertices = new IVertex[2];
     this.Head = this.Graph[head];
     this.Tail = this.Graph[tail];
 }
        /// <summary>
        /// Creates a new Protocol Handler Configuration
        /// </summary>
        /// <param name="context">HTTP Context</param>
        /// <param name="g">Configuration Graph</param>
        /// <param name="objNode">Object Node</param>
        public BaseProtocolHandlerConfiguration(HttpContext context, IGraph g, INode objNode)
            : base(context, g, objNode)
        {
            //Then get the Protocol Processor to be used
            ISparqlHttpProtocolProcessor processor;
            INode procNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyProtocolProcessor));
            if (procNode == null) throw new DotNetRdfConfigurationException("Unable to load Protocol Handler Configuration as the RDF configuration file does not specify a dnr:protocolProcessor property for the Handler");
            Object temp = ConfigurationLoader.LoadObject(g, procNode);
            if (temp is ISparqlHttpProtocolProcessor)
            {
                processor = (ISparqlHttpProtocolProcessor)temp;
            }
            else
            {
                throw new DotNetRdfConfigurationException("Unable to load Protocol Handler Configuration as the RDF configuration file specifies a value for the Handlers dnr:protocolProcessor property which cannot be loaded as an object which implements the ISparqlHttpProtocolProcessor interface");
            }
            this._processor = processor;

            //Get the Service Description Graph
            INode descripNode = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyServiceDescription));
            if (descripNode != null)
            {
                Object descrip = ConfigurationLoader.LoadObject(g, descripNode);
                if (descrip is IGraph)
                {
                    this._serviceDescription = (IGraph)descrip;
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to set the Service Description Graph for the HTTP Handler identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:serviceDescription property points to an Object which could not be loaded as an object which implements the required IGraph interface");
                }
            }
        }
Example #25
0
        /// <summary>
        /// Writes the Graph to a String and returns the output in your chosen concrete RDF Syntax
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <param name="writer">Writer to use to generate the concrete RDF Syntax</param>
        /// <returns></returns>
        /// <remarks>
        /// Since the API allows for any <see cref="TextWriter">TextWriter</see> to be passed to the <see cref="IRdfWriter.Save">Save()</see> method of a <see cref="IRdfWriter">IRdfWriter</see> you can just pass in a <see cref="StringWriter">StringWriter</see> to the Save() method to get the output as a String.  This method simply provides a wrapper to doing just that.
        /// </remarks>
        public static String Write(IGraph g, IRdfWriter writer)
        {
            System.IO.StringWriter sw = new System.IO.StringWriter();
            writer.Save(g, sw);

            return sw.ToString();
        }
 public string DehydrateValue(object obj, IGraph uow)
 {
     Condition.Requires(obj).IsNotNull();
     var name = obj.GetType().Name;
     var val = obj.ToString();
     return LengthEncoder.LengthEncodeList(name, val);
 }
Example #27
0
 /// <summary>
 /// Formats a Graph Header by creating an <strong>&lt;rdf:RDF&gt;</strong> element and adding namespace definitions
 /// </summary>
 /// <param name="g">Graph</param>
 /// <returns></returns>
 public string FormatGraphHeader(IGraph g)
 {
     this._mapper = new QNameOutputMapper(g.NamespaceMap);
     StringBuilder output = new StringBuilder();
     output.Append(this.GetGraphHeaderBase());
     foreach (String prefix in g.NamespaceMap.Prefixes)
     {
         if (!prefix.Equals("rdf"))
         {
             if (prefix.Equals(String.Empty))
             {
                 output.Append(" xmlns=\"" + WriterHelper.EncodeForXml(g.NamespaceMap.GetNamespaceUri(prefix).ToString()) + "\"");
             }
             else
             {
                 output.Append(" xmlns:" + prefix + "=\"" + WriterHelper.EncodeForXml(g.NamespaceMap.GetNamespaceUri(prefix).ToString()) + "\"");
             }
         }
     }
     if (g.BaseUri != null)
     {
         output.Append(" xml:base=\"" + WriterHelper.EncodeForXml(g.BaseUri.ToString()) + "\"");
     }
     output.Append(">");
     return output.ToString();
 }
        public static IGraph ReplaceResourceUris(IGraph original, IDictionary<string, Uri> replacements)
        {
            IGraph modified = new Graph();
            foreach (Triple triple in original.Triples)
            {
                Uri subjectUri;
                if (!replacements.TryGetValue(triple.Subject.ToString(), out subjectUri))
                {
                    subjectUri = ((IUriNode)triple.Subject).Uri;
                }

                INode subjectNode = modified.CreateUriNode(subjectUri);
                INode predicateNode = triple.Predicate.CopyNode(modified);

                INode objectNode;
                if (triple.Object is IUriNode)
                {
                    Uri objectUri;
                    if (!replacements.TryGetValue(triple.Object.ToString(), out objectUri))
                    {
                        objectUri = ((IUriNode)triple.Object).Uri;
                    }
                    objectNode = modified.CreateUriNode(objectUri);
                }
                else
                {
                    objectNode = triple.Object.CopyNode(modified);
                }

                modified.Assert(subjectNode, predicateNode, objectNode);
            }

            return modified;
        }
        public bool CanHandle(object obj, IGraph uow)
        {
            if (obj == null)
                return false;

            return PrimitivesUtil.IsSystemPrimitive(obj);
        }
        public override bool CanHandle(object obj, IGraph uow)
        {
            if (obj == null)
                return false;

            return obj.IsMarkedSerializable();
        }
Example #31
0
 /// <summary>
 /// Updates an existing edge connecting the given nodes when <see cref="GraphBuilder{TNode,TEdge,TGroup}.UpdateGraph"/>
 /// is called and the edge should remain in the graph.
 /// </summary>
 /// <param name="graph">The graph.</param>
 /// <param name="edge">The edge to update.</param>
 /// <param name="labelData">The optional label data of the edge if an <see cref="EdgeLabelProvider"/> is specified.</param>
 /// <y.expert/>
 protected virtual void UpdateEdge([NotNull] IGraph graph, [NotNull] IEdge edge, [CanBeNull] object labelData)
 {
     this.graphBuilderHelper.UpdateEdge(graph, edge, labelData, default);
 }
 protected override void ConfigureOutputHandlers(IGraph graph, GraphMLWriter writer)
 {
     base.ConfigureOutputHandlers(graph, writer);
     writer.QueryOutputHandlers += RegisterZOrderOutputHandler;
 }
Example #33
0
 /// <summary>
 /// Converts a Result Set into a Triple Collection.
 /// </summary>
 /// <param name="g">Graph to generate the Nodes in.</param>
 /// <returns></returns>
 /// <remarks>
 /// Assumes the Result Set contains three variables ?s, ?p and ?o to use as the Subject, Predicate and Object respectively.  Only Results for which all three variables have bound values will generate Triples.
 /// </remarks>
 public BaseTripleCollection ToTripleCollection(IGraph g)
 {
     return(ToTripleCollection(g, "s", "p", "o"));
 }
Example #34
0
        /// <summary>
        /// Determines whether two Result Sets are equal.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// <remarks>
        /// Experimental and not yet complete.
        /// </remarks>
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

            if (obj is SparqlResultSet results)
            {
                // Must contain same number of Results to be equal
                if (Count != results.Count)
                {
                    return(false);
                }

                // Must have same Boolean result to be equal
                if (Result != results.Result)
                {
                    return(false);
                }

                // Must contain the same set of variables
                if (Variables.Count() != results.Variables.Count())
                {
                    return(false);
                }
                if (!Variables.All(v => results.Variables.Contains(v)))
                {
                    return(false);
                }
                if (results.Variables.Any(v => !_variables.Contains(v)))
                {
                    return(false);
                }

                // If both have no results then they are equal
                if (Count == 0 && results.Count == 0)
                {
                    return(true);
                }

                // All Ground Results from the Result Set must appear in the Other Result Set
                List <SparqlResult> otherResults = results.OrderByDescending(r => r.Variables.Count()).ToList();
                List <SparqlResult> localResults = new List <SparqlResult>();
                int grCount = 0;
                foreach (SparqlResult result in Results.OrderByDescending(r => r.Variables.Count()))
                {
                    if (result.IsGroundResult)
                    {
                        // If a Ground Result in this Result Set is not in the other Result Set we're not equal
                        if (!otherResults.Remove(result))
                        {
                            return(false);
                        }
                        grCount++;
                    }
                    else
                    {
                        localResults.Add(result);
                    }
                }

                // If all the Results were ground results and we've emptied all the Results from the other Result Set
                // then we were equal
                if (Count == grCount && otherResults.Count == 0)
                {
                    return(true);
                }

                // If the Other Results still contains Ground Results we're not equal
                if (otherResults.Any(r => r.IsGroundResult))
                {
                    return(false);
                }

                // Create Graphs of the two sets of non-Ground Results
                SparqlResultSet local = new SparqlResultSet();
                SparqlResultSet other = new SparqlResultSet();
                foreach (String var in _variables)
                {
                    local.AddVariable(var);
                    other.AddVariable(var);
                }
                foreach (SparqlResult r in localResults)
                {
                    local.AddResult(r);
                }
                foreach (SparqlResult r in otherResults)
                {
                    other.AddResult(r);
                }

                // Compare the two Graphs for equality
                SparqlRdfWriter writer = new SparqlRdfWriter();
                IGraph          g      = writer.GenerateOutput(local);
                IGraph          h      = writer.GenerateOutput(other);
                return(g.Equals(h));
            }
            else
            {
                return(false);
            }
        }
Example #35
0
        /// <summary>
        /// Saves a Graph to the Joseki store (appends to any existing Graph with the same URI)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// <para>
        /// Contents of this Graph will be appended to any existing Graph with the same URI
        /// </para>
        /// </remarks>
        public void SaveGraph(IGraph g)
        {
            if (this._updateService == null)
            {
                throw new RdfStorageException("Unable to save a Graph to the Joseki store - the connector was created in read-only mode");
            }
            try
            {
                HttpWebRequest request = this.CreateRequest(this._updateService, MimeTypesHelper.Any, "POST", new Dictionary <string, string>());

                //Build our Sparql Update Query
                StringBuilder postData = new StringBuilder();
                postData.Append("INSERT DATA");
                if (g.BaseUri != null)
                {
                    postData.Append(" INTO <" + g.BaseUri.ToString().Replace(">", "\\>") + ">");
                }
                postData.AppendLine(" {");
                foreach (Triple t in g.Triples)
                {
                    postData.AppendLine(t.ToString(this._formatter));
                }
                postData.AppendLine("}");

                StreamWriter postWriter = new StreamWriter(request.GetRequestStream());
                postWriter.Write(postData.ToString());
                postWriter.Close();

                #if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
                #endif

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif

                    //If we get then it was OK
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null)
                    {
                        Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                    }
                }
#endif

                throw new RdfStorageException("A HTTP error occurred while communicating with the Joseki server", webEx);
            }
        }
Example #36
0
 /// <summary>
 /// Loads a Graph from the Joseki store
 /// </summary>
 /// <param name="g">Graph to load into</param>
 /// <param name="graphUri">URI of the Graph to load</param>
 public void LoadGraph(IGraph g, Uri graphUri)
 {
     this.LoadGraph(g, graphUri.ToSafeString());
 }
        protected override async Task StartWithIGraph(IGraph graph, ILookup newContext)
        {
            OptionGroup epGroup            = (OptionGroup)Handler.GetGroupByName(LABELING).GetGroupByName(LABELING_EDGE_PROPERTIES);
            string      edgeLabelModelName = (string)epGroup[EDGE_LABEL_MODEL].Value;
            string      edgeLabelingName   = (string)epGroup[EDGE_LABELING].Value;

            if (edgeLabelingName != EDGE_LABELING_NONE)
            {
                if (edgeLabelModelName != EDGE_LABEL_MODEL_AS_IS)
                {
                    ApplyModelToIGraph(graph, CreateModelParameters(edgeLabelingName, edgeLabelModelName));
                }
                SetupPreferredLabelPlacement(graph);
            }
            bool useDirectedness = (bool)Handler.GetValue(EDGE_SETTINGS, CONSIDER_EDGE_DIRECTION);
            bool useThickness    = (bool)Handler.GetValue(EDGE_SETTINGS, CONSIDER_EDGE_THICKNESS);

            if (useDirectedness)
            {
                graph.MapperRegistry.CreateDelegateMapper <IEdge, double>(HierarchicLayout.EdgeDirectednessDpKey, edge => {
                    IArrowOwner style = edge.Style as IArrowOwner;
                    if (style == null)
                    {
                        return(0);
                    }
                    if (style.SourceArrow == Arrows.None && style.TargetArrow != Arrows.None)
                    {
                        return(1);
                    }
                    else if (style.SourceArrow != Arrows.None && style.TargetArrow == Arrows.None)
                    {
                        return(1);
                    }
                    else
                    {
                        return(0);
                    }
                });
            }
            if (useThickness)
            {
                graph.MapperRegistry.CreateDelegateMapper <IEdge, double>(HierarchicLayout.EdgeThicknessDpKey, edge => {
                    var pes = edge.Style as PolylineEdgeStyle;
                    if (pes != null)
                    {
                        return(pes.Pen.Thickness);
                    }
                    var aes = edge.Style as ArcEdgeStyle;
                    if (aes != null)
                    {
                        return(aes.Pen.Thickness);
                    }
                    return(1);
                });
            }
            var  foldingView      = graph.GetFoldingView();
            bool recursiveRouting = foldingView != null &&
                                    Handler.GetValue(EDGE_SETTINGS, RECURSIVE_EDGE_ROUTING) != RECURSIVE_EDGE_ROUTING_OFF;

            if (recursiveRouting)
            {
                graph.MapperRegistry.CreateDelegateMapper(HierarchicLayout.FolderNodesDpKey, node => foldingView.IsInFoldingState(node));
            }
            try {
                await base.StartWithIGraph(graph, newContext);
            } finally {
                if (useDirectedness)
                {
                    graph.MapperRegistry.RemoveMapper(HierarchicLayout.EdgeDirectednessDpKey);
                }
                if (useThickness)
                {
                    graph.MapperRegistry.RemoveMapper(HierarchicLayout.EdgeThicknessDpKey);
                }
                if (recursiveRouting)
                {
                    graph.MapperRegistry.RemoveMapper(HierarchicLayout.FolderNodesDpKey);
                }
            }
        }
Example #38
0
 protected virtual INode CreateGroupNode([NotNull] IGraph graph, [CanBeNull] object labelData, [CanBeNull] TGroup groupObject)
 {
     return(this.graphBuilderHelper.CreateGroupNode(graph, labelData, groupObject));
 }
Example #39
0
 /// <summary>
 /// Updates an existing node when the <see cref="UpdateGraph">graph is updated</see>.
 /// </summary>
 /// <remarks>
 /// This method is called during <see cref="UpdateGraph">updating the graph</see> for every node that already
 /// exists in the graph where its corresponding object from <see cref="NodesSource"/> is also still present.
 /// <para>
 /// Customizing how nodes are updated is usually easier by adding an event handler to the <see cref="NodeUpdated"/>
 /// event than by overriding this method.
 /// </para>
 /// </remarks>
 /// <param name="graph">The node's containing graph.</param>
 /// <param name="node">The node to update.</param>
 /// <param name="parent">The node's parent node.</param>
 /// <param name="labelData">The optional label data of the node if an <see cref="NodeLabelProvider"/> is specified.</param>
 /// <param name="nodeObject">The object from <see cref="NodesSource"/> from which the node has been created.</param>
 /// <y.expert/>
 protected virtual void UpdateNode([NotNull] IGraph graph, [NotNull] INode node, [CanBeNull] INode parent, [CanBeNull] object labelData, [CanBeNull] TNode nodeObject)
 {
     this.graphBuilderHelper.UpdateNode(graph, node, parent, labelData, nodeObject);
 }
Example #40
0
 protected virtual IEdge CreateEdge([NotNull] IGraph graph, [NotNull] INode source, [NotNull] INode target, [CanBeNull] object labelData)
 {
     return(this.graphBuilderHelper.CreateEdge(graph, source, target, labelData, default(TNode)));
 }
Example #41
0
 public DepthFirstSearch(IGraph graph, int vertex)
 {
     isConnected = new bool[graph.VertexCount];
     DFS(graph, vertex);
 }
Example #42
0
 /// <summary>
 /// Updates an existing group node when the <see cref="UpdateGraph">graph is updated</see>.
 /// </summary>
 /// <remarks>
 /// This method is called during <see cref="UpdateGraph">updating the graph</see> for every group node that already
 /// exists in the graph where its corresponding object from <see cref="GroupsSource"/> is also still present.
 /// <para>
 /// Customizing how group nodes are updated is usually easier by adding an event handler to the <see cref="GroupNodeUpdated"/>
 /// event than by overriding this method.
 /// </para>
 /// </remarks>
 /// <param name="graph">The group node's containing graph.</param>
 /// <param name="groupNode">The group node to update.</param>
 /// <param name="labelData">The optional label data of the group node if an <see cref="GroupLabelProvider"/> is specified.</param>
 /// <param name="groupObject">The object from <see cref="GroupsSource"/> from which the group node has been created.</param>
 /// <y.expert/>
 protected virtual void UpdateGroupNode([NotNull] IGraph graph, [NotNull] INode groupNode, [CanBeNull] object labelData, [CanBeNull] TGroup groupObject)
 {
     this.graphBuilderHelper.UpdateGroupNode(graph, groupNode, labelData, groupObject);
 }
Example #43
0
        /// <summary>
        /// Create a proxy reference node, i.e., a node referencing a proxy node.
        /// </summary>
        /// <remarks>
        /// This implementation copies the labels of the represented node and applies the <c>ProxyReferenceNodeStyle</c>.
        /// </remarks>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutNode">The node of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created node</returns>
        /// <seealso cref="CreateNodeCore"/>
        protected INode CreateProxyReferenceNode(LayoutGraph pageLayoutGraph, Node layoutNode, IGraph pageView)
        {
            INode       representedNode = GetRepresentedNode(layoutNode);
            INode       viewNode        = CreateNodeCore(pageLayoutGraph, pageView, layoutNode, representedNode, true, ProxyReferenceNodeDefaults);
            INodeInfo   nodeInfo        = result.GetNodeInfo(layoutNode);
            Node        referencingNode = nodeInfo.ReferencingNode;
            int         targetPage      = result.GetNodeInfo(referencingNode).PageNo;
            ILabelStyle style           = ProxyNodeDefaults.Labels.Style != NullLabelStyle
                            ? ProxyNodeDefaults.Labels.GetStyleInstance(viewNode)
                            : pageView.NodeDefaults.Labels.GetStyleInstance(viewNode);

            ILabelModelParameter parameter = ProxyNodeDefaults.Labels.LayoutParameter != NullLabelModelParameter
                            ? ProxyNodeDefaults.Labels.GetLayoutParameterInstance(viewNode)
                            : pageView.NodeDefaults.Labels.GetLayoutParameterInstance(viewNode);

            pageView.AddLabel(viewNode, "p" + targetPage, parameter, style);
            return(viewNode);
        }
Example #44
0
 protected virtual INode CreateNode([NotNull] IGraph graph, [CanBeNull] INode parent, [CanBeNull] object labelData, [CanBeNull] TNode nodeObject)
 {
     return(this.graphBuilderHelper.CreateNode(graph, parent, labelData, nodeObject));
 }
Example #45
0
        /// <summary>
        /// Create a group node, i.e., a node that directly corresponds to a group node of the original input graph.
        /// </summary>
        /// <remarks>
        ///  This implementation copies the labels of the corresponding node in the original input graph.
        /// Also the style of the original node is used for the returned node, unless the <c>GroupNodeStyle</c> is set.
        /// </remarks>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutNode">The node of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created node</returns>
        /// <seealso cref="CreateNodeCore"/>
        protected INode CreateGroupNode(LayoutGraph pageLayoutGraph, Node layoutNode, IGraph pageView)
        {
            INode modelNode = GetModelNode(layoutNode);
            INode viewNode  = CreateNodeCore(pageLayoutGraph, pageView, layoutNode, modelNode, false, GroupNodeDefaults);

            CopyNodeLabels(pageLayoutGraph, pageView, layoutNode, viewNode, modelNode);
            return(viewNode);
        }
Example #46
0
        /// <summary>
        /// Creates a new <see cref="IGraph{TShape, TMat}"/> by importing the given graphs and passing their <see cref="Shape"/>s
        /// along with the <see cref="Builder{TMat}"/> to the given create function.
        /// </summary>
        /// <typeparam name="TShapeOut">A type describing shape of the returned graph.</typeparam>
        /// <typeparam name="TMatOut">A type of value, that graph will materialize to after completion.</typeparam>
        /// <typeparam name="TMat0">A type of materialized value of the first input graph parameter.</typeparam>
        /// <typeparam name="TMat1">A type of materialized value of the second input graph parameter.</typeparam>
        /// <typeparam name="TMat2">A type of materialized value of the third input graph parameter.</typeparam>
        /// <typeparam name="TMat3">A type of materialized value of the fourth input graph parameter.</typeparam>
        /// <typeparam name="TMat4">A type of materialized value of the fifth input graph parameter.</typeparam>
        /// <typeparam name="TShape0">A type describing the shape of a first input graph parameter.</typeparam>
        /// <typeparam name="TShape1">A type describing the shape of a second input graph parameter.</typeparam>
        /// <typeparam name="TShape2">A type describing the shape of a third input graph parameter.</typeparam>
        /// <typeparam name="TShape3">A type describing the shape of a fourth input graph parameter.</typeparam>
        /// <typeparam name="TShape4">A type describing the shape of a fifth input graph parameter.</typeparam>
        /// <param name="g0">A first input graph.</param>
        /// <param name="g1">A second input graph.</param>
        /// <param name="g2">A third input graph.</param>
        /// <param name="g3">A fourth input graph.</param>
        /// <param name="g4">A fifth input graph.</param>
        /// <param name="combineMaterializers">Function used to determine output materialized value based on the materialized values of the passed graphs.</param>
        /// <param name="buildBlock">A graph constructor function.</param>
        /// <returns>A graph with materialized value.</returns>
        public static IGraph <TShapeOut, TMatOut> Create <TShapeOut, TMatOut, TMat0, TMat1, TMat2, TMat3, TMat4, TShape0, TShape1, TShape2, TShape3, TShape4>(
            IGraph <TShape0, TMat0> g0, IGraph <TShape1, TMat1> g1, IGraph <TShape2, TMat2> g2, IGraph <TShape3, TMat3> g3, IGraph <TShape4, TMat4> g4,
            Func <TMat0, TMat1, TMat2, TMat3, TMat4, TMatOut> combineMaterializers,
            Func <Builder <TMatOut>, TShape0, TShape1, TShape2, TShape3, TShape4, TShapeOut> buildBlock)
            where TShapeOut : Shape
            where TShape0 : Shape
            where TShape1 : Shape
            where TShape2 : Shape
            where TShape3 : Shape
            where TShape4 : Shape
        {
            var builder = new Builder <TMatOut>();

            var shape0 = builder.Add <TShape0, TMat0, Func <TMat1, Func <TMat2, Func <TMat3, Func <TMat4, TMatOut> > > > >(g0, m0 => (m1 => (m2 => (m3 => (m4 => combineMaterializers(m0, m1, m2, m3, m4))))));
            var shape1 = builder.Add <TShape1, Func <TMat1, Func <TMat2, Func <TMat3, Func <TMat4, TMatOut> > > >, TMat1, Func <TMat2, Func <TMat3, Func <TMat4, TMatOut> > > >(g1, (f, m1) => f(m1));
            var shape2 = builder.Add <TShape2, Func <TMat2, Func <TMat3, Func <TMat4, TMatOut> > >, TMat2, Func <TMat3, Func <TMat4, TMatOut> > >(g2, (f, m2) => f(m2));
            var shape3 = builder.Add <TShape3, Func <TMat3, Func <TMat4, TMatOut> >, TMat3, Func <TMat4, TMatOut> >(g3, (f, m3) => f(m3));
            var shape4 = builder.Add <TShape4, Func <TMat4, TMatOut>, TMat4, TMatOut>(g4, (f, m4) => f(m4));

            var shape  = buildBlock(builder, shape0, shape1, shape2, shape3, shape4);
            var module = builder.Module.ReplaceShape(shape);

            return(new GraphImpl <TShapeOut, TMatOut>(shape, module));
        }
Example #47
0
        /// <summary>
        /// Create a connector edge.
        /// </summary>
        /// <remarks>A connector edge is an edge connected to a connector node, i.e., it represents an edge
        /// of the input graph whose endpoints lie on different pages.
        /// </remarks>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutEdge">The edge of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created edge</returns>
        /// <seealso cref="CreateEdgeCore"/>
        protected IEdge CreateConnectorEdge(LayoutGraph pageLayoutGraph, Edge layoutEdge, IGraph pageView)
        {
            IEdge representedEdge = GetRepresentedEdge(layoutEdge);
            IEdge viewEdge        = CreateEdgeCore(pageLayoutGraph, pageView, layoutEdge, representedEdge, ConnectorEdgeDefaults);

            CopyEdgeLabels(pageLayoutGraph, pageView, layoutEdge, viewEdge, representedEdge, ConnectorEdgeDefaults.Labels);
            return(viewEdge);
        }
Example #48
0
        /// <summary>
        /// Create a proxy node, i.e., a node that "partially" represents a node of the input graph.
        /// </summary>
        /// <remarks>
        /// This implementation copies the labels of the represented node and applies the <c>ProxyNodeStyle</c>.
        /// </remarks>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutNode">The node of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created node</returns>
        /// <seealso cref="CreateNodeCore"/>
        protected INode CreateProxyNode(LayoutGraph pageLayoutGraph, Node layoutNode, IGraph pageView)
        {
            INode representedNode = GetRepresentedNode(layoutNode);
            INode viewNode        = CreateNodeCore(pageLayoutGraph, pageView, layoutNode, representedNode, true, ProxyNodeDefaults);

            CopyNodeLabels(pageLayoutGraph, pageView, layoutNode, viewNode, representedNode);
            return(viewNode);
        }
Example #49
0
 internal SSMTSP(IGraph gr, int source, bool[] fnodes /*, IntBinaryHeapPriorityQueue pq */)
 {
     //this.pq = pq;
     init(gr, source, fnodes);
 }
Example #50
0
        /// <summary>
        ///  Create a proxy reference edge.
        /// </summary>
        /// <remarks>
        ///  A proxy reference edge is an edge connected to a proxy reference node, i.e., a node that
        /// refers to a proxy of an original node located on a different page.
        /// </remarks>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutEdge">The edge of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created edge</returns>
        /// <seealso cref="CreateEdgeCore"/>
        protected IEdge CreateProxyReferenceEdge(LayoutGraph pageLayoutGraph, Edge layoutEdge, IGraph pageView)
        {
            IEdge representedEdge = GetRepresentedEdge(layoutEdge);
            IEdge viewEdge        = CreateEdgeCore(pageLayoutGraph, pageView, layoutEdge, representedEdge, ProxyReferenceEdgeDefaults);

            return(viewEdge);
        }
Example #51
0
 /// <summary>
 /// Creates a new Parser Context.
 /// </summary>
 /// <param name="g">Graph.</param>
 /// <param name="document">XML Document.</param>
 public RdfAParserContext(IGraph g, THtmlDocument document)
     : this(g, document, false)
 {
 }
Example #52
0
        /// <summary>
        /// Create a normal edge, i.e., an edge that directly corresponds to an edge of the original input graph.
        /// </summary>
        /// <param name="pageLayoutGraph">The layout graph representing the current page</param>
        /// <param name="layoutEdge">The edge of the layout graph that should be copied</param>
        /// <param name="pageView">The <see cref="IGraph"/> that is built to show the multi-page layout in a graph canvas</param>
        /// <returns>The created edge</returns>
        /// <seealso cref="CreateEdgeCore"/>
        protected IEdge CreateNormalEdge(LayoutGraph pageLayoutGraph, Edge layoutEdge, IGraph pageView)
        {
            IEdge modelEdge = GetModelEdge(layoutEdge);
            IEdge edge      = CreateEdgeCore(pageLayoutGraph, pageView, layoutEdge, modelEdge, NormalEdgeDefaults);

            CopyEdgeLabels(pageLayoutGraph, pageView, layoutEdge, edge, modelEdge, NormalEdgeDefaults.Labels);
            return(edge);
        }
 public void LoadGraph(IGraph g, string graphUri)
 {
     throw new NotImplementedException();
 }
Example #54
0
 /// <summary>
 /// Creates a new Parser Context.
 /// </summary>
 /// <param name="g">Graph.</param>
 /// <param name="document">HTML Document.</param>
 /// <param name="traceParsing">Whether to Trace Parsing.</param>
 public RdfAParserContext(IGraph g, THtmlDocument document, bool traceParsing)
     : base(g, traceParsing)
 {
     _document = document;
 }
 protected virtual INode CreateNode(IGraph graph)
 {
     return(NodeCreator(graph));
 }
 public void SaveGraph(IGraph g)
 {
     throw new NotImplementedException();
 }
Example #57
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <typeparam name="TIn">TBD</typeparam>
        /// <typeparam name="TOut">TBD</typeparam>
        /// <typeparam name="TMat">TBD</typeparam>
        /// <param name="ops">TBD</param>
        /// <param name="source">TBD</param>
        /// <returns>TBD</returns>
        public static GraphDsl.Builder <TMat> From <TIn, TOut, TMat>(this GraphDsl.ReverseOps <TIn, TMat> ops, IGraph <SourceShape <TOut>, TMat> source)
            where TIn : TOut
        {
            var b = ops.Builder;
            var s = b.Add(source);

            b.AddEdge(s.Outlet, ops.In);
            return(b);
        }
Example #58
0
 /// <summary>
 /// Attempts to load a RDF Graph from a URI asynchronously
 /// </summary>
 /// <param name="g">Graph to assert triple in</param>
 /// <param name="u">URI to load from</param>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 /// <remarks>
 /// <para>
 /// Will attempt to autodetect the format of the RDF based on the Content-Type header of the HTTP response
 /// </para>
 /// </remarks>
 public static void Load(IGraph g, Uri u, GraphCallback callback, Object state)
 {
     UriLoader.Load(g, u, null, callback, state);
 }
Example #59
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <typeparam name="TIn">TBD</typeparam>
        /// <typeparam name="TOut1">TBD</typeparam>
        /// <typeparam name="TOut2">TBD</typeparam>
        /// <typeparam name="TMat">TBD</typeparam>
        /// <param name="ops">TBD</param>
        /// <param name="flow">TBD</param>
        /// <returns>TBD</returns>
        public static GraphDsl.ForwardOps <TOut2, TMat> Via <TIn, TOut1, TOut2, TMat>(this GraphDsl.ForwardOps <TOut1, TMat> ops, IGraph <FlowShape <TIn, TOut2>, NotUsed> flow)
            where TIn : TOut1
        {
            var b = ops.Builder;
            var s = b.Add(flow);

            b.AddEdge(ops.Out, s.Inlet);
            return(new GraphDsl.ForwardOps <TOut2, TMat>(b, s.Outlet));
        }
Example #60
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <typeparam name="TIn">TBD</typeparam>
        /// <typeparam name="TOut1">TBD</typeparam>
        /// <typeparam name="TOut2">TBD</typeparam>
        /// <typeparam name="TMat">TBD</typeparam>
        /// <param name="ops">TBD</param>
        /// <param name="flow">TBD</param>
        /// <returns>TBD</returns>
        public static GraphDsl.ReverseOps <TOut1, TMat> Via <TIn, TOut1, TOut2, TMat>(this GraphDsl.ReverseOps <TIn, TMat> ops, IGraph <FlowShape <TOut1, TOut2>, TMat> flow)
            where TIn : TOut2
        {
            var b = ops.Builder;
            var f = b.Add(flow);

            b.AddEdge(f.Outlet, ops.In);
            return(new GraphDsl.ReverseOps <TOut1, TMat>(b, f.Inlet));
        }