Inheritance: SemWeb.Query.Query
コード例 #1
0
        public object Search(queryrequest xml)
        {
            SemWeb.Query.Query query = null;

            string q = string.Empty;

            try
            {
                query = new SparqlEngine(new StringReader(xml.query));
            }
            catch (QueryFormatException ex)
            {
                var malformed = new malformedquery();

                malformed.faultdetails = ex.Message;

                return malformed;
            }

            // Load the data from sql server
            SemWeb.Stores.SQLStore store;

            string connstr = ConfigurationManager.ConnectionStrings["SemWebDB"].ConnectionString;

            DebugLogging.Log(connstr);

            store = (SemWeb.Stores.SQLStore)SemWeb.Store.CreateForInput(connstr);

            //Create a Sink for the results to be writen once the query is run.
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            try
            {
                // Run the query.
                query.Run(store, sink);

            }
            catch (Exception ex)
            {
                // Run the query.
                query.Run(store, sink);
                DebugLogging.Log("Run the query a second time");
                DebugLogging.Log(ex.Message);

            }
            //flush the writer then  load the memory stream
            writer.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            //Write the memory stream out to the response.
            ASCIIEncoding ascii = new ASCIIEncoding();
            DebugLogging.Log(ascii.GetString(ms.ToArray()).Replace("???", ""));
            writer.Close();

            DebugLogging.Log("End of Processing");

            return SerializeXML.DeserializeObject(ascii.GetString(ms.ToArray()).Replace("???", ""), typeof(sparql)) as sparql;
        }
コード例 #2
0
        public void LocalSparqlQuery1()
        {
            CreateMemoryStore();
            var x = new {Title="foo", FileLocation="bar"};
            ObjectDeserialiserQuerySink sink = new ObjectDeserialiserQuerySink(typeof(Track), x.GetType(), null, false, null, null);
            string qry = CreateQueryForArtist("Rory Blythe");
            Query query = new SparqlEngine(qry);
            //			Query query = new GraphMatch(new N3Reader(new StringReader(qry)));
            query.Run(store, sink);

            foreach (object track in sink.IncomingResults)
            {
                Console.WriteLine(track.ToString());
            }
        }
コード例 #3
0
ファイル: euler.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main(string[] args)
    {
        if (args.Length < 2) {
            Console.WriteLine("Usage: euler.exe axioms.n3 axioms... {questions.n3 | -sparql query.sparql}");
            return;
        }

        // Load Axioms

        bool sparql = false;

        MemoryStore axioms = new MemoryStore();
        for (int i = 0; i < args.Length-1; i++) {
            if (i > 0 && i == args.Length-2 && args[i] == "-sparql") {
                sparql = true;
                break;
            }

            N3Reader axiomsreader = new N3Reader(args[i]);
            axiomsreader.BaseUri = "http://www.example.org/arbitrary/base#";
            axioms.Import(axiomsreader);
        }

        Euler engine = new Euler(axioms);

        // Load question
        if (!sparql) {
            MemoryStore question = new MemoryStore();
            question.Import(new N3Reader(args[args.Length-1]));

            Proof[] proofs = engine.Prove(null, question.ToArray());

            foreach (Proof p in proofs) {
                Console.WriteLine(p.ToString());
            }
        } else {
            using (StreamReader fs = new StreamReader(args[args.Length-1])) {
                string q = fs.ReadToEnd();

                Store store = new Store();
                store.AddReasoner(engine);

                SparqlEngine s = new SparqlEngine(q);
                s.Run(store, Console.Out);
            }
        }
    }
コード例 #4
0
ファイル: query.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main(string[] argv)
    {
        if (argv.Length < 3) {
            Console.WriteLine("Usage: query.exe format queryfile datafile");
            return;
        }

        string format = argv[0];
        string queryfile = argv[1];
        string datafile = argv[2];

        Query query;

        if (format == "rsquary") {
            // Create a simple-entailment "RSquary" query
            // from the N3 file.
            query = new GraphMatch(new N3Reader(queryfile));
        } else {
            // Create a SPARQL query by reading the file's
            // contents.
            query = new SparqlEngine(new StreamReader(queryfile));
        }

        // Load the data file from disk
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));

        // First, print results in SPARQL XML Results format...

        // Create a result sink where results are written to.
        QueryResultSink sink = new SparqlXmlQuerySink(Console.Out);

        // Run the query.
        query.Run(data, sink);

        // Second, print the results via our own custom QueryResultSink...
        query.Run(data, new PrintQuerySink());
    }
コード例 #5
0
    protected void myWizard_NextButtonClick(object sender, System.Web.UI.WebControls.WizardNavigationEventArgs e)
    {
        Query query;
        string queryfile = @"C:\Query.txt";
        string datafile = @"C:\KLM11.n3";
        string str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
        "SELECT distinct ?name ?symp   \n " +
        "FROM <C:/KLM11.owl> \n " +
        " where \n" +
           "{\n" +
           " ?Disease table:disease ?name.\n" +
        " ?Disease table:symptoms ?symp.\n" +
        " ?Disease table:classification ?class.\n" +
          " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\" }\n";

        TextWriter stringWriter = new StringWriter();
        stringWriter.Write(str);

        query = new SparqlEngine(str);
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));

        // First, print results in SPARQL XML Results format...

        // Create a result sink where results are written to.
        XmlTextWriter writer = new XmlTextWriter("C:\\temp\\xmltest3.xml", null);

        QueryResultSink sink = new SparqlXmlQuerySink(writer);

        // Run the query.
        query.Run(data, sink);

        writer.Close();
        TextWriter stringWriter1 = new StringWriter();

        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptoms");
        query.Run(data, stringWriter1);
        //Response.Write(stringWriter1.ToString());

        FileStream fs = new FileStream("C:\\temp\\xmltest3.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        xmldoc = new XmlDocument();
        xmldoc.Load(fs);
        XmlNodeList xmlnode = xmldoc.GetElementsByTagName("binding");
        Console.WriteLine("Here is the list of catalogs\n\n");

        for (int i = 0; i < xmlnode.Count; i++)
        {

            XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

            //XML Attribute Name and Value returned
            //Example: <Book id = "001">

            //First Child of the XML file - Catalog.xml - returned
            //Example: <Author>Mark</Author>

            dt.Rows.Add(xmlnode[i].NextSibling.InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""), xmlnode[i].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""));
            i = i + 1;

        }

        fs.Close();

        str = string.Empty;
        str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
          "SELECT distinct  ?symp   \n " +
          "FROM <C:/KLM11.owl> \n " +
          " where \n" +
         "{\n" +
         " ?Disease table:disease ?name.\n" +
          " ?Disease table:symptoms ?symp.\n" +
          " ?Disease table:classification ?class.\n" +
        " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\" }\n";

        // Response.Write("Catalog Finished");
        query = new SparqlEngine(str);
        data = new MemoryStore();
        data.Import(new N3Reader(datafile));
        PrintQuerySink psink = new PrintQuerySink();
        query.Run(data, psink);

        Question.Text = "Do you have " + psink.al[0].ToString() + "?";
        a = new ArrayList();
        Session["array"] = dt;
        processQuestions();
        Session["item"] = 0;
        Session["a"] = a;
        Session["arraylist"] = psink.al;
        GridView1.DataSource = null;

        //foreach (string s in psink.array)
        //{
        //    CheckBoxList1.Items.Add(new ListItem(s));
        //}
        //CheckBoxList1.
    }
コード例 #6
0
    protected void RadioButtonList2_SelectedIndexChanged(object sender, EventArgs e)
    {
        WizardStepType t = new WizardStepType();
        string result = string.Empty;
        //if (Convert.ToInt32(Session["item"]) <((DataTable)Session["array"]).Rows.Count)
        //{
        //    Question.Text = "Do you have " +((DataTable)Session["array"]).Rows[Convert.ToInt32(Session["item"])][1].ToString()+"?";
        //    Session["item"] = Convert.ToInt32(Session["item"])+1;
        //    RadioButtonList2.Items.Clear();
        //    RadioButtonList2.Items.Add(new ListItem("Yes"));
        //    RadioButtonList2.Items.Add(new ListItem("No"));
        //}
        if (Session["array"] != null)
        {
            if (RadioButtonList2.SelectedItem.Text == "Yes")
            {
                ((ArrayList)Session["a"]).Add("'" + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "'");
                string expr = string.Empty;
                foreach (string items in ((ArrayList)Session["a"]))
                {
                    expr = expr + items + ",";

                }
                //if(expr!=string.Empty)
                // expr="Symptoms in ("+expr.Remove(expr.Length - 1)+") and";

                expr = "Symptoms in( '" + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "') and";
                DataView dv;
                if (GridView1.Rows.Count > 0)
                {
                    string expr1 = string.Empty;

                    foreach (GridViewRow r in GridView1.Rows)
                    {
                        expr1 = expr1 + "'" + r.Cells[0].Text + "',";

                    }
                    expr1 = expr + " Disease in (" + expr1.Remove(expr1.Length - 1) + ")";
                    dv = new DataView(((DataTable)Session["array"]), expr1, "", DataViewRowState.CurrentRows);
                }
                else
                {
                    expr = expr.Remove(expr.Length - 3);
                    dv = new DataView(((DataTable)Session["array"]), expr, "", DataViewRowState.CurrentRows);
                }

                DataTable dt2 = dv.ToTable();

                // foreach (DataRowView drv in dv)

                //{

                //    value = (int)drv["column1"];

                //   }

                //  DataRow[] foundrows = ((DataTable)Session["array"]).Select("Symptoms like '" + ((DataTable)Session["array"]).Rows[Convert.ToInt32(Session["item"])][1].ToString() + "'");

                if (dt2.Rows.Count > 0)
                {
                    GridView1.DataSource = dt2;
                    GridView1.DataBind();
                    //   GridView1.Columns[1].Visible = false;
                    if (GridView1.Rows.Count == 1)
                    {
                        t = myWizard.WizardSteps[2].StepType;
                        if (t == WizardStepType.Complete)
                        {
                            lblName.Text = GridView1.Rows[0].Cells[0].Text;

                            Query query;
                            string queryfile = @"C:\Query.txt";
                            string datafile = @"C:\KLM11.n3";
                            string str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
                            "SELECT distinct ?med  \n " +
                            "FROM <C:/KLM11.N3> \n " +
                            " where \n" +
                           "{\n" +
                           " ?Disease table:disease ?name.\n" +
                            " ?Disease table:symptoms ?symp.\n" +
                            " ?Disease table:classification ?class.\n" +
                          " ?class table:class-name \"" + RadioButtonList1.SelectedItem.Text + "\". \n" +
                          "?name table:disease-name ?nam.\n" +
                          " Filter regex(?nam, \"" + GridView1.Rows[0].Cells[0].Text + "\",\"i\"). \n " +
                          "?name table:medication ?med.\n }";

                            TextWriter stringWriter = new StringWriter();
                            stringWriter.Write(str);

                            query = new SparqlEngine(str);
                            MemoryStore data = new MemoryStore();
                            data.Import(new N3Reader(datafile));

                            PrintQuerySink psink = new PrintQuerySink();
                            query.Run(data, psink);
                            foreach (string s in psink.al)
                                result = result + s + ",";
                            if (result != string.Empty)
                                result = result.Remove(result.Length - 1);

                            //ListBox1.DataSource = psink.al;
                            //ListBox1.DataBind();

                        }

                    }
                    // GridView1.Columns[1].Visible = false;
                }

            }

            if (t != WizardStepType.Complete)
            {

                if (Convert.ToInt32(Session["item"]) < ((ArrayList)Session["arraylist"]).Count - 1)
                {

                    Session["item"] = Convert.ToInt32(Session["item"]) + 1;
                    RadioButtonList2.Items[0].Selected = false;
                    RadioButtonList2.Items[1].Selected = false;
                    Question.Text = "Do you have " + ((ArrayList)Session["arraylist"])[Convert.ToInt32(Session["item"])].ToString() + "?";

                }
            }
            else
            {

                Response.Redirect("~/Patient/DiagResult.aspx?dis='" + GridView1.Rows[0].Cells[0].Text + "' &med='" + result + "'");

            }
        }
    }
コード例 #7
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        Query query;
        XmlDocument xmldoc;
        DataTable dt = new DataTable();
        PrintQuerySink psink = new PrintQuerySink();

        dt.Columns.Add("Name");
        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptom");
        dt.Columns.Add("Medication");

        DirectoryInfo dir = new DirectoryInfo(@"C:\PatientOWLFiles");
        FileInfo[] n3files = dir.GetFiles("*.n3");

        foreach (FileInfo f in n3files)
        {

            string datafile = f.FullName;
            string str = string.Empty;

            if (DropDownList1.SelectedIndex == 0)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp ?medi  \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?dise, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }
            else if (DropDownList1.SelectedIndex == 1)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp  ?medi \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?symp, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }
            else if (DropDownList1.SelectedIndex == 2)
            {
                str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
               "SELECT distinct ?dis ?symp ?medi  \n " +
               "from <" + f.FullName + ">\n " +
               " where \n" +
              "{\n" +
              " ?Disease table:disease ?dis.\n" +
              " ?dis table:symptoms ?sym. \n" +
              " ?dis table:medication ?med. \n" +
              "?dis table:disease-name ?dise.\n" +
               "?sym table:symp-name ?symp.\n" +
               "?med table:med-name ?medi.\n";
                str = str + "Filter regex(?medi, \"" + TextBox1.Text + "\" ,\"i\").\n";

            }

            str = str + "  }\n";

            TextWriter stringWriter = new StringWriter();
            stringWriter.Write(str);

            query = new SparqlEngine(str);
            MemoryStore data = new MemoryStore();
            data.Import(new N3Reader(datafile));

            // First, print results in SPARQL XML Results format...

            // Create a result sink where results are written to.
            XmlTextWriter writer = new XmlTextWriter("C:\\temp\\xmltest3.xml", null);

            QueryResultSink sink = new SparqlXmlQuerySink(writer);

            // Run the query.
            query.Run(data, sink);

            writer.Close();
            TextWriter stringWriter1 = new StringWriter();

            query.Run(data, stringWriter1);

            psink._pName = f.Name.Replace(".n3", "");
            query.Run(data, psink);
            //Response.Write(stringWriter1.ToString());

            //    FileStream fs = new FileStream("C:\\temp\\xmltest3.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            //    xmldoc = new XmlDocument();
            //    xmldoc.Load(fs);
            //    XmlNodeList xmlnode = xmldoc.GetElementsByTagName("binding");

            //    for (int i = 0; i < xmlnode.Count; i++)
            //    {

            //        XmlAttributeCollection xmlattrc = xmlnode[i].Attributes;

            //        //XML Attribute Name and Value returned
            //        //Example: <Book id = "001">

            //        //First Child of the XML file - Catalog.xml - returned
            //        //Example: <Author>Mark</Author>
            //        i = i + 1;
            //        dt.Rows.Add(f.Name.Replace(".n3",""),xmlnode[i].NextSibling.InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""), xmlnode[i-1].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""),xmlnode[i].InnerText.Replace("http://www.owl-ontologies.com/Ontology1183162121.owl#", ""));

            //    }

            //    fs.Close();
        }

        if (psink.list.Count > 0)
        {
            GridView1.DataSource = null;
            Result r = new Result();
            r.R = psink.list;
            GridView1.DataSource = psink.list;

            GridView1.DataBind();
            GridView1.Visible = true;
            lblMessage.Visible = false;
        }
        else
        {
            lblMessage.Text = "No records found";
            lblMessage.Visible = true;
            dt = new DataTable();
        }
    }
コード例 #8
0
    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Query query;
        XmlDocument xmldoc;
        DataTable dt = new DataTable();
        PrintQuerySink psink = new PrintQuerySink();

        string datafile = ListBox1.SelectedValue.ToString();
        string str = string.Empty;
        dt.Columns.Add("Name");
        dt.Columns.Add("Disease");
        dt.Columns.Add("Symptom");
        dt.Columns.Add("Medication");

        str = "PREFIX table:<http://www.owl-ontologies.com/Ontology1183162121.owl#> \n " +
        "SELECT distinct ?dis ?symp ?medi  \n " +
        "from <" + ListBox1.SelectedValue.ToString() + ">\n " +
        " where \n" +
           "{\n" +
           " ?Disease table:disease ?dis.\n" +
           " ?dis table:symptoms ?sym. \n" +
           " ?dis table:medication ?med. \n" +
           "?dis table:disease-name ?dise.\n" +
        "?sym table:symp-name ?symp.\n" +
        "?med table:med-name ?medi.\n }";
        query = new SparqlEngine(str);
        MemoryStore data = new MemoryStore();
        data.Import(new N3Reader(datafile));
        psink._pName = ListBox1.SelectedValue.ToString().Replace(".n3", "").Replace(@"C:\PatientOWLFiles\", "");
        query.Run(data, psink);

        if (psink.list.Count > 0)
        {
            GridView1.DataSource = null;
            Result r = new Result();
            r.R = psink.list;
            GridView1.DataSource = psink.list;
            GridView1.Visible = true;
            GridView1.DataBind();
            lblMessage.Visible = false;
        }
        else
        {
            lblMessage.Text = "No records found";
            GridView1.Visible = false;
            lblMessage.Visible = true;
            dt = new DataTable();
        }
    }
コード例 #9
0
 public RdfSourceWrapper(SelectableSource source, SparqlEngine sparql)
 {
     this.source = source;
     this.sparql = sparql;
 }
コード例 #10
0
ファイル: run-tests.cs プロジェクト: JoshData/semweb-dotnet
    static void RunTest(Entity test, Store manifest)
    {
        Entity rdf_type = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
        Entity mf_PositiveSyntaxTest = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#PositiveSyntaxTest";
        Entity mf_NegativeSyntaxTest = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#NegativeSyntaxTest";
        Entity mf_QueryTest = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#QueryEvaluationTest";
        Entity mf_action = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#action";
        Entity mf_result = "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#result";
        Entity qt_data = "http://www.w3.org/2001/sw/DataAccess/tests/test-query#data";
        Entity qt_query = "http://www.w3.org/2001/sw/DataAccess/tests/test-query#query";

        Entity test_type = (Entity)manifest.SelectObjects(test, rdf_type)[0];
        Entity action = (Entity)manifest.SelectObjects(test, mf_action)[0];

        if (test_type == mf_PositiveSyntaxTest || test_type == mf_NegativeSyntaxTest) {
            // The action is a query.

            // Load the action as a string.
            string q = ReadFile(action.Uri);

            // Run the action.
            try {
                new SparqlEngine(q);
            } catch (SemWeb.Query.QueryFormatException qfe) {
                // On a negative test: Good!
                if (test_type == mf_NegativeSyntaxTest) {
                    pass++;
                    return;
                }

                Console.WriteLine("Test Failed: " + action);
                Console.WriteLine(qfe.Message);
                Console.WriteLine(q);
                Console.WriteLine();
                fail++;
                return;
            }

            // On a positive test: Good!
            if (test_type == mf_PositiveSyntaxTest) {
                pass++;
                return;
            }

            Console.WriteLine("Test Failed: " + action);
            Console.WriteLine("Query is syntactically incorrect.");
            Console.WriteLine(q);
            Console.WriteLine();
            fail++;

        } else if (test_type == mf_QueryTest) {

            Entity data = (Entity)manifest.SelectObjects(action, qt_data)[0];
            Entity query = (Entity)manifest.SelectObjects(action, qt_query)[0];
            Entity result = (Entity)manifest.SelectObjects(test, mf_result)[0];

            MemoryStore data_store = new MemoryStore(new N3Reader(data.Uri));
            string q = ReadFile(query.Uri);

            if (q.IndexOf("ASK") >= 0) {
                Console.WriteLine("ASK Test Skipped: " + test);
                skip++;
                return;
            }

            string run_individual_test = "mono ../../bin/rdfquery.exe -type sparql n3:" + data.Uri + " < " + query.Uri;

            SparqlEngine sp;
            try {
                sp = new SparqlEngine(q);
            } catch (SemWeb.Query.QueryFormatException qfe) {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(qfe.Message);
                Console.WriteLine();
                fail++;
                return;
            }

            QueryResultBuffer results = new QueryResultBuffer();
            bool results_bool = false;
            try {
                if (sp.Type != SparqlEngine.QueryType.Ask)
                    sp.Run(data_store, results);
                else
                    results_bool = sp.Ask(data_store);
            } catch (Exception e) {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(e);
                Console.WriteLine();
                fail++;
                return;
            }

            bool failed = false;
            StringBuilder info = new StringBuilder();

            if (result.Uri.EndsWith(".ttl") || result.Uri.EndsWith(".srx") || result.Uri.EndsWith(".rdf")) {

                bool sorted = false;
                QueryResultBuffer results2 = new QueryResultBuffer();

                if (result.Uri.EndsWith(".srx")) {
                        using (FileStream fs = new FileStream(result.Uri, FileMode.Open))
                            SemWeb.Remote.SparqlHttpSource.ParseSparqlResponse(fs, results2);

                } else if (result.Uri.EndsWith(".rdf") || result.Uri.EndsWith(".ttl")) {
                    RdfReader reader = null;
                    if (result.Uri.EndsWith(".rdf"))
                        reader = new RdfXmlReader(result.Uri);
                    else if (result.Uri.EndsWith(".ttl"))
                        reader = new N3Reader(result.Uri);
                    MemoryStore result_store = new MemoryStore(reader);

                    string rs = "http://www.w3.org/2001/sw/DataAccess/tests/result-set#";
                    Entity rsResultSet = rs + "ResultSet";
                    Entity rsresultVariable = rs + "resultVariable";
                    Entity rssolution = rs + "solution";
                    Entity rsindex = rs + "index";
                    Entity rsbinding = rs + "binding";
                    Entity rsvariable = rs + "variable";
                    Entity rsvalue = rs + "value";

                    // get a list of variables in the query output
                    Entity resultset = result_store.GetEntitiesOfType(rsResultSet)[0];
                    ArrayList vars = new ArrayList();
                    foreach (Literal var in result_store.SelectObjects(resultset, rsresultVariable))
                        vars.Add(new Variable(var.Value));
                    Variable[] varsarray = (Variable[])vars.ToArray(typeof(Variable));

                    // try to order as best we can to our own output, so we sort the results the same way
                    for (int i = 0; i < results.Variables.Length; i++) {
                        if (i >= varsarray.Length) break;
                        for (int j = i; j < varsarray.Length; j++) {
                            if (varsarray[j].LocalName == results.Variables[i].LocalName) {
                                Variable temp = varsarray[i];
                                varsarray[i] = varsarray[j];
                                varsarray[j] = temp;
                                break;
                            }
                        }
                    }

                    Hashtable varmap = new Hashtable();
                    foreach (Variable v in varsarray)
                            varmap[v.LocalName] = varmap.Count;

                    results2.Init(varsarray);

                    Resource[] resultbindings = result_store.SelectObjects(resultset, rssolution);

                    // Try sorting by index
                    int[] indexes = new int[resultbindings.Length];
                    for (int i = 0; i < resultbindings.Length; i++) {
                        Entity binding = (Entity)resultbindings[i];
                        Literal index = (Literal)result_store.SelectObjects(binding, rsindex)[0];
                        indexes[i] = (int)(Decimal)index.ParseValue();
                        sorted = true;
                    }
                    Array.Sort(indexes, resultbindings);

                    // Add bindings into results2.
                    for (int i = 0; i < resultbindings.Length; i++) {
                        Resource[] row = new Resource[vars.Count];
                        Entity binding = (Entity)resultbindings[i];
                        foreach (Entity var in result_store.SelectObjects(binding, rsbinding)) {
                            string name = ((Literal)result_store.SelectObjects(var, rsvariable)[0]).Value;
                            Resource val = result_store.SelectObjects(var, rsvalue)[0];
                            row[(int)varmap[name]] = val;
                        }
                        results2.Add(new VariableBindings(varsarray, row));
                    }
                }

                // Check variable list
                ArrayList vars1 = new ArrayList();
                foreach (Variable v in results.Variables)
                    vars1.Add(v.LocalName);
                ArrayList vars2 = new ArrayList();
                foreach (Variable v in results2.Variables)
                    vars2.Add(v.LocalName);
                failed |= !SetsSame(vars1, vars2, "Result Set Variables", info);

                // Checking bindings
                if (results.Bindings.Count != results2.Bindings.Count) {
                    info.Append("Solutions have different number of bindings.\n");
                    failed = true;
                } else {
                    // Now actually run comparison.

                    if (!sorted) {
                        ((ArrayList)results.Bindings).Sort();
                        ((ArrayList)results2.Bindings).Sort();
                    }

                    for (int i = 0; i < results.Bindings.Count; i++) {
                            VariableBindings b1 = (VariableBindings)results.Bindings[i];
                            VariableBindings b2 = (VariableBindings)results2.Bindings[i];
                            foreach (Variable var in results.Variables) {
                                Resource val1 = b1[var.LocalName];
                                Resource val2 = b2[var.LocalName];
                                if (val1 != val2 && !(val1 is BNode) && !(val2 is BNode)) { // TODO: Test bnodes are returned correctly
                                    info.Append("Binding row " + i + " differ in value of " + var.LocalName + " variable: " + val2 + ", should be: " + val1 + "\n");
                                    failed = true;
                                }
                            }
                    }
                }

            } else {
                skip++;
                Console.WriteLine(test + ": Unknown result type " + result.Uri);
            }

            if (failed) {
                Console.WriteLine("Test Failed: " + test);
                Console.WriteLine(run_individual_test);
                Console.WriteLine(q);
                Console.WriteLine(info.ToString());
                Console.WriteLine();
                fail++;
            } else {
                pass++;
            }

        } else {
            skip++;
            Console.WriteLine(test + ": Unknown test type " + test_type);
            Console.WriteLine();
        }
    }
コード例 #11
0
ファイル: rdfquery.cs プロジェクト: JoshData/semweb-dotnet
    public static void Main(string[] args)
    {
        System.Net.ServicePointManager.Expect100Continue = false;

        Opts opts = new Opts();
        opts.ProcessArgs(args);

        if (opts.RemainingArguments.Length != 1) {
            opts.DoHelp();
            return;
        }

        string baseuri = "query://query/#";

        QueryResultSink qs;
        if (opts.format == "simple")
            qs = new PrintQuerySink();
        else if (opts.format == "html")
            qs = new HTMLQuerySink(Console.Out);
        else if (opts.format == "xml")
            qs = new SparqlXmlQuerySink(Console.Out);
        else if (opts.format == "lubm")
            qs = new LUBMReferenceAnswerOutputQuerySink();
        else if (opts.format == "csv")
            qs = new CSVQuerySink();
        else {
            Console.Error.WriteLine("Invalid output format.");
            return;
        }

        Query query;

        MemoryStore queryModel = null;
        #if !DOTNET2
        System.Collections.ICollection queryModelVars = null;
        #else
        System.Collections.Generic.ICollection<Variable> queryModelVars = null;
        #endif

        Store model = Store.Create(opts.RemainingArguments[0]);

        if (opts.type == "rsquary") {
            RdfReader queryparser = RdfReader.Create("n3", "-");
            queryparser.BaseUri = baseuri;
            queryModel = new MemoryStore(queryparser);
            queryModelVars = queryparser.Variables;
            query = new GraphMatch(queryModel);
        } else if (opts.type == "sparql" && model.DataSources.Count == 1 && model.DataSources[0] is SemWeb.Remote.SparqlSource) {
            string querystring = Console.In.ReadToEnd();
            ((SemWeb.Remote.SparqlSource)model.DataSources[0]).RunSparqlQuery(querystring, Console.Out);
            return;
        } else if (opts.type == "sparql") {
            string querystring = Console.In.ReadToEnd();
            query = new SparqlEngine(querystring);
        } else {
            throw new Exception("Invalid query format: " + opts.type);
        }

        if (opts.limit > 0)
            query.ReturnLimit = opts.limit;

        //Console.Error.WriteLine(query.GetExplanation());

        if (query is SparqlEngine && ((SparqlEngine)query).Type != SparqlEngine.QueryType.Select) {
            SparqlEngine sparql = (SparqlEngine)query;
            sparql.Run(model, Console.Out);
        } else if (model is QueryableSource && queryModel != null) {
            SemWeb.Query.QueryOptions qopts = new SemWeb.Query.QueryOptions();
            qopts.DistinguishedVariables = queryModelVars;

            // Replace bnodes in the query with Variables
            int bnodectr = 0;
            foreach (Entity e in queryModel.GetEntities()) {
                if (e is BNode && !(e is Variable)) {
                    BNode b = (BNode)e;
                    queryModel.Replace(e, new Variable(b.LocalName != null ? b.LocalName : "bnodevar" + (++bnodectr)));
                }
            }

            model.Query(queryModel.ToArray(), qopts, qs);
        } else {
            query.Run(model, qs);
        }

        if (qs is IDisposable)
            ((IDisposable)qs).Dispose();
    }
コード例 #12
0
 protected virtual Query CreateQuery(string query)
 {
     Query sparql = new SparqlEngine(query);
     if (MaximumLimit != -1 && (sparql.ReturnLimit == -1 || sparql.ReturnLimit > MaximumLimit)) sparql.ReturnLimit = MaximumLimit;
     return sparql;
 }