예제 #1
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");
            }
        }
예제 #2
0
        public void ProcessRequest(HttpContext context)
        {
            //Turn on Response Buffering
            context.Response.Buffer = true;

            //Prepare the Cache Directories
            if (!Path.IsPathRooted(this._cacheDir))
            {
                this._cacheDir = context.Server.MapPath(this._cacheDir);
            }
            if (this._loader == null)
            {
                this._loader = new ExpansionLoader(this._cacheDir);
            }

            //Add our Custom Headers
            try
            {
                context.Response.Headers.Add("X-dotNetRDF-Version", Assembly.GetAssembly(typeof(VDS.RDF.IGraph)).GetName().Version.ToString());
            }
            catch (PlatformNotSupportedException)
            {
                context.Response.AddHeader("X-dotNetRDF-Version", Assembly.GetAssembly(typeof(VDS.RDF.IGraph)).GetName().Version.ToString());
            }

            try
            {
                //Retrieve the desired URI and Profile URI from Querystring parameters
                String uri     = context.Request.QueryString["uri"];
                String profile = context.Request.QueryString["profile"];

                if (uri == null)
                {
                    if (context.Request.Url.Query.Equals(String.Empty))
                    {
                        throw new ArgumentNullException("uri", "Required uri parameter used to designate the URI you wish to expand was not found.  Your request must use a URI of the form " + context.Request.Url.ToString() + "?uri=" + Uri.EscapeDataString("http://example.org"));
                    }
                    else
                    {
                        throw new ArgumentNullException("uri", "Required uri parameter used to designate the URI you wish to expand was not found.  Your request must use a URI of the form " + context.Request.Url.ToString().Replace(context.Request.Url.Query, String.Empty) + "?uri=" + Uri.EscapeDataString("http://example.org"));
                    }
                }

                //Note that the ExpansionLoader class automatically handles all the Caching for us
                IInMemoryQueryableStore store;
                String uriHash = new Uri(uri).GetSha256Hash();
                if (profile == null)
                {
                    //Use Default Profile
                    store = this._loader.Load(new Uri(uri));
                }
                else
                {
                    //Use Custom Profile
                    store = this._loader.Load(new Uri(uri), new Uri(profile));
                }

                String       ctype;
                IStoreWriter writer = MimeTypesHelper.GetStoreWriter(context.Request.AcceptTypes, out ctype);
                context.Response.ContentType = ctype;
                writer.Save(store, new StreamParams(context.Response.OutputStream));
            }
            catch (ArgumentNullException argNull)
            {
                HandleErrors(context, "Missing Argument", argNull);
            }
            catch (RdfParseException parseEx)
            {
                HandleErrors(context, "RDF Parser Error", parseEx);
            }
            catch (RdfException rdfEx)
            {
                HandleErrors(context, "RDF Error", rdfEx);
            }
            catch (Exception ex)
            {
                HandleErrors(context, "Error", ex);
            }
        }
예제 #3
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);
        }