public string GetString(SparqlResultsFormat format, IRdfWriter graphWriter = null)
        {
            switch (ResultType)
            {
                case BrightstarSparqlResultsType.VariableBindings:
                case BrightstarSparqlResultsType.Boolean:
                    var stringWriter = new System.IO.StringWriter();
                    var sparqlXmlWriter = GetSparqlWriter(format); 
                    sparqlXmlWriter.Save(_resultSet, stringWriter);
                    return stringWriter.GetStringBuilder().ToString();
                case BrightstarSparqlResultsType.Graph:
                    if (graphWriter == null)
                    {
#if WINDOWS_PHONE
                        // Cannot use DTD because the mobile version of XmlWriter doesn't support writing a DOCTYPE.
                        graphWriter = new RdfXmlWriter(WriterCompressionLevel.High, false);
#else
                        graphWriter = new RdfXmlWriter();
#endif
                    }
                    return StringWriter.Write(_graph, graphWriter);
                default:
                    throw new BrightstarInternalException(
                        String.Format("Unrecognized result type when serializing results string: {0}",
                                      ResultType));
            }
        }
Ejemplo n.º 2
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(IGraph, TextWriter)">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());
        }
Ejemplo n.º 3
0
 public void Setup()
 {
     Buffer    = new MemoryStream();
     RdfWriter = new JsonLdWriter();
     ScenarioSetup();
     TheTest();
 }
Ejemplo n.º 4
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IHtmlWriter)
     {
         ((IHtmlWriter)writer).Stylesheet = this._stylesheet;
     }
 }
        protected 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);

                GraphDiffReport report = g.Difference(h);
                if (!report.AreEqual)
                {
                    TestTools.ShowDifferences(report);
                }
                Assert.Equal(g, h);
            }
        }
Ejemplo n.º 6
0
        public RdfWriterOptionsWindow(IRdfWriter writer)
        {
            InitializeComponent();

            //Show Compression Levels
            Type clevels = typeof(WriterCompressionLevel);

            foreach (FieldInfo field in clevels.GetFields())
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Content = field.Name;
                item.Tag     = field.GetValue(null);
                this.cboCompressionLevel.Items.Add(item);
                if (field.Name.Equals("Default"))
                {
                    this.cboCompressionLevel.SelectedItem = item;
                }
            }
            if (this.cboCompressionLevel.SelectedItem == null && this.cboCompressionLevel.Items.Count > 0)
            {
                this.cboCompressionLevel.SelectedItem = this.cboCompressionLevel.Items[0];
            }

            //Enable/Disable relevant controls
            this.cboCompressionLevel.IsEnabled = (writer is ICompressingWriter);
            this.chkHighSpeed.IsEnabled        = (writer is IHighSpeedWriter);
            this.chkPrettyPrint.IsEnabled      = (writer is IPrettyPrintingWriter);
            this.chkUseAttributes.IsEnabled    = (writer is IAttributeWriter);
            this.chkUseDtds.IsEnabled          = (writer is IDtdWriter);
            this.stkHtmlWriter.IsEnabled       = (writer is IHtmlWriter);
            this.stkXmlWriter.IsEnabled        = (writer is IDtdWriter || writer is IAttributeWriter);

            this._writer = writer;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Processes a HEAD operation
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public override void ProcessHead(IHttpContext context)
        {
            //Work out the Graph URI we want to get
            Uri graphUri = this.ResolveGraphUri(context);

            try
            {
                bool exists = this.HasGraph(graphUri);
                if (exists)
                {
                    //Send the Content Type we'd select based on the Accept header to the user
                    String     ctype;
                    IRdfWriter writer = MimeTypesHelper.GetWriter(HandlerHelper.GetAcceptTypes(context), out ctype);
                    context.Response.ContentType = ctype;
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                }
            }
            catch (RdfQueryException)
            {
                //If the GetGraph() method errors this implies that the Store does not contain the Graph
                //In such a case we should return a 404
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }
        }
        public RdfWriterOptionsWindow(IRdfWriter writer)
        {
            InitializeComponent();

            //Show Compression Levels
            Type clevels = typeof(WriterCompressionLevel);
            foreach (FieldInfo field in clevels.GetFields())
            {
                ComboBoxItem item = new ComboBoxItem();
                item.Content = field.Name;
                item.Tag = field.GetValue(null);
                this.cboCompressionLevel.Items.Add(item);
                if (field.Name.Equals("Default"))
                {
                    this.cboCompressionLevel.SelectedItem = item;
                }
            }
            if (this.cboCompressionLevel.SelectedItem == null && this.cboCompressionLevel.Items.Count > 0)
            {
                this.cboCompressionLevel.SelectedItem = this.cboCompressionLevel.Items[0];
            }

            //Enable/Disable relevant controls
            this.cboCompressionLevel.IsEnabled = (writer is ICompressingWriter);
            this.chkHighSpeed.IsEnabled = (writer is IHighSpeedWriter);
            this.chkPrettyPrint.IsEnabled = (writer is IPrettyPrintingWriter);
            this.chkUseAttributes.IsEnabled = (writer is IAttributeWriter);
            this.chkUseDtds.IsEnabled = (writer is IDtdWriter);
            this.stkHtmlWriter.IsEnabled = (writer is IHtmlWriter);
            this.stkXmlWriter.IsEnabled = (writer is IDtdWriter || writer is IAttributeWriter);

            this._writer = writer;
        }
Ejemplo n.º 9
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IPrettyPrintingWriter)
     {
         ((IPrettyPrintingWriter)writer).PrettyPrintMode = this._prettyPrint;
     }
 }
Ejemplo n.º 10
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IHighSpeedWriter)
     {
         ((IHighSpeedWriter)writer).HighSpeedModePermitted = this._hiSpeedAllowed;
     }
 }
Ejemplo n.º 11
0
 public static void Save(this IRdfWriter writer, IGraph g, string fileName)
 {
     using (var textWriter = new StreamWriter(fileName))
     {
         writer.Save(g, textWriter);
     }
 }
Ejemplo n.º 12
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IHighSpeedWriter)
     {
         ((IHighSpeedWriter)writer).HighSpeedModePermitted = this._hiSpeedAllowed;
     }
 }
Ejemplo n.º 13
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is ICompressingWriter)
     {
         ((ICompressingWriter)writer).CompressionLevel = this._compressionLevel;
     }
 }
Ejemplo n.º 14
0
 /// <summary>Creates a new instance of the file triple store.</summary>
 /// <param name="fileStream">Stream to read/write.</param>
 /// <param name="rdfReader">RDF reader used to read the file.</param>
 /// <param name="rdfWriter">RDF writer to write the file.</param>
 public FileTripleStore(Stream fileStream, IRdfReader rdfReader, IRdfWriter rdfWriter)
 {
     _fileStream = fileStream;
     _rdfReader  = rdfReader;
     _rdfWriter  = rdfWriter;
     Read();
 }
Ejemplo n.º 15
0
        public string GetString(SparqlResultsFormat format, IRdfWriter graphWriter = null)
        {
            switch (ResultType)
            {
            case BrightstarSparqlResultsType.VariableBindings:
            case BrightstarSparqlResultsType.Boolean:
                var stringWriter    = new System.IO.StringWriter();
                var sparqlXmlWriter = GetSparqlWriter(format);
                sparqlXmlWriter.Save(_resultSet, stringWriter);
                return(stringWriter.GetStringBuilder().ToString());

            case BrightstarSparqlResultsType.Graph:
                if (graphWriter == null)
                {
#if WINDOWS_PHONE
                    // Cannot use DTD because the mobile version of XmlWriter doesn't support writing a DOCTYPE.
                    graphWriter = new RdfXmlWriter(WriterCompressionLevel.High, false);
#else
                    graphWriter = new RdfXmlWriter();
#endif
                }
                return(StringWriter.Write(_graph, graphWriter));

            default:
                throw new BrightstarInternalException(
                          String.Format("Unrecognized result type when serializing results string: {0}",
                                        ResultType));
            }
        }
Ejemplo n.º 16
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 SaveOnCompletionHandler(IRdfWriter writer, TextWriter textWriter)
     : base(new Graph())
 {
     if (writer == null) throw new ArgumentNullException("writer", "Must specify a RDF Writer to use when the Handler completes RDF handling");
     if (textWriter == null) throw new ArgumentNullException("textWriter", "Cannot save RDF to a null TextWriter");
     this._writer = writer;
     this._textWriter = textWriter;            
 }
 public SaveOnCompletionHandler(IRdfWriter writer, String file)
     : base(new Graph())
 {
     if (writer == null) throw new ArgumentNullException("writer", "Must specify a RDF Writer to use when the Handler completes RDF handling");
     if (file == null) throw new ArgumentNullException("file", "Cannot save RDF to a null file");
     this._writer = writer;
     this._file = file;
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Creates a new GZipped writer
 /// </summary>
 /// <param name="writer">Underlying writer</param>
 public BaseGZipWriter(IRdfWriter writer)
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     this._writer          = writer;
     this._writer.Warning += this.RaiseWarning;
 }
Ejemplo n.º 20
0
        public void WritingCharEscaping()
        {
            List <IRdfReader> readers = new List <IRdfReader>()
            {
                new TurtleParser(),
                new Notation3Parser()
            };
            List <IRdfWriter> writers = new List <IRdfWriter>()
            {
                new CompressingTurtleWriter(WriterCompressionLevel.High),
                new Notation3Writer()
            };

            for (int i = 0; i < readers.Count; i++)
            {
                IRdfReader parser = readers[i];
                IRdfWriter writer = writers[i];

                foreach (String sample in samples)
                {
                    Graph g = new Graph();
                    Console.WriteLine("Original RDF Fragment");
                    Console.WriteLine(prefix + sample);
                    StringParser.Parse(g, prefix + sample, parser);
                    Console.WriteLine();
                    Console.WriteLine("Triples in Original");
                    foreach (Triple t in g.Triples)
                    {
                        Console.WriteLine(t.ToString());
                    }
                    Console.WriteLine();

                    String serialized = VDS.RDF.Writing.StringWriter.Write(g, writer);
                    Console.WriteLine("Serialized RDF Fragment");
                    Console.WriteLine(serialized);

                    Graph h = new Graph();
                    StringParser.Parse(h, serialized, parser);

                    Console.WriteLine();
                    Console.WriteLine("Triples in Serialized");
                    foreach (Triple t in g.Triples)
                    {
                        Console.WriteLine(t.ToString());
                    }
                    Console.WriteLine();

                    Assert.AreEqual(g, h, "Graphs should have been equal");

                    Console.WriteLine("Graphs were equal as expected");
                    Console.WriteLine();
                }
            }
        }
Ejemplo n.º 21
0
        private bool SetResultsFormat(String format)
        {
            switch (format)
            {
            case "xml":
                this._resultsWriter = new SparqlXmlWriter();
                this._graphWriter   = new RdfXmlWriter();
                break;

            case "json":
                this._resultsWriter = new SparqlJsonWriter();
                this._graphWriter   = new RdfJsonWriter();
                break;

            case "ntriples":
                this._graphWriter = new NTriplesWriter();
                break;

            case "rdfxml":
                this._graphWriter = new RdfXmlWriter();
                break;

            case "turtle":
                this._graphWriter = new CompressingTurtleWriter(WriterCompressionLevel.High);
                break;

            case "n3":
                this._graphWriter = new Notation3Writer(WriterCompressionLevel.High);
                break;

            case "html":
            case "rdfa":
                this._resultsWriter = new SparqlHtmlWriter();
                this._graphWriter   = new HtmlWriter();
                break;

            case "csv":
                this._resultsWriter = new SparqlCsvWriter();
                this._graphWriter   = new CsvWriter();
                break;

            case "tsv":
                this._resultsWriter = new SparqlTsvWriter();
                this._graphWriter   = new TsvWriter();
                break;

            default:
                Console.Error.WriteLine("rdfQuery: The value '" + format + "' is not a valid Results Format");
                return(false);
            }

            return(true);
        }
Ejemplo n.º 22
0
        public void WritingBackslashEscaping()
        {
            Graph g    = new Graph();
            INode subj = g.CreateBlankNode();
            INode pred = g.CreateUriNode(new Uri("ex:string"));
            INode obj  = g.CreateLiteralNode(@"C:\Program Files\some\path\\to\file.txt");

            g.Assert(subj, pred, obj);
            obj = g.CreateLiteralNode(@"\");
            g.Assert(subj, pred, obj);
            obj = g.CreateLiteralNode(@"C:\\new\\real\\ugly\\Under has all the possible escape character interactions");
            g.Assert(subj, pred, obj);

            List <IRdfWriter> writers = new List <IRdfWriter>()
            {
                new NTriplesWriter(),
                new TurtleWriter(),
                new CompressingTurtleWriter(WriterCompressionLevel.High),
                new Notation3Writer()
            };

            List <IRdfReader> parsers = new List <IRdfReader>()
            {
                new NTriplesParser(),
                new TurtleParser(),
                new TurtleParser(),
                new Notation3Parser()
            };

            Console.WriteLine("Original Graph");
            TestTools.ShowGraph(g);
            Console.WriteLine();

            for (int i = 0; i < writers.Count; i++)
            {
                IRdfWriter writer = writers[i];
                Console.WriteLine("Testing Writer " + writer.GetType().Name);

                System.IO.StringWriter strWriter = new System.IO.StringWriter();
                writer.Save(g, strWriter);

                Console.WriteLine("Written as:");
                Console.WriteLine(strWriter.ToString());
                Console.WriteLine();

                Graph h = new Graph();
                StringParser.Parse(h, strWriter.ToString(), parsers[i]);
                Console.WriteLine("Parsed Graph");
                TestTools.ShowGraph(h);
                Console.WriteLine();
                Assert.AreEqual(g, h, "Graphs should be equal");
            }
        }
Ejemplo n.º 23
0
        /// <summary>Creates a new instance of the file triple store.</summary>
        /// <param name="filePath">Path of the file to read/write.</param>
        /// <param name="rdfReader">RDF reader used to read the file.</param>
        /// <param name="rdfWriter">RDF writer to write the file.</param>
        public FileTripleStore(string filePath, IRdfReader rdfReader, IRdfWriter rdfWriter)
        {
            if (!File.Exists(_filePath = filePath))
            {
                File.Create(filePath).Close();
            }

            _rdfReader = rdfReader;
            _rdfWriter = rdfWriter;

            Read();
        }
Ejemplo n.º 24
0
 public RdfAdaptor(IRdfReader parser, IRdfWriter writer)
 {
     if (parser == null)
     {
         throw new ArgumentNullException("parser", "Cannot use a null parser for an RDF Adaptor");
     }
     if (writer == null)
     {
         throw new ArgumentNullException("writer", "Cannot use a null writer for an RDF Adaptor");
     }
     this._parser = parser;
     this._writer = writer;
 }
Ejemplo n.º 25
0
        /// <summary>Creates a new instance of the file triple store.</summary>
        /// <param name="filePath">Path of the file to read/write.</param>
        /// <param name="rdfReader">RDF reader used to read the file.</param>
        /// <param name="rdfWriter">RDF writer to write the file.</param>
        public FileTripleStore(string filePath, IRdfReader rdfReader, IRdfWriter rdfWriter)
        {
            if (!File.Exists(_filePath = EnsureAbsolute(filePath)))
            {
                File.Create(_filePath).Close();
            }

            _watcher   = CreateFileHooks(_filePath);
            _rdfReader = rdfReader;
            _rdfWriter = rdfWriter;

            Read();
        }
Ejemplo n.º 26
0
        public void WritingI18NCharacters(IRdfWriter writer, IRdfReader parser)
        {
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/植物");
            g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/植物"));
            IUriNode subj = g.CreateUriNode(new Uri("http://example.org/植物/名=しそ;使用部=葉"));
            IUriNode pred = g.CreateUriNode(new Uri("http://example.org/植物#使用部"));
            IUriNode obj  = g.CreateUriNode(new Uri("http://example.org/葉"));

            g.Assert(subj, pred, obj);

            RoundTripTest(g, writer, parser);
        }
Ejemplo n.º 27
0
 public SaveOnCompletionHandler(IRdfWriter writer, String file)
     : base(new Graph())
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer", "Must specify a RDF Writer to use when the Handler completes RDF handling");
     }
     if (file == null)
     {
         throw new ArgumentNullException("file", "Cannot save RDF to a null file");
     }
     this._writer = writer;
     this._file   = file;
 }
Ejemplo n.º 28
0
 public SaveOnCompletionHandler(IRdfWriter writer, TextWriter textWriter)
     : base(new Graph())
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer", "Must specify a RDF Writer to use when the Handler completes RDF handling");
     }
     if (textWriter == null)
     {
         throw new ArgumentNullException("textWriter", "Cannot save RDF to a null TextWriter");
     }
     this._writer     = writer;
     this._textWriter = textWriter;
 }
Ejemplo n.º 29
0
        public void WritingUriEscaping(IRdfWriter writer, IRdfReader parser)
        {
            Graph g = new Graph();

            g.BaseUri = new Uri("http://example.org/space in/base");
            g.NamespaceMap.AddNamespace("ex", new Uri("http://example.org/space in/namespace"));
            IUriNode subj = g.CreateUriNode(new Uri("http://example.org/subject"));
            IUriNode pred = g.CreateUriNode(new Uri("http://example.org/predicate"));
            IUriNode obj  = g.CreateUriNode(new Uri("http://example.org/with%20uri%20escapes"));
            IUriNode obj2 = g.CreateUriNode(new Uri("http://example.org/needs escapes"));

            g.Assert(subj, pred, obj);
            g.Assert(subj, pred, obj2);

            RoundTripTest(g, writer, parser);
        }
Ejemplo n.º 30
0
        private void CreateIOHandlers(string extension)
        {
            switch (extension)
            {
            case ".nq":
                _storeReader = new NQuadsParser();
                _storeWriter = new NQuadsWriter();
                break;

            case ".ttl":
                _rdfReader = new TurtleParser();
                _rdfWriter = new CompressingTurtleWriter();
                break;

            case ".trig":
                _storeReader = new TriGParser();
                _storeWriter = new TriGWriter()
                {
                    CompressionLevel = -1
                };
                break;

            case ".xml":
                _rdfReader = new RdfXmlParser();
                _rdfWriter = new RdfXmlWriter();
                break;

            case ".n3":
                _rdfReader = new Notation3Parser();
                _rdfWriter = new Notation3Writer();
                break;

            case ".trix":
                _storeReader = new TriXParser();
                _storeWriter = new TriXWriter();
                break;

            case ".json":
                _rdfReader = new RdfJsonParser();
                _rdfWriter = new RdfJsonWriter();
                break;

            default:
                throw new ArgumentOutOfRangeException(System.String.Format("Provided file path does not allow to detect a type of the RDF serialization type."));
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Internal Helper function which returns the Results back to the Client in one of their accepted formats
        /// </summary>
        /// <param name="context">Context of the HTTP Request</param>
        /// <param name="result">Results of the Sparql Query</param>
        protected void ProcessQueryResults(HttpServerContext context, Object result)
        {
            //Return the Results
            String ctype;

            if (result is SparqlResultSet)
            {
                //Get the appropriate Writer and set the Content Type
                ISparqlResultsWriter sparqlwriter;
                if (context.Request.AcceptTypes != null)
                {
                    sparqlwriter = MimeTypesHelper.GetSparqlWriter(context.Request.AcceptTypes, out ctype);
                }
                else
                {
                    //Default to SPARQL XML Results Format if no accept header
                    sparqlwriter = new SparqlXmlWriter();
                    ctype        = "application/sparql-results+xml";
                }
                context.Response.ContentType = ctype;
                if (sparqlwriter is IHtmlWriter)
                {
                    ((IHtmlWriter)sparqlwriter).Stylesheet = this._config.Stylesheet;
                }

                //Send Result Set to Client
                sparqlwriter.Save((SparqlResultSet)result, new StreamWriter(context.Response.OutputStream));
            }
            else if (result is Graph)
            {
                //Get the appropriate Writer and set the Content Type
                IRdfWriter rdfwriter = MimeTypesHelper.GetWriter(context.Request.AcceptTypes, out ctype);
                context.Response.ContentType = ctype;
                if (rdfwriter is IHtmlWriter)
                {
                    ((IHtmlWriter)rdfwriter).Stylesheet = this._config.Stylesheet;
                }

                //Send Graph to Client
                rdfwriter.Save((Graph)result, new StreamWriter(context.Response.OutputStream));
            }
            else
            {
                throw new RdfQueryException("Unexpected Query Result Object of Type '" + result.GetType().ToString() + "' returned");
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Helper method for doing async update operations, callers just need to provide an appropriately prepared HTTP request and a RDF writer which will be used to write the data to the request body
        /// </summary>
        /// <param name="request">HTTP Request</param>
        /// <param name="writer">RDF writer</param>
        /// <param name="graphUri">URI of the Graph to update</param>
        /// <param name="ts">Triples</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        protected internal void UpdateGraphAsync(HttpWebRequest request, IRdfWriter writer, Uri graphUri, IEnumerable <Triple> ts, AsyncStorageCallback callback, Object state)
        {
            Graph g = new Graph();

            g.Assert(ts);

            request.BeginGetRequestStream(r =>
            {
                try
                {
                    Stream reqStream = request.EndGetRequestStream(r);
                    writer.Save(g, new StreamWriter(reqStream));

                    Tools.HttpDebugRequest(request);

                    request.BeginGetResponse(r2 =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                            Tools.HttpDebugResponse(response);
                            //If we get here then it was OK
                            response.Close();
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri), state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleHttpError(webEx, "updating a Graph asynchronously in")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.UpdateGraph, graphUri, StorageHelper.HandleError(ex, "updating a Graph asynchronously in")), state);
                }
            }, state);
        }
Ejemplo n.º 33
0
        /// <inheritdoc />
        public async Task Write(StreamWriter streamWriter, IRdfWriter rdfWriter)
        {
            if (streamWriter == null)
            {
                throw new ArgumentNullException(nameof(streamWriter));
            }

            if (rdfWriter == null)
            {
                throw new ArgumentNullException(nameof(rdfWriter));
            }

            var graphs = from entity in Entities
                         from statement in entity.Value
                         group statement by statement.Graph into graph
                         select new KeyValuePair <Iri, IEnumerable <Statement> >(graph.Key, graph);
            await rdfWriter.Write(streamWriter, graphs);
        }
Ejemplo n.º 34
0
        private void Test(String literal, IRdfWriter writer, IRdfReader parser)
        {
            IGraph g = new Graph();

            g.NamespaceMap.AddNamespace(String.Empty, UriFactory.Create("http://example/"));
            g.Assert(g.CreateUriNode(":subj"), g.CreateUriNode(":pred"), g.CreateLiteralNode(literal));

            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            writer.Save(g, strWriter);

            Console.WriteLine(strWriter.ToString());

            IGraph h = new Graph();

            parser.Load(h, new StringReader(strWriter.ToString()));

            Assert.AreEqual(g, h);
        }
        public void saveGraph(IGraph g, IRdfWriter w, String fileName)
        {
            if (w is IPrettyPrintingWriter)
            {
                ((IPrettyPrintingWriter)w).PrettyPrintMode = true;
            }

            if (w is IHighSpeedWriter)
            {
                ((IHighSpeedWriter)w).HighSpeedModePermitted = true;
            }

            if (w is ICompressingWriter)
            {
                ((ICompressingWriter)w).CompressionLevel = WriterCompressionLevel.High;
            }

            w.Save(g, fileName);
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Creates a new Export Graph Options Form
        /// </summary>
        public ExportGraphOptionsForm()
        {
            InitializeComponent();

            //Load Writers
            Type targetType           = typeof(IRdfWriter);
            List <IRdfWriter> writers = new List <IRdfWriter>();

            foreach (Type t in Assembly.GetAssembly(targetType).GetTypes())
            {
                if (t.Namespace == null)
                {
                    continue;
                }

                if (t.Namespace.Equals("VDS.RDF.Writing"))
                {
                    if (t.GetInterfaces().Contains(targetType))
                    {
                        try
                        {
                            IRdfWriter writer = (IRdfWriter)Activator.CreateInstance(t);
                            writers.Add(writer);
                        }
                        catch
                        {
                            //Ignore this Formatter
                        }
                    }
                }
            }
            writers.Sort(new ToStringComparer <IRdfWriter>());
            this.cboWriter.DataSource = writers;
            if (this.cboWriter.Items.Count > 0)
            {
                this.cboWriter.SelectedIndex = 0;
            }

            this.cboWriter.SelectedIndex      = 0;
            this.cboCompression.SelectedIndex = 1;
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Helper method for doing async save operations, callers just need to provide an appropriately perpared HTTP requests and a RDF writer which will be used to write the data to the request body
        /// </summary>
        /// <param name="request">HTTP request</param>
        /// <param name="writer">RDF Writer</param>
        /// <param name="g">Graph to save</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        protected internal void SaveGraphAsync(HttpWebRequest request, IRdfWriter writer, IGraph g, AsyncStorageCallback callback, Object state)
        {
            request.BeginGetRequestStream(r =>
            {
                try
                {
                    Stream reqStream = request.EndGetRequestStream(r);
                    writer.Save(g, new StreamWriter(reqStream));

                    Tools.HttpDebugRequest(request);

                    request.BeginGetResponse(r2 =>
                    {
                        try
                        {
                            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2);
                            Tools.HttpDebugResponse(response);
                            //If we get here then it was OK
                            response.Close();
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state);
                        }
                        catch (WebException webEx)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                        }
                        catch (Exception ex)
                        {
                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                        }
                    }, state);
                }
                catch (WebException webEx)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                }
                catch (Exception ex)
                {
                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                }
            }, state);
        }
Ejemplo n.º 38
0
        private void SaveWith(IRdfWriter writer)
        {
            if (this._editor.DocumentManager.ActiveDocument == null) return;

            Document<TextEditor> doc = this._editor.DocumentManager.ActiveDocument;
            IRdfReader parser = SyntaxManager.GetParser(doc.Syntax);
            if (parser == null)
            {
                MessageBox.Show("To use Save With the source document must be in a RDF Graph Syntax.  If the document is in a RDF Graph Syntax please change the syntax setting to the relevant format under Options > Syntax", "Save With Unavailable");
                return;
            }

            Graph g = new Graph();
            try
            {
                StringParser.Parse(g, doc.Text, parser);
            }
            catch
            {
                MessageBox.Show("Unable to Save With an RDF Writer as the current document is not a valid RDF document when parsed with the " + parser.GetType().Name + ".  If you believe this is a valid RDF document please select the correct Syntax Highlighting from the Options Menu and retry", "Save With Failed");
                return;
            }

            try
            {
                //Check whether the User wants to set advanced options?
                if (Properties.Settings.Default.SaveWithOptionsPrompt)
                {
                    RdfWriterOptionsWindow optPrompt = new RdfWriterOptionsWindow(writer);
                    optPrompt.Owner = this;
                    if (optPrompt.ShowDialog() != true) return;
                }

                //Do the actual save
                System.IO.StringWriter strWriter = new System.IO.StringWriter();
                writer.Save(g, strWriter);
                Document<TextEditor> newDoc = this._editor.DocumentManager.New(true);
                newDoc.Text = strWriter.ToString();
                newDoc.AutoDetectSyntax();
                this.AddTextEditor(new TabItem(), newDoc);
                this.tabDocuments.SelectedIndex = this.tabDocuments.Items.Count - 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while saving: " + ex.Message, "Save With Failed");
            }
        }
Ejemplo n.º 39
0
        private bool SetOptions(String[] args)
        {
            if (args.Length == 0 || (args.Length == 1 && args[0].Equals("-help")))
            {
                this.ShowUsage();
                return false;
            }

            //Look through the arguments to see what we've been asked to do
            foreach (String arg in args)
            {
                if (arg.StartsWith("-uri:"))
                {
                    this._inputs.Add(arg);
                }
                else if (arg.StartsWith("-hs"))
                {
                    if (arg.Contains(':'))
                    {
                        bool hs;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out hs))
                        {
                            this._options.Add(new HighSpeedOption(hs));
                        }
                        else
                        {
                            this._options.Add(new HighSpeedOption(true));
                        }
                    }
                    else
                    {
                        this._options.Add(new HighSpeedOption(true));
                    }
                }
                else if (arg.StartsWith("-pp"))
                {
                    if (arg.Contains(':'))
                    {
                        bool pp;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out pp))
                        {
                            this._options.Add(new PrettyPrintingOption(pp));
                        }
                        else
                        {
                            this._options.Add(new PrettyPrintingOption(true));
                        }
                    }
                    else
                    {
                      this._options.Add(new PrettyPrintingOption(true));
                    }
                }
                else if (arg.StartsWith("-c"))
                {
                    if (arg.Contains(':'))
                    {
                        int c;
                        if (Int32.TryParse(arg.Substring(arg.IndexOf(':') + 1), out c))
                        {
                            this._options.Add(new CompressionLevelOption(c));
                        }
                        else
                        {
                            this._options.Add(new CompressionLevelOption(WriterCompressionLevel.Default));
                        }
                    }
                    else
                    {
                        this._options.Add(new CompressionLevelOption(WriterCompressionLevel.Default));
                    }
                }
                else if (arg.StartsWith("-stylesheet:"))
                {
                    String stylesheet = arg.Substring(arg.IndexOf(':') + 1);
                    this._options.Add(new StylesheetOption(stylesheet));

                }
                else if (arg.Equals("-merge"))
                {
                    this._merge = true;
                }
                else if (arg.Equals("-overwrite"))
                {
                    this._overwrite = true;
                }
                else if (arg.Equals("-dataset"))
                {
                    this._dataset = true;
                    this._merge = true;
                }
                else if (arg.StartsWith("-out:") || arg.StartsWith("-output:"))
                {
                    this._output = arg.Substring(arg.IndexOf(':') + 1);
                    //If the Writers have not been set then we'll set them now
                    if (this._writer == null && this._storeWriter == null)
                    {
                        String format;
                        try
                        {
                            format = MimeTypesHelper.GetMimeType(Path.GetExtension(this._output));
                        }
                        catch (RdfException)
                        {
                            Console.Error.WriteLine("rdfConvert: The File Extension '" + Path.GetExtension(this._output) + "' is not permissible since dotNetRDF cannot infer a MIME type from the extension");
                            return false;
                        }
                        try
                        {
                            this._writer = MimeTypesHelper.GetWriter(format);
                        }
                        catch (RdfException)
                        {
                            //Supress this error
                        }
                        try
                        {
                            this._storeWriter = MimeTypesHelper.GetStoreWriter(format);
                            if (this._writer == null)
                            {
                                this._merge = true;
                            }
                            else if (this._writer is NTriplesWriter && !Path.GetExtension(this._output).Equals(".nt"))
                            {
                                this._writer = null;
                                this._merge = true;
                            }
                        }
                        catch (RdfException)
                        {
                            //Suppress this error
                        }
                        if (this._writer == null && this._storeWriter == null)
                        {
                            Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                            return false;
                        }
                    }
                }
                else if (arg.StartsWith("-outformat:"))
                {
                    String format = arg.Substring(arg.IndexOf(':') + 1);
                    if (!format.Contains("/"))
                    {
                        try
                        {
                            format = MimeTypesHelper.GetMimeType(format);
                        }
                        catch (RdfException)
                        {
                            Console.Error.WriteLine("rdfConvert: The File Extension '" + format + "' is not permissible since dotNetRDF cannot infer a MIME type from the extension");
                            return false;
                        }
                    }
                    //Validate the MIME Type
                    if (!IsValidMimeType(format))
                    {
                        Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                        return false;
                    }
                    try
                    {
                        this._writer = MimeTypesHelper.GetWriter(format);
                        this._outExt = MimeTypesHelper.GetFileExtension(this._writer);
                    }
                    catch (RdfException)
                    {
                        //Supress this error
                    }
                    try
                    {
                        this._storeWriter = MimeTypesHelper.GetStoreWriter(format);
                        if (this._writer == null)
                        {
                            //In the event that we can't get a valid Writer then individual graphs
                            //will be put into a Store and output as a Dataset
                            this._merge = true;
                            this._outExt = MimeTypesHelper.GetFileExtension(this._storeWriter);
                        }
                        else if (this._writer is NTriplesWriter && (!format.Equals("nt") || !format.Equals(".nt") || !format.Equals("text/plain")))
                        {
                            this._writer = null;
                            this._merge = true;
                            this._outExt = MimeTypesHelper.GetFileExtension(this._storeWriter);
                        }
                    }
                    catch (RdfException)
                    {
                        //Suppress this error
                    }
                    if (this._writer == null && this._storeWriter == null)
                    {
                        Console.Error.WriteLine("rdfConvert: The MIME Type '" + format + "' is not permissible since dotNetRDF does not support outputting in that format");
                        return false;
                    }
                }
                else if (arg.StartsWith("-outext:"))
                {
                    this._outExt = arg.Substring(arg.IndexOf(':') + 1);
                    if (!this._outExt.StartsWith(".")) this._outExt = "." + this._outExt;
                }
                else if (arg.Equals("-debug"))
                {
                    this._debug = true;
                }
                else if (arg.Equals("-help"))
                {
                    //Ignore help argument if other arguments are present
                }
                else if (arg.Equals("-nocache"))
                {
                    Options.UriLoaderCaching = false;
                }
                else if (arg.Equals("-nobom"))
                {
                    Options.UseBomForUtf8 = false;
                }
                else if (arg.Equals("-warnings"))
                {
                    this._warnings = true;
                    UriLoader.Warning += this.ShowWarning;
                    UriLoader.StoreWarning += this.ShowWarning;
                    FileLoader.Warning += this.ShowWarning;
                    FileLoader.StoreWarning += this.ShowWarning;
                }
                else
                {
                    //Anything else is treated as an input file
                    this._inputs.Add(arg);
                }
            }

            //If there are no this._inputs then we'll abort
            if (this._inputs.Count == 0)
            {
                Console.Error.WriteLine("rdfConvert: No Inputs were provided - please provide one/more files or URIs you wish to convert");
                return false;
            }

            //If there are no writers specified then we'll abort
            if (this._writer == null && this._storeWriter == null)
            {
                Console.Error.WriteLine("rdfConvert: Aborting since no output options have been specified, use the -out:filename or -outformat: arguments to specify output format");
                return false;
            }

            if (!this._outExt.Equals(String.Empty))
            {
                if (!this._outExt.StartsWith(".")) this._outExt = "." + this._outExt;
            }
            else if (!this._output.Equals(String.Empty))
            {
                this._outExt = Path.GetExtension(this._output);
            }

            //Apply the Options to the Writers
            foreach (IConversionOption option in this._options)
            {
                if (this._writer != null) option.Apply(this._writer);
                if (this._storeWriter != null) option.Apply(this._storeWriter);
            }

            return true;
        }
Ejemplo n.º 40
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is ICompressingWriter)
     {
         ((ICompressingWriter)writer).CompressionLevel = this._compressionLevel;
     }
 }
Ejemplo n.º 41
0
        private bool SetOptions(String[] args)
        {
            if (args.Length == 0 || args.Length == 1 && args[0].Equals("-help"))
            {
                this.ShowUsage();
                return false;
            }

            String arg;
            int i = 0;
            while (i < args.Length)
            {
                arg = args[i];

                if (arg.StartsWith("-uri:"))
                {
                    if (this._mode == RdfQueryMode.Remote)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify input URIs as well as specifying a remote endpoint to query");
                        return false;
                    }

                    String uri = arg.Substring(5);
                    try
                    {
                        this._mode = RdfQueryMode.Local;

                        //Try and parse RDF from the given URI
                        if (!this._print)
                        {
                            Uri u = new Uri(uri);
                            Graph g = new Graph();
                            UriLoader.Load(g, u);
                            this._store.Add(g);
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since -print has been specified so the query will not be executed so no need to load the data");
                        }
                    }
                    catch (UriFormatException uriEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' since this is not a valid URI");
                        if (this._debug) this.DebugErrors(uriEx);
                    }
                    catch (RdfParseException parseEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                        if (this._debug) this.DebugErrors(parseEx);
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the input URI '" + uri + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                        if (this._debug) this.DebugErrors(ex);
                    }
                }
                else if (arg.StartsWith("-endpoint:"))
                {
                    if (this._mode == RdfQueryMode.Local)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify a remote endpoint to query as well as specifying local files and/or input URIs");
                        return false;
                    }
                    else if (this._mode == RdfQueryMode.Remote)
                    {
                        if (!(this._endpoint is FederatedSparqlRemoteEndpoint))
                        {
                            this._endpoint = new FederatedSparqlRemoteEndpoint(this._endpoint);
                        }
                    }

                    try
                    {
                        this._mode = RdfQueryMode.Remote;
                        if (this._endpoint is FederatedSparqlRemoteEndpoint)
                        {
                            ((FederatedSparqlRemoteEndpoint)this._endpoint).AddEndpoint(new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1))));
                        }
                        else
                        {
                            this._endpoint = new SparqlRemoteEndpoint(new Uri(arg.Substring(arg.IndexOf(':') + 1)));
                        }
                    }
                    catch (UriFormatException uriEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Unable to use remote endpoint with URI '" + arg.Substring(arg.IndexOf(':') + 1) + "' since this is not a valid URI");
                        if (this._debug) this.DebugErrors(uriEx);
                        return false;
                    }
                }
                else if (arg.StartsWith("-output:") || arg.StartsWith("-out:"))
                {
                    this._output = arg.Substring(arg.IndexOf(':') + 1);
                }
                else if (arg.StartsWith("-outformat:"))
                {
                    String format = arg.Substring(arg.IndexOf(':') + 1);
                    try
                    {
                        if (format.Contains("/"))
                        {
                            //MIME Type
                            this._graphWriter = MimeTypesHelper.GetWriter(format);
                            this._resultsWriter = MimeTypesHelper.GetSparqlWriter(format);
                        }
                        else
                        {
                            //File Extension
                            this._graphWriter = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(format));
                            this._resultsWriter = MimeTypesHelper.GetSparqlWriter(MimeTypesHelper.GetMimeType(format));
                        }
                    }
                    catch (RdfException)
                    {
                        Console.Error.WriteLine("rdfQuery: The file extension '" + format + "' could not be used to determine a MIME Type and select a writer - default writers will be used");
                    }
                }
                else if (arg.StartsWith("-syntax"))
                {
                    if (arg.Contains(':'))
                    {
                        String syntax = arg.Substring(arg.IndexOf(':') + 1);
                        switch (syntax)
                        {
                            case "1":
                            case "1.0":
                                this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_0;
                                break;
                            case "1.1":
                                this._parser.SyntaxMode = SparqlQuerySyntax.Sparql_1_1;
                                break;
                            case "E":
                            case "e":
                                this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                                break;
                            default:
                                Console.Error.WriteLine("rdfQuery: The value '" + syntax + "' is not a valid query syntax specifier - assuming SPARQL 1.1 with Extensions");
                                this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                                break;
                        }
                    }
                    else
                    {
                        this._parser.SyntaxMode = SparqlQuerySyntax.Extended;
                    }
                }
                else if (arg.StartsWith("-timeout:"))
                {
                    long timeout;
                    if (Int64.TryParse(arg.Substring(arg.IndexOf(':') + 1), out timeout))
                    {
                        this._timeout = timeout;
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid timeout in milliseconds - default timeouts will be used");
                    }
                }
                else if (arg.StartsWith("-r:"))
                {
                    arg = arg.Substring(arg.IndexOf(':') + 1);
                    switch (arg)
                    {
                        case "rdfs":
                            ((IInferencingTripleStore)this._store).AddInferenceEngine(new RdfsReasoner());
                            break;
                        case "skos":
                            ((IInferencingTripleStore)this._store).AddInferenceEngine(new SkosReasoner());
                            break;
                        default:
                            Console.Error.WriteLine("rdfQuery: The value '" + arg + "' is not a valid Reasoner - ignoring this option");
                            break;
                    }
                }
                else if (arg.StartsWith("-partialResults"))
                {
                    if (arg.Contains(':'))
                    {
                        bool partial;
                        if (Boolean.TryParse(arg.Substring(arg.IndexOf(':') + 1), out partial))
                        {
                            this._partialResults = partial;
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: The value '" + arg.Substring(arg.IndexOf(':') + 1) + "' is not a valid boolean - partial results mode is disabled");
                        }
                    }
                    else
                    {
                        this._partialResults = true;
                    }
                }
                else if (arg.StartsWith("-noopt"))
                {
                    if (arg.Equals("-noopt"))
                    {
                        Options.QueryOptimisation = false;
                        Options.AlgebraOptimisation = false;
                    }
                    else if (arg.Length >= 7)
                    {
                        String opts = arg.Substring(7);
                        foreach (char c in opts.ToCharArray())
                        {
                            if (c == 'a' || c == 'A')
                            {
                                Options.AlgebraOptimisation = false;
                            }
                            else if (c == 'q' || c == 'Q')
                            {
                                Options.QueryOptimisation = false;
                            }
                            else
                            {
                                Console.Error.WriteLine("rdfQuery: The value '" + c + "' as part of the -noopt argument is not supported - it has been ignored");
                            }
                        }
                    }
                }
                else if (arg.Equals("-nocache"))
                {
                    Options.UriLoaderCaching = false;
                }
                else if (arg.Equals("-nobom"))
                {
                    Options.UseBomForUtf8 = false;
                }
                else if (arg.Equals("-print"))
                {
                    this._print = true;
                }
                else if (arg.Equals("-debug"))
                {
                    this._debug = true;
                }
                else if (arg.StartsWith("-explain"))
                {
                    this._explain = true;
                    if (arg.Length > 9)
                    {
                        try
                        {
                            this._level = (ExplanationLevel)Enum.Parse(typeof(ExplanationLevel), arg.Substring(9));
                            this._level = (this._level | ExplanationLevel.OutputToConsoleStdErr | ExplanationLevel.Simulate) ^ ExplanationLevel.OutputToConsoleStdOut;
                        }
                        catch
                        {
                            Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' does not specify a valid Explanation Level");
                            return false;
                        }
                    }
                }
                else if (arg.Equals("-help"))
                {
                    //Ignore Help Argument if other arguments present
                }
                else if (arg.StartsWith("-"))
                {
                    //Report Invalid Argument
                    Console.Error.WriteLine("rdfQuery: The argument '" + arg + "' is not a supported argument - it has been ignored");
                }
                else if (i == args.Length - 1)
                {
                    //Last Argument must be the Query
                    this._query = arg;
                }
                else
                {
                    //Treat as an input file

                    if (this._mode == RdfQueryMode.Remote)
                    {
                        Console.Error.WriteLine("rdfQuery: Cannot specify local files as well as specifying a remote endpoint to query");
                        return false;
                    }

                    try
                    {
                        this._mode = RdfQueryMode.Local;

                        //Try and parse RDF from the given file
                        if (!this._print)
                        {
                            Graph g = new Graph();
                            FileLoader.Load(g, arg);
                            this._store.Add(g);
                        }
                        else
                        {
                            Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' since -print has been specified so the query will not be executed so no need to load the data");
                        }
                    }
                    catch (RdfParseException parseEx)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Parser Error: " + parseEx.Message);
                        if (this._debug) this.DebugErrors(parseEx);
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("rdfQuery: Ignoring the local file '" + arg + "' due to the following error:");
                        Console.Error.WriteLine("rdfQuery: Error: " + ex.Message);
                        if (this._debug) this.DebugErrors(ex);
                    }
                }


                i++;
            }

            return true;
        }
Ejemplo n.º 42
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IHtmlWriter)
     {
         ((IHtmlWriter)writer).Stylesheet = this._stylesheet;
     }
 }
Ejemplo n.º 43
0
 private void CreateIOHandlers(string extension)
 {
     switch (extension)
     {
         case ".nq":
             _storeReader = new NQuadsParser();
             _storeWriter = new NQuadsWriter();
             break;
         case ".ttl":
             _rdfReader = new TurtleParser();
             _rdfWriter = new CompressingTurtleWriter();
             break;
         case ".trig":
             _storeReader = new TriGParser();
             _storeWriter = new TriGWriter();
             break;
         case ".xml":
             _rdfReader = new RdfXmlParser();
             _rdfWriter = new RdfXmlWriter();
             break;
         case ".n3":
             _rdfReader = new Notation3Parser();
             _rdfWriter = new Notation3Writer();
             break;
         case ".trix":
             _storeReader = new TriXParser();
             _storeWriter = new TriXWriter();
             break;
         case ".json":
             _rdfReader = new RdfJsonParser();
             _rdfWriter = new RdfJsonWriter();
             break;
         default:
             throw new ArgumentOutOfRangeException(System.String.Format("Provided file path does not allow to detect a type of the RDF serialization type."));
     }
 }
Ejemplo n.º 44
0
 public void Apply(IRdfWriter writer)
 {
     if (writer is IPrettyPrintingWriter)
     {
         ((IPrettyPrintingWriter)writer).PrettyPrintMode = this._prettyPrint;
     }
 }
Ejemplo n.º 45
0
        private void cboGraphFormat_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.cboGraphFormat.SelectedIndex)
            {
                case 0:
                    this._rdfwriter = new CsvWriter();
                    this._rdfext = ".csv";
                    break;
                case 1:
                    fclsStylesheetPicker stylesheetPicker = new fclsStylesheetPicker("CSS (Optional)");
                    if (stylesheetPicker.ShowDialog() == DialogResult.OK)
                    {
                        HtmlWriter temp = new HtmlWriter();
                        temp.Stylesheet = stylesheetPicker.StylesheetUri;
                        this._rdfwriter = temp;
                    }
                    else
                    {
                        this._rdfwriter = new HtmlWriter();
                    }
                    this._rdfext = ".html";
                    break;
                case 2:
                    this._rdfwriter = new Notation3Writer();
                    this._rdfext = ".n3";
                    break;
                case 3:
                    this._rdfwriter = new NTriplesWriter();
                    this._rdfext = ".nt";
                    break;
                case 4:
                    this._rdfwriter = new RdfJsonWriter();
                    this._rdfext = ".json";
                    break;
                case 5:
                    this._rdfwriter = new RdfXmlWriter();
                    this._rdfext = ".rdf";
                    break;
                case 6:
                    this._rdfwriter = new CompressingTurtleWriter();
                    this._rdfext = ".ttl";
                    break;
                case 7:
                    this._rdfwriter = new TsvWriter();
                    this._rdfext = ".tsv";
                    break;
            }

            if (this._rdfwriter is ICompressingWriter)
            {
                ((ICompressingWriter)this._rdfwriter).CompressionLevel = WriterCompressionLevel.High;
            }

            if (this.cboResultsFormat.SelectedIndex == 1)
            {
                this._resultswriter = new SparqlRdfWriter(this._rdfwriter);
                this._resultsext = this._rdfext;
            }
        }
Ejemplo n.º 46
0
 public SyntaxDefinition(String name, String definitionFile, String[] fileExtensions, IRdfWriter defaultWriter)
     : this(name, definitionFile, fileExtensions)
 {
     this._writer = defaultWriter;
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Selects the appropriate File Extension for the given RDF Writer
        /// </summary>
        /// <param name="writer">RDF Writer</param>
        /// <returns></returns>
        public static String GetFileExtension(IRdfWriter writer)
        {
            if (!_init) Init();
            Type requiredType = writer.GetType();
            foreach (MimeTypeDefinition definition in MimeTypesHelper.Definitions)
            {
                if (requiredType.Equals(definition.RdfWriterType))
                {
                    return definition.CanonicalFileExtension;
                }
            }

            throw new RdfException("Unable to determine the appropriate File Extension for the RDF Writer '" + writer.GetType().ToString() + "'");
        }
Ejemplo n.º 48
0
        private bool SetResultsFormat(String format)
        {
            switch (format)
            {
                case "xml":
                    this._resultsWriter = new SparqlXmlWriter();
                    this._graphWriter = new FastRdfXmlWriter();
                    break;
                case "json":
                    this._resultsWriter = new SparqlJsonWriter();
                    this._graphWriter = new RdfJsonWriter();
                    break;
                case "ntriples":
                    this._graphWriter = new NTriplesWriter();
                    break;
                case "rdfxml":
                    this._graphWriter = new FastRdfXmlWriter();
                    break;
                case "turtle":
                    this._graphWriter = new CompressingTurtleWriter(WriterCompressionLevel.High);
                    break;
                case "n3":
                    this._graphWriter = new Notation3Writer(WriterCompressionLevel.High);
                    break;
                case "html":
                case "rdfa":
                    this._resultsWriter = new SparqlHtmlWriter();
                    this._graphWriter = new HtmlWriter();
                    break;
                case "csv":
                    this._resultsWriter = new SparqlCsvWriter();
                    this._graphWriter = new CsvWriter();
                    break;
                case "tsv":
                    this._resultsWriter = new SparqlTsvWriter();
                    this._graphWriter = new TsvWriter();
                    break;
                default:
                    Console.Error.WriteLine("rdfQuery: The value '" + format + "' is not a valid Results Format");
                    return false;
            }

            return true;
        }
Ejemplo n.º 49
0
 /// <summary>Creates a new instance of the file triple store.</summary>
 /// <param name="fileStream">Stream to read/write.</param>
 /// <param name="rdfReader">RDF reader used to read the file.</param>
 /// <param name="rdfWriter">RDF writer to write the file.</param>
 public FileTripleStore(Stream fileStream, IRdfReader rdfReader, IRdfWriter rdfWriter)
 {
     _fileStream = fileStream;
     _rdfReader = rdfReader;
     _rdfWriter = rdfWriter;
     Read();
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Registers a writer as the default RDF Writer for all the given MIME types and updates relevant definitions to include the MIME types and file extensions
        /// </summary>
        /// <param name="writer">RDF Writer</param>
        /// <param name="mimeTypes">MIME Types</param>
        /// <param name="fileExtensions">File Extensions</param>
        public static void RegisterWriter(IRdfWriter writer, IEnumerable<String> mimeTypes, IEnumerable<String> fileExtensions)
        {
            if (!_init) Init();

            if (!mimeTypes.Any()) throw new RdfException("Cannot register a writer without specifying at least 1 MIME Type");

            //Get any existing defintions that are to be altered
            IEnumerable<MimeTypeDefinition> existing = GetDefinitions(mimeTypes);
            foreach (MimeTypeDefinition def in existing)
            {
                foreach (String type in mimeTypes)
                {
                    def.AddMimeType(type);
                }
                foreach (String ext in fileExtensions)
                {
                    def.AddFileExtension(ext);
                }
                def.RdfWriterType = writer.GetType();
            }

            //Create any new defintions
            IEnumerable<String> newTypes = mimeTypes.Where(t => !GetDefinitions(t).Any());
            if (newTypes.Any())
            {
                MimeTypeDefinition newDef = new MimeTypeDefinition(String.Empty, newTypes, fileExtensions);
                newDef.RdfWriterType = writer.GetType();
                AddDefinition(newDef);
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Creates a new SPARQL RDF Writer which will save Result Sets in the RDF serialization in your chosen RDF Syntax
 /// </summary>
 /// <param name="writer">RDF Writer to use</param>
 public SparqlRdfWriter(IRdfWriter writer)
 {
     this._writer = writer;
 }
Ejemplo n.º 52
0
 public SyntaxDefinition(String name, String definitionFile, String[] fileExtensions, IRdfWriter defaultWriter, ISyntaxValidator validator)
     : this(name, definitionFile, fileExtensions, defaultWriter)
 {
     this._validator = validator;
 }
Ejemplo n.º 53
0
 private bool SetWriter(String format)
 {
     switch (format)
     {
         case "rdfxml":
             this._writer = new FastRdfXmlWriter();
             break;
         case "ntriples":
             this._writer = new NTriplesWriter();
             break;
         case "turtle":
             this._writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
             break;
         case "n3":
             this._writer = new Notation3Writer(WriterCompressionLevel.High);
             break;
         case "html":
         case "rdfa":
             this._writer = new HtmlWriter();
             break;
         case "json":
             this._writer = new RdfJsonWriter();
             break;
         case "dot":
             this._writer = new GraphVizWriter();
             break;
         default:
             Console.Error.WriteLine("rdfConvert: The value '" + format + "' is not a valid format parameter");
             return false;
     }
     return true;
 }
Ejemplo n.º 54
0
        public void RunConvert(String[] args)
        {
            //Single Help Argument means Show Help
            if (args.Length == 1 && (args[0].Equals("-h") || args[0].Equals("--help")))
            {
                this.ShowUsage();
                return;
            }

            //Set the Options
            if (!this.SetOptions(args))
            {
                //If SetOptions returns false then some options were invalid and errors have been output to the error stream
                return;
            }

            if (this._input == null)
            {
                //If no Input then abort
                Console.Error.WriteLine("The required argument Input URI was not specified");
                return;
            }
            if (this._writer == null && !this._count)
            {
                //If no Output Format was specified and the Count option was not specified we abort
                if (!this._quiet) Console.Error.WriteLine("rdfConvert: No Ouput Format specified - using default serializer NTriples");
                this._writer = new NTriplesWriter();                
            }
            if (this._parser == null && !this._guess)
            {
                //Use guess mode if no specific input format or guess mode was specified
                if (!this._quiet) Console.Error.WriteLine("rdfConvert: No Input Format was specified and the guess option was not specified - using default parser RDF/XML");
                this._parser = new RdfXmlParser();
            }
            //Set Parser to Null if using guess mode
            if (this._guess) this._parser = null;
            if (this._parser != null && !this._ignoreWarnings)
            {
                //Output warnings to stderror if not ignoring warnings or using a mode where can't add a handler to the warning
                this._parser.Warning += this.ShowWarnings;
                if (this._writer != null) this._writer.Warning += this.ShowWarnings;
            }
            else if (!this._ignoreWarnings)
            {
                UriLoader.Warning += this.ShowWarnings;
                UriLoader.StoreWarning += this.ShowWarnings;
                FileLoader.Warning += this.ShowWarnings;
                FileLoader.StoreWarning += this.ShowWarnings;
            }

            //Try to parse in the Input
            try
            {
                if (!this._quiet) 
                {
                    if (this._parser != null)
                    {
                        Console.Error.WriteLine("rdfConvert: Parsing URI " + this._input + " with Parser " + this._parser.GetType().Name);
                    }
                    else
                    {
                        Console.Error.WriteLine("rdfConvert: Parsing URI " + this._input + " with guessing of Content Type");
                    }
                }
                if (this._input == "-")
                {
                    //Read from Standard In
                    if (this._guess) 
                    {
                        StringParser.Parse(this._g, Console.In.ReadToEnd());
                    } 
                    else 
                    {
                        this._parser.Load(this._g, new StreamReader(Console.OpenStandardInput()));
                    }
                }
                else
                {
                    try
                    {
                        Uri u = new Uri(this._input);
                        if (u.IsAbsoluteUri)
                        {
                            //Valid Absolute URI
                            UriLoader.Load(this._g, u, this._parser);
                        }
                        else
                        {
                            //If not an absolute URI then probably a filename
                            FileLoader.Load(this._g, this._input, this._parser);
                        }
                    }
                    catch (UriFormatException)
                    {
                        //If not a valid URI then probably a filename
                        FileLoader.Load(this._g, this._input, this._parser);
                    }
                }
            }
            catch (RdfParseException parseEx)
            {
                this.ShowErrors(parseEx, "Parse Error");
                return;
            }
            catch (RdfException rdfEx)
            {
                this.ShowErrors(rdfEx, "RDF Error");
                return;
            }
            catch (Exception ex)
            {
                this.ShowErrors(ex, "Error");
                return;
            }

            if (!this._quiet) Console.Error.WriteLine("rdfConvert: Parsing returned " + this._g.Triples.Count + " Triples");

            //Show only count if that was asked for
            if (this._count)
            {
                Console.WriteLine(this._g.Triples.Count);
                return;
            }

            //Show Namespaces if asked for
            if (this._showNamespaces)
            {
                foreach (String prefix in this._g.NamespaceMap.Prefixes)
                {
                    Console.WriteLine(prefix + ": <" + this._g.NamespaceMap.GetNamespaceUri(prefix).ToString() + ">");
                }
            }

            //Now do the serialization
            if (this._outputBase != null || this._useNullOutputBase)
            {
                //Set the Output Base URI if specified
                this._g.BaseUri = this._outputBase;
            }
            else if (this._useInputBase)
            {
                //Set the Output Base URI to the Input Base URI if specified
                //Have to reset this since parsing the Input may have changed the Base URI
                this._g.BaseUri = this._inputBase;
            }
            try
            {
                if (!this._quiet) Console.Error.WriteLine("rdfConvert: Serializing with serializer " + this._writer.GetType().Name);

                //Save the Graph to Standard Out
                this._writer.Save(this._g, Console.Out);
            }
            catch (RdfOutputException outEx)
            {
                this.ShowErrors(outEx, "Output Error");
                return;
            }
            catch (RdfException rdfEx)
            {
                this.ShowErrors(rdfEx, "RDF Error");
                return;
            }
            catch (Exception ex)
            {
                this.ShowErrors(ex, "Error");
                return;
            }
        }
Ejemplo n.º 55
0
 public SyntaxDefinition(String name, IHighlightingDefinition definition, String[] fileExtensions, IRdfReader defaultParser, IRdfWriter defaultWriter, ISyntaxValidator validator)
     : this(name, definition, fileExtensions, defaultParser, defaultWriter)
 {
     this._validator = validator;
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Creates a new GZipped writer
 /// </summary>
 /// <param name="writer">Underlying writer</param>
 public BaseGZipWriter(IRdfWriter writer)
 {
     if (writer == null) throw new ArgumentNullException("writer");
     this._writer = writer;
     this._writer.Warning += this.RaiseWarning;
 }
Ejemplo n.º 57
0
        private void SaveWith(IRdfWriter writer)
        {
            IRdfReader parser = this._manager.GetParser();
            Graph g = new Graph();
            try
            {
                StringParser.Parse(g, textEditor.Text, parser);
            }
            catch
            {
                MessageBox.Show("Unable to Save With an RDF Writer as the current file is not a valid RDF document when parsed with the " + parser.GetType().Name + ".  If you believe this is a valid RDF document please select the correct Syntax Highlighting from the Options Menu and retry", "Save With Failed");
                return;
            }

            bool filenameRequired = (this._manager.CurrentFile == null);
            if (!filenameRequired)
            {
                MessageBoxResult res = MessageBox.Show("Are you sure you wish to overwrite your existing file with the output of the " + writer.GetType().Name + "?  Click Yes to proceed, No to select a different Filename or Cancel to abort this operation", "Overwrite File",MessageBoxButton.YesNoCancel);
                if (res == MessageBoxResult.Cancel)
                {
                    return;
                }
                else if (res == MessageBoxResult.No)
                {
                    filenameRequired = true;
                }
                else if (res == MessageBoxResult.None)
                {
                    return;
                }
            }

            //Get a Filename to Save to
            String origFilename = this._manager.CurrentFile;
            if (filenameRequired)
            {
                if (_sfd.ShowDialog() == true)
                {
                    this.UpdateMruList(this._sfd.FileName);
                    this._manager.CurrentFile = _sfd.FileName;
                }
                else
                {
                    return;
                }
            }


            try
            {
                writer.Save(g, this._manager.CurrentFile);

                MessageBoxResult res = MessageBox.Show("Would you like to switch editing to the newly created file?", "Switch Editing", MessageBoxButton.YesNo);
                if (res == MessageBoxResult.Yes)
                {
                    try
                    {
                        using (StreamReader reader = new StreamReader(this._manager.CurrentFile))
                        {
                            String text = reader.ReadToEnd();
                            textEditor.Text = String.Empty;
                            textEditor.Text = text;
                            this._manager.AutoDetectSyntax(this._manager.CurrentFile);
                        }
                        this.Title = "rdfEditor - " + System.IO.Path.GetFileName(this._manager.CurrentFile);
                        this._manager.HasChanged = false;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("An error occurred while opening the selected file: " + ex.Message, "Unable to Open File");
                    }
                }
                else
                {
                    if (origFilename != null)
                    {
                        this._manager.CurrentFile = origFilename;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while saving: " + ex.Message, "Save With Failed");
            }
        }
Ejemplo n.º 58
0
 public SyntaxDefinition(String name, IHighlightingDefinition definition, String[] fileExtensions, IRdfWriter defaultWriter)
     : this(name, definition, fileExtensions)
 {
     this._writer = defaultWriter;
 }
Ejemplo n.º 59
0
        public static void TestWriter(StreamWriter output, Graph g, IRdfWriter writer, IRdfReader reader, String file)
        {
            Stopwatch timer = new Stopwatch();

            Console.WriteLine();
            Console.WriteLine(new String('-', file.Length));
            Console.WriteLine(file);
            Console.WriteLine("Attempting serialization with " + writer.GetType().ToString());

            //Show Compression Level
            if (writer is ICompressingWriter)
            {
                Console.WriteLine("Compression Level is " + ((ICompressingWriter)writer).CompressionLevel);
            }

            //Enable Pretty Printing if supported
            if (writer is IPrettyPrintingWriter)
            {
                ((IPrettyPrintingWriter)writer).PrettyPrintMode = true;
            }

            try
            {
                timer.Start();
                writer.Save(g, "writer_tests/" + file + ".out");
                Console.WriteLine("Serialization Done");
            }
            catch (IOException ioEx)
            {
                reportError(output, "IO Exception", ioEx);
            }
            catch (RdfParseException parseEx)
            {
                reportError(output, "Parsing Exception", parseEx);
            }
            catch (RdfException rdfEx)
            {
                reportError(output, "RDF Exception", rdfEx);
            }
            catch (Exception ex)
            {
                reportError(output, "Other Exception", ex);
            }
            finally
            {
                timer.Stop();
                Console.WriteLine("Writing took " + timer.ElapsedMilliseconds + "ms");

                //Get the relevant Reader
                Graph h = new Graph();
                try
                {
                    //Read back in the serialized output to check it's valid RDF
                    Console.WriteLine("Attempting to read back in from serialized Output using " + reader.GetType().ToString());
                    reader.Load(h, "writer_tests/" + file + ".out");
                    Console.WriteLine("Serialized Output was valid RDF");

                    //Check same number of Triples are present
                    if (g.Triples.Count == h.Triples.Count)
                    {
                        Console.WriteLine("Correct number of Triples loaded");
                    }
                    else
                    {
                        throw new RdfException("Incorrect number of Triples loaded, got " + h.Triples.Count + " but expected " + g.Triples.Count);
                    }

                    //Check same number of Subjects are present
                    if (g.Triples.SubjectNodes.Distinct().Count() == h.Triples.SubjectNodes.Distinct().Count())
                    {
                        Console.WriteLine("Correct number of Subjects loaded");
                    }
                    else
                    {
                        throw new RdfException("Incorrect number of Subjects loaded, got " + h.Triples.SubjectNodes.Distinct().Count() + " but expected " + g.Triples.SubjectNodes.Distinct().Count());
                    }

                    //Reserialize to NTriples
                    NTriplesWriter ntwriter = new NTriplesWriter();
                    ntwriter.SortTriples = true;
                    ntwriter.Save(h, "writer_tests/" + file + ".nt");
                    Console.WriteLine("Serialized Output reserialized to NTriples");

                    //Check Graphs are Equal
                    if (g.Equals(h))
                    {
                        Console.WriteLine("Graphs are Equal");
                    }
                    else
                    {
                        Console.WriteLine("First Graphs triples:");
                        foreach (Triple t in g.Triples)
                        {
                            Console.WriteLine(t.ToString());
                        }
                        Console.WriteLine();
                        Console.WriteLine("Second Graph triples:");
                        foreach (Triple t in h.Triples)
                        {
                            Console.WriteLine(t.ToString());
                        }
                        Console.WriteLine();
                        throw new RdfException("Graphs are non-equal");
                    }
                }
                catch (IOException ioEx)
                {
                    reportError(output, "IO Exception", ioEx);
                }
                catch (RdfParseException parseEx)
                {
                    reportError(output, "Parsing Exception", parseEx);
                }
                catch (RdfException rdfEx)
                {
                    reportError(output, "RDF Exception", rdfEx);
                }
                catch (Exception ex)
                {
                    reportError(output, "Other Exception", ex);
                }
                Console.WriteLine();
            }
        }