예제 #1
0
        public void RunVocab(String[] args)
        {
            if (args.Length < 2)
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: 2 Arguments are required in order to use the -vocab mode");
                return;
            }

            if (File.Exists(args[1]))
            {
                Console.Error.WriteLine("rdfWebDeploy: Error: Cannot output the configuration vocabulary to " + args[1] + " as a file already exists at that location");
                return;
            }

            TurtleParser ttlparser = new TurtleParser();
            StreamReader reader    = new StreamReader(Assembly.GetAssembly(typeof(IGraph)).GetManifestResourceStream("VDS.RDF.Configuration.configuration.ttl"));
            Graph        g         = new Graph();

            ttlparser.Load(g, reader);

            IRdfWriter writer;

            try
            {
                writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(Path.GetExtension(args[1])));
            }
            catch (RdfWriterSelectionException)
            {
                writer = new CompressingTurtleWriter(WriterCompressionLevel.High);
            }
            writer.Save(g, args[1]);
            Console.WriteLine("rdfWebDeploy: Configuration Vocabulary output to " + args[1]);
        }
        /// <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;
            }
        }
        /// <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");
            }
        }
예제 #4
0
        /// <summary>
        /// Sends the given Graph to the Client via the HTTP Response.
        /// </summary>
        /// <param name="context">HTTP Context.</param>
        /// <param name="g">Graph to send.</param>
        protected void SendResultsToClient(IHttpContext context, IGraph g)
        {
            IRdfWriter writer;
            String     ctype;

            // Look up the MIME Type Definition - if none use GetWriter instead
            MimeTypeDefinition definition = MimeTypesHelper.GetDefinitions(context.GetAcceptTypes()).FirstOrDefault(d => d.CanWriteRdf);

            if (definition != null)
            {
                writer = definition.GetRdfWriter();
                ctype  = definition.CanonicalMimeType;
            }
            else
            {
                writer = MimeTypesHelper.GetWriter(context.GetAcceptTypes(), out ctype);
            }

            // Set up the Writer
            if (writer is ICompressingWriter)
            {
                ((ICompressingWriter)writer).CompressionLevel = Options.DefaultCompressionLevel;
            }

            // Send Content to Client
            context.Response.ContentType = ctype;
            if (definition != null)
            {
                context.Response.ContentEncoding = definition.Encoding;
                writer.Save(g, new StreamWriter(context.Response.OutputStream, definition.Encoding));
            }
            else
            {
                writer.Save(g, new StreamWriter(context.Response.OutputStream));
            }
        }
예제 #5
0
        /// <summary>
        /// Helper function which returns the Results (Graph/Triple Store/SPARQL 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>
        /// <param name="config">Handler Configuration</param>
        public static void SendToClient(HttpContext context, Object result, BaseHandlerConfiguration config)
        {
            MimeTypeDefinition definition = null;
            String             ctype      = "text/plain";

            String[] acceptTypes = HandlerHelper.GetAcceptTypes(context);

            //Return the Results
            if (result is SparqlResultSet)
            {
                ISparqlResultsWriter sparqlWriter = null;

                //Try and get a MIME Type Definition using the HTTP Requests Accept Header
                if (acceptTypes != null)
                {
                    definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteSparqlResults);
                }
                //Try and get the registered Definition for SPARQL Results XML
                if (definition == null)
                {
                    definition = MimeTypesHelper.GetDefinitions(MimeTypesHelper.SparqlXml[0]).FirstOrDefault();
                }
                //If Definition is still null create a temporary definition
                if (definition == null)
                {
                    definition = new MimeTypeDefinition("SPARQL Results XML", MimeTypesHelper.SparqlXml, Enumerable.Empty <String>());
                    definition.SparqlResultsWriterType = typeof(VDS.RDF.Writing.SparqlXmlWriter);
                }

                //Set up the Writer appropriately
                sparqlWriter = definition.GetSparqlResultsWriter();
                context.Response.ContentType = definition.CanonicalMimeType;
                HandlerHelper.ApplyWriterOptions(sparqlWriter, config);

                //Clear any existing Response
                context.Response.Clear();

                //Send Result Set to Client
                context.Response.ContentEncoding = definition.Encoding;
                sparqlWriter.Save((SparqlResultSet)result, new StreamWriter(context.Response.OutputStream, definition.Encoding));
            }
            else if (result is IGraph)
            {
                IRdfWriter rdfWriter = null;

                //Try and get a MIME Type Definition using the HTTP Requests Accept Header
                if (acceptTypes != null)
                {
                    definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteRdf);
                }
                if (definition == null)
                {
                    //If no appropriate definition then use the GetWriter method instead
                    rdfWriter = MimeTypesHelper.GetWriter(acceptTypes, out ctype);
                }
                else
                {
                    rdfWriter = definition.GetRdfWriter();
                }

                //Setup the writer
                if (definition != null)
                {
                    ctype = definition.CanonicalMimeType;
                }
                context.Response.ContentType = ctype;
                HandlerHelper.ApplyWriterOptions(rdfWriter, config);

                //Clear any existing Response
                context.Response.Clear();

                //Send Graph to Client
                if (definition != null)
                {
                    context.Response.ContentEncoding = definition.Encoding;
                    rdfWriter.Save((IGraph)result, new StreamWriter(context.Response.OutputStream, definition.Encoding));
                }
                else
                {
                    rdfWriter.Save((IGraph)result, new StreamWriter(context.Response.OutputStream));
                }
            }
            else if (result is ITripleStore)
            {
                IStoreWriter storeWriter = null;

                //Try and get a MIME Type Definition using the HTTP Requests Accept Header
                if (acceptTypes != null)
                {
                    definition = MimeTypesHelper.GetDefinitions(acceptTypes).FirstOrDefault(d => d.CanWriteRdfDatasets);
                }
                if (definition == null)
                {
                    //If no appropriate definition then use the GetStoreWriter method instead
                    storeWriter = MimeTypesHelper.GetStoreWriter(acceptTypes, out ctype);
                }
                else
                {
                    storeWriter = definition.GetRdfDatasetWriter();
                }

                //Setup the writer
                if (definition != null)
                {
                    ctype = definition.CanonicalMimeType;
                }
                context.Response.ContentType = ctype;
                HandlerHelper.ApplyWriterOptions(storeWriter, config);

                //Clear any existing Response
                context.Response.Clear();

                //Send Triple Store to Client
                if (definition != null)
                {
                    context.Response.ContentEncoding = definition.Encoding;
                    storeWriter.Save((ITripleStore)result, new VDS.RDF.Storage.Params.StreamParams(context.Response.OutputStream, definition.Encoding));
                }
                else
                {
                    storeWriter.Save((ITripleStore)result, new VDS.RDF.Storage.Params.StreamParams(context.Response.OutputStream));
                }
            }
            else if (result is ISparqlDataset)
            {
                //Wrap in a Triple Store and then call self so the Triple Store writing branch of this if gets called instead
                TripleStore store = new TripleStore(new DatasetGraphCollection((ISparqlDataset)result));
                HandlerHelper.SendToClient(context, store, config);
            }
            else
            {
                throw new RdfOutputException("Unexpected Result Object of Type '" + result.GetType().ToString() + "' returned - unable to write Objects of this Type to the HTTP Response");
            }
        }
예제 #6
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.GetWriterByFileExtension(format);
                            this._resultsWriter = MimeTypesHelper.GetSparqlWriterByFileExtension(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);
        }
예제 #7
0
        public void Run()
        {
            if (this._args.Length == 0)
            {
                this.ShowUsage();
            }
            else
            {
                if (!this.ParseOptions())
                {
                    Console.Error.WriteLine("rdfOptStats: Error: One/More options were invalid");
                    return;
                }

                if (this._inputs.Count == 0)
                {
                    Console.Error.WriteLine("rdfOptStats: Error: No Inputs Specified");
                    return;
                }

                List <BaseStatsHandler> handlers = new List <BaseStatsHandler>();
                if (this._subjects && this._predicates && this._objects)
                {
                    handlers.Add(new SPOStatsHandler(this._literals));
                }
                else if (this._subjects && this._predicates)
                {
                    handlers.Add(new SPStatsHandler(this._literals));
                }
                else
                {
                    if (this._subjects)
                    {
                        handlers.Add(new SubjectStatsHandler(this._literals));
                    }
                    if (this._predicates)
                    {
                        handlers.Add(new PredicateStatsHandler(this._literals));
                    }
                    if (this._objects)
                    {
                        handlers.Add(new ObjectStatsHandler(this._literals));
                    }
                }
                if (this._nodes)
                {
                    handlers.Add(new NodeStatsHandler());
                }

                bool        ok = true;
                IRdfHandler handler;
                if (handlers.Count == 1)
                {
                    handler = handlers[0];
                }
                else
                {
                    handler = new MultiHandler(handlers.OfType <IRdfHandler>());
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();
                for (int i = 0; i < this._inputs.Count; i++)
                {
                    Console.WriteLine("rdfOptStats: Processing Input " + (i + 1) + " of " + this._inputs.Count + " - '" + this._inputs[i] + "'");

                    try
                    {
                        FileLoader.Load(handler, this._inputs[i]);
                    }
                    catch (RdfParserSelectionException selEx)
                    {
                        ok = false;
                        Console.Error.WriteLine("rdfOptStats: Error: Unable to select a Parser to read input");
                        break;
                    }
                    catch (RdfParseException parseEx)
                    {
                        ok = false;
                        Console.Error.WriteLine("rdfOptStats: Error: Parsing Error while reading input");
                        break;
                    }
                    catch (RdfException parseEx)
                    {
                        ok = false;
                        Console.Error.WriteLine("rdfOptStats: Error: RDF Error while reading input");
                        break;
                    }
                    catch (Exception ex)
                    {
                        ok = false;
                        Console.Error.WriteLine("rdfOptStats: Error: Unexpected Error while reading input");
                        break;
                    }
                }
                Console.WriteLine("rdfOptStats: Finished Processing Inputs");
                timer.Stop();
                Console.WriteLine("rdfOptStats: Took " + timer.Elapsed + " to process inputs");
                timer.Reset();

                if (ok)
                {
                    //Output the Stats
                    timer.Start();
                    Graph g = new Graph();
                    g.NamespaceMap.Import(handlers.First().Namespaces);
                    try
                    {
                        foreach (BaseStatsHandler h in handlers)
                        {
                            h.GetStats(g);
                        }
                        IRdfWriter writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeTypes(Path.GetExtension(this._file)));
                        if (writer is ICompressingWriter)
                        {
                            ((ICompressingWriter)writer).CompressionLevel = WriterCompressionLevel.High;
                        }
                        if (writer is IHighSpeedWriter)
                        {
                            ((IHighSpeedWriter)writer).HighSpeedModePermitted = false;
                        }
                        writer.Save(g, this._file);

                        Console.WriteLine("rdfOptStats: Statistics output to " + this._file);
                        timer.Stop();
                        Console.WriteLine("rdfOptStats: Took " + timer.Elapsed + " to output statistics");
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine("rdfOptStats: Error: Unexpected error outputting statistics to " + this._file);
                        Console.Error.WriteLine(ex.Message);
                        Console.Error.WriteLine(ex.StackTrace);
                    }
                }
                else
                {
                    Console.Error.WriteLine("rdfOptStats: Error: Unable to output statistics due to errors during input processing");
                }
            }
        }
예제 #8
0
        public BrightstarSparqlResultsType ExecuteSparql(SparqlQuery query, IStore store, TextWriter resultsWriter)
        {
            try
            {
                EnsureValidResultFormat(query);

                var dataset = MakeDataset(store);
                if (_defaultGraphUris != null)
                {
                    dataset.SetDefaultGraph(_defaultGraphUris);
                }

                var queryProcessor = new BrightstarQueryProcessor(store, dataset);
                var queryResult    = queryProcessor.ProcessQuery(query);
                if (queryResult is SparqlResultSet)
                {
                    var sparqlResultSet = (SparqlResultSet)queryResult;
                    ISparqlResultsWriter sparqlResultsWriter = null;
                    if (_sparqlResultsFormat != null)
                    {
                        sparqlResultsWriter =
                            MimeTypesHelper.GetSparqlWriter(new string[] { _sparqlResultsFormat.ToString() });
                    }
                    if (sparqlResultsWriter == null)
                    {
                        throw new NoAcceptableFormatException(typeof(SparqlResultsFormat),
                                                              "No acceptable format provided for writing a SPARQL result set.");
                    }
                    sparqlResultsWriter.Save(sparqlResultSet, resultsWriter);
                    switch (sparqlResultSet.ResultsType)
                    {
                    case SparqlResultsType.Boolean:
                        return(BrightstarSparqlResultsType.Boolean);

                    case SparqlResultsType.VariableBindings:
                        return(BrightstarSparqlResultsType.VariableBindings);

                    default:
                        throw new BrightstarInternalException("Unrecognized SPARQL result type");
                    }
                }
                if (queryResult is IGraph)
                {
                    var g         = (IGraph)queryResult;
                    var rdfWriter = _rdfFormat == null
                                        ? null
                                        : MimeTypesHelper.GetWriter(new string[] { _rdfFormat.ToString() });
                    if (rdfWriter == null)
                    {
                        throw new NoAcceptableFormatException(typeof(RdfFormat),
                                                              "No acceptable format provided for writing an RDF graph result.");
                    }
                    rdfWriter.Save(g, resultsWriter);
                    try
                    {
                        resultsWriter.Flush();
                    }
                    catch (ObjectDisposedException)
                    {
                        // resultWriter is already closed
                    }
                    return(BrightstarSparqlResultsType.Graph);
                }
                throw new BrightstarInternalException(
                          String.Format("Unexpected return type from QueryProcessor.ProcessQuery: {0}",
                                        queryResult.GetType()));
            }
            catch (Exception ex)
            {
                Logging.LogError(BrightstarEventId.SparqlExecutionError,
                                 "Error Executing query {0}. Cause: {1}",
                                 query.ToString(), ex);
                throw;
            }
        }
예제 #9
0
        // See https://github.com/dotnetrdf/dotnetrdf/blob/5b7fc480346c90eb9b164fb4f8ee09f378442d52/Libraries/dotNetRDF.Web/HandlerHelper.cs#L157
        /// <summary>
        /// Helper function which returns the Results (Graph/Triple Store/SPARQL 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>
        /// <param name="config">Handler Configuration</param>
        public static void SendToClient(HttpContext context, SparqlQueryResult result)
        {
            MimeTypeDefinition definition = null;
            const string       TEXT_PLAIN = "text/plain";
            var acceptTypes = context.Request.Headers[HeaderNames.Accept];

            // Return the Results
            if (result.SparqlResultSet != null)
            {
                ISparqlResultsWriter sparqlWriter = null;

                // Try and get a MIME Type Definition using the HTTP Requests Accept Header
                if (acceptTypes.Count > 0)
                {
                    definition = MimeTypesHelper.GetDefinitions((IEnumerable <string>)acceptTypes).FirstOrDefault(d => d.CanWriteSparqlResults);
                }
                // Try and get the registered Definition for SPARQL Results XML
                if (definition == null)
                {
                    definition = MimeTypesHelper.GetDefinitions(MimeTypesHelper.SparqlResultsXml[0]).FirstOrDefault();
                }
                // If Definition is still null create a temporary definition
                if (definition == null)
                {
                    definition = new MimeTypeDefinition("SPARQL Results XML", MimeTypesHelper.SparqlResultsXml, Enumerable.Empty <String>());
                    definition.SparqlResultsWriterType = typeof(VDS.RDF.Writing.SparqlXmlWriter);
                }

                // Set up the Writer appropriately
                sparqlWriter = definition.GetSparqlResultsWriter();
                context.Response.ContentType = definition.CanonicalMimeType;
                // HandlerHelper.ApplyWriterOptions(sparqlWriter, config);

                // Send Result Set to Client
                context.Response.Headers[HeaderNames.ContentEncoding] = definition.Encoding.WebName;
                sparqlWriter.Save(result.SparqlResultSet, new StreamWriter(context.Response.Body, definition.Encoding));
            }
            else if (result.Graph != null)
            {
                IRdfWriter rdfWriter = null;
                var        ctype     = TEXT_PLAIN;
                // Try and get a MIME Type Definition using the HTTP Requests Accept Header
                if (acceptTypes.Count > 0)
                {
                    definition = MimeTypesHelper.GetDefinitions((IEnumerable <string>)acceptTypes).FirstOrDefault(d => d.CanWriteRdf);
                }
                if (definition == null)
                {
                    // If no appropriate definition then use the GetWriter method instead
                    rdfWriter = MimeTypesHelper.GetWriter((IEnumerable <string>)acceptTypes, out ctype);
                }
                else
                {
                    rdfWriter = definition.GetRdfWriter();
                }

                // Setup the writer
                if (definition != null)
                {
                    ctype = definition.CanonicalMimeType;
                }
                context.Response.ContentType = ctype;
                //HandlerHelper.ApplyWriterOptions(rdfWriter, config);

                // Clear any existing Response
                //context.Response.Clear();

                // Send Graph to Client
                if (definition != null)
                {
                    context.Response.Headers[HeaderNames.ContentEncoding] = definition.Encoding.WebName;
                    rdfWriter.Save(result.Graph, new StreamWriter(context.Response.Body, definition.Encoding));
                }
                else
                {
                    rdfWriter.Save(result.Graph, new StreamWriter(context.Response.Body));
                }
            }
            else
            {
                Debug.Assert(result == SparqlQueryResult.Null);
            }
        }
예제 #10
0
        private void mnuSaveConnection_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null)
            {
                if (this.ActiveMdiChild is StoreManagerForm)
                {
                    Object manager;
                    if (this.ActiveMdiChild is StoreManagerForm)
                    {
                        manager = ((StoreManagerForm)this.ActiveMdiChild).Manager;
                    }
                    else
                    {
                        return;
                    }
                    if (manager is IConfigurationSerializable)
                    {
                        this.sfdConnection.Filter = MimeTypesHelper.GetFilenameFilter(true, false, false, false, false, false);
                        if (this.sfdConnection.ShowDialog() == DialogResult.OK)
                        {
                            //Append to existing configuration file or overwrite?
                            ConfigurationSerializationContext context;
                            if (File.Exists(this.sfdConnection.FileName))
                            {
                                DialogResult result = MessageBox.Show("The selected connection file already exists - would you like to append this connection to that file?  Click Yes to append to this file, No to overwrite and Cancel to abort", "Append Connection?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                                switch (result)
                                {
                                case DialogResult.Yes:
                                    Graph g = new Graph();
                                    FileLoader.Load(g, this.sfdConnection.FileName);
                                    context = new ConfigurationSerializationContext(g);
                                    break;

                                case DialogResult.No:
                                    context = new ConfigurationSerializationContext();
                                    break;

                                default:
                                    return;
                                }
                            }
                            else
                            {
                                //Create new configuration file
                                context = new ConfigurationSerializationContext();
                            }

                            //Save the Connection
                            ((IConfigurationSerializable)manager).SerializeConfiguration(context);

                            try
                            {
                                IRdfWriter writer = MimeTypesHelper.GetWriter(MimeTypesHelper.GetMimeType(Path.GetExtension(this.sfdConnection.FileName)));
                                writer.Save(context.Graph, this.sfdConnection.FileName);
                            }
                            catch (RdfWriterSelectionException)
                            {
                                CompressingTurtleWriter ttlwriter = new CompressingTurtleWriter(WriterCompressionLevel.High);
                                ttlwriter.Save(context.Graph, this.sfdConnection.FileName);
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Unable to save the current connection as it does not support this feature", "Save Unavailable", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    this.mnuSaveConnection.Enabled = false;
                }
            }
            else
            {
                this.mnuSaveConnection.Enabled = false;
            }
        }
예제 #11
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);
        }