[OpenLayers-Commits] r11065 - in trunk/openlayers: examples lib lib/OpenLayers/Format tests tests/Format

commits-20090109 at openlayers.org commits-20090109 at openlayers.org
Fri Jan 28 18:15:10 EST 2011


Author: tschaub
Date: 2011-01-28 15:15:10 -0800 (Fri, 28 Jan 2011)
New Revision: 11065

Added:
   trunk/openlayers/examples/cql-format.html
   trunk/openlayers/examples/cql-format.js
   trunk/openlayers/lib/OpenLayers/Format/CQL.js
   trunk/openlayers/tests/Format/CQL.html
Modified:
   trunk/openlayers/lib/OpenLayers.js
   trunk/openlayers/tests/list-tests.html
Log:
Adding a parser for reading and writing CQL.  This can be used to create filters to be used in rules when styling or it can be used to serialize filters when making requests to services that supprot CQL.  p=dwinslow, r=me (closes #2522)

Added: trunk/openlayers/examples/cql-format.html
===================================================================
--- trunk/openlayers/examples/cql-format.html	                        (rev 0)
+++ trunk/openlayers/examples/cql-format.html	2011-01-28 23:15:10 UTC (rev 11065)
@@ -0,0 +1,51 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+    <head>
+        <title>
+            OpenLayers CQL Example
+        </title>
+        <link rel="stylesheet" href="../theme/default/style.css" type="text/css">
+        <link rel="stylesheet" href="style.css" type="text/css">
+        <style>
+            #cql {
+                width: 400px;
+            }
+            #output {
+                padding-top: 1em;
+                width: 512px;
+                height: 60px;
+                border: none;
+                color: #ff3333;
+            }
+        </style>
+        <script src="../lib/OpenLayers.js"></script>
+    </head>
+    <body>
+        <h1 id="title">CQL Filter Example</h1>
+        <div id="tags">
+            CQL, filter
+        </div>
+        <p id="shortdesc">
+            Demonstrate use the CQL filter.
+        </p>
+        <div id="map" class="smallmap"></div>
+        <div id="docs">
+            <p>
+                Enter text for a CQL filter to update the features displayed.
+                <br>
+                <form name="cql_form" id="cql_form">
+                    <label for="cql">CQL</label>
+                    <input id="cql" type="text" value="STATE_ABBR >= 'B' AND STATE_ABBR <= 'O'">
+                    <input type="submit" value="update">
+                    <input type="reset" value="reset">
+                </form>
+                <textarea id="output"></textarea>
+            </p><p>
+                View the <a href="cql-filter.js" target="_blank">cql-filter.js source</a> 
+                to see how this is done.
+            </p>
+        </div>
+        <script src="cql-format.js"></script>
+        <script src="http://demo.opengeo.org/geoserver/wfs?service=WFS&amp;version=1.0.0&amp;request=GetFeature&amp;typename=topp:states&amp;outputFormat=json&amp;format_options=callback:loadFeatures" type="text/javascript"></script>
+    </body>
+</html>

Added: trunk/openlayers/examples/cql-format.js
===================================================================
--- trunk/openlayers/examples/cql-format.js	                        (rev 0)
+++ trunk/openlayers/examples/cql-format.js	2011-01-28 23:15:10 UTC (rev 11065)
@@ -0,0 +1,61 @@
+
+// use a CQL parser for easy filter creation
+var format = new OpenLayers.Format.CQL();
+
+// this rule will get a filter from the CQL text in the form
+var rule = new OpenLayers.Rule({
+    // We could also set a filter here.  E.g.
+    // filter: format.read("STATE_ABBR >= 'B' AND STATE_ABBR <= 'O'"),
+    symbolizer: {
+        fillColor: "#ff0000",
+        strokeColor: "#ffcccc",
+        fillOpacity: "0.5"
+    }    
+});
+
+var states = new OpenLayers.Layer.Vector("States", {
+    styleMap: new OpenLayers.StyleMap({
+        "default": new OpenLayers.Style(null, {rules: [rule]})
+    })
+});
+
+var map = new OpenLayers.Map({
+    div: "map",
+    layers: [
+        new OpenLayers.Layer.WMS(
+            "OpenLayers WMS",
+            "http://maps.opengeo.org/geowebcache/service/wms",
+            {layers: "openstreetmap", format: "image/png"}
+        ),
+        states
+    ],
+    center: new OpenLayers.LonLat(-101, 39),
+    zoom: 3
+});
+
+// called when features are fetched
+function loadFeatures(data) {
+    var features = new OpenLayers.Format.GeoJSON().read(data);
+    states.addFeatures(features);
+};
+
+// update filter and redraw when form is submitted
+var cql = document.getElementById("cql");
+var output = document.getElementById("output");
+function updateFilter() {
+    var filter;
+    try {
+        filter = format.read(cql.value);
+    } catch (err) {
+        output.value = err.message;
+    }
+    if (filter) {
+        output.value = "";
+        rule.filter = filter;
+        states.redraw();
+    }
+    return false;
+}
+updateFilter();
+var form = document.getElementById("cql_form");
+form.onsubmit = updateFilter;

Added: trunk/openlayers/lib/OpenLayers/Format/CQL.js
===================================================================
--- trunk/openlayers/lib/OpenLayers/Format/CQL.js	                        (rev 0)
+++ trunk/openlayers/lib/OpenLayers/Format/CQL.js	2011-01-28 23:15:10 UTC (rev 11065)
@@ -0,0 +1,438 @@
+/* Copyright (c) 2006-2011 by OpenLayers Contributors (see authors.txt for 
+ * full list of contributors). Published under the Clear BSD license.  
+ * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
+ * full text of the license. */
+
+/**
+ * @requires OpenLayers/Format/WKT.js
+ */
+
+/**
+ * Class: OpenLayers.Format.CQL
+ * Read CQL strings to get <OpenLayers.Filter> objects.  Write 
+ *     <OpenLayers.Filter> objects to get CQL strings. Create a new parser with 
+ *     the <OpenLayers.Format.CQL> constructor.
+ *
+ * Inherits from:
+ *  - <OpenLayers.Format>
+ */
+OpenLayers.Format.CQL = (function() {
+    
+    var tokens = [
+        "PROPERTY", "COMPARISON", "VALUE", "LOGICAL"
+    ],
+
+    patterns = {
+        PROPERTY: /^[_a-zA-Z]\w*/,
+        COMPARISON: /^(=|<>|<=|<|>=|>|LIKE)/i,
+        COMMA: /^,/,
+        LOGICAL: /^(AND|OR)/i,
+        VALUE: /^('\w+'|\d+(\.\d*)?|\.\d+)/,
+        LPAREN: /^\(/,
+        RPAREN: /^\)/,
+        SPATIAL: /^(BBOX|INTERSECTS|DWITHIN|WITHIN|CONTAINS)/i,
+        NOT: /^NOT/i,
+        BETWEEN: /^BETWEEN/i,
+        GEOMETRY: function(text) {
+            var type = /^(POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)/.exec(text);
+            if (type) {
+                var len = text.length;
+                var idx = text.indexOf("(", type[0].length);
+                if (idx > -1) {
+                    var depth = 1;
+                    while (idx < len && depth > 0) {
+                        idx++;
+                        switch(text.charAt(idx)) {
+                            case '(':
+                                depth++;
+                                break;
+                            case ')':
+                                depth--;
+                                break;
+                            default:
+                                // in default case, do nothing
+                        }
+                    }
+                }
+                return [text.substr(0, idx+1)];
+            }
+        },
+        END: /^$/
+    },
+
+    follows = {
+        LPAREN: ['GEOMETRY', 'SPATIAL', 'PROPERTY', 'VALUE', 'LPAREN'],
+        RPAREN: ['NOT', 'LOGICAL', 'END', 'RPAREN'],
+        PROPERTY: ['COMPARISON', 'BETWEEN', 'COMMA'],
+        BETWEEN: ['VALUE'],
+        COMPARISON: ['VALUE'],
+        COMMA: ['GEOMETRY', 'VALUE', 'PROPERTY'],
+        VALUE: ['LOGICAL', 'COMMA', 'RPAREN', 'END'],
+        SPATIAL: ['LPAREN'],
+        LOGICAL: ['NOT', 'VALUE', 'SPATIAL', 'PROPERTY', 'LPAREN'],
+        NOT: ['PROPERTY', 'LPAREN'],
+        GEOMETRY: ['COMMA', 'RPAREN']
+    },
+
+    operators = {
+        '=': OpenLayers.Filter.Comparison.EQUAL_TO,
+        '<>': OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
+        '<': OpenLayers.Filter.Comparison.LESS_THAN,
+        '<=': OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO,
+        '>': OpenLayers.Filter.Comparison.GREATER_THAN,
+        '>=': OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
+        'LIKE': OpenLayers.Filter.Comparison.LIKE,
+        'BETWEEN': OpenLayers.Filter.Comparison.BETWEEN
+    },
+
+    operatorReverse = {},
+
+    logicals = {
+        'AND': OpenLayers.Filter.Logical.AND,
+        'OR': OpenLayers.Filter.Logical.OR
+    },
+
+    logicalReverse = {},
+
+    precedence = {
+        'RPAREN': 3,
+        'LOGICAL': 2,
+        'COMPARISON': 1
+    };
+
+    var i;
+    for (i in operators) {
+        if (operators.hasOwnProperty(i)) {
+            operatorReverse[operators[i]] = i;
+        }
+    }
+
+    for (i in logicals) {
+        if (logicals.hasOwnProperty(i)) {
+            logicalReverse[logicals[i]] = i;
+        }
+    }
+
+    function tryToken(text, pattern) {
+        if (pattern instanceof RegExp) {
+            return pattern.exec(text);
+        } else {
+            return pattern(text);
+        }
+    }
+
+    function nextToken(text, tokens) {
+        var i, token, len = tokens.length;
+        for (i=0; i<len; i++) {
+            token = tokens[i];
+            var pat = patterns[token];
+            var matches = tryToken(text, pat);
+            if (matches) {
+                var match = matches[0];
+                var remainder = text.substr(match.length).replace(/^\s*/, "");
+                return {
+                    type: token,
+                    text: match,
+                    remainder: remainder
+                };
+            }
+        }
+
+        var msg = "ERROR: In parsing: [" + text + "], expected one of: ";
+        for (i=0; i<len; i++) {
+            token = tokens[i];
+            msg += "\n    " + token + ": " + patterns[token];
+        }
+
+        throw new Error(msg);
+    }
+
+    function tokenize(text) {
+        var results = [];
+        var token, expect = ["NOT", "GEOMETRY", "SPATIAL", "PROPERTY", "LPAREN"];
+
+        do {
+            token = nextToken(text, expect);
+            text = token.remainder;
+            expect = follows[token.type];
+            if (token.type != "END" && !expect) {
+                throw new Error("No follows list for " + token.type);
+            }
+            results.push(token);
+        } while (token.type != "END");
+
+        return results;
+    }
+
+    function buildAst(tokens) {
+        var operatorStack = [],
+            postfix = [];
+
+        while (tokens.length) {
+            var tok = tokens.shift();
+            switch (tok.type) {
+                case "PROPERTY":
+                case "GEOMETRY":
+                case "VALUE":
+                    postfix.push(tok);
+                    break;
+                case "COMPARISON":
+                case "BETWEEN":
+                case "LOGICAL":
+                    var p = precedence[tok.type];
+
+                    while (operatorStack.length > 0 &&
+                        (precedence[operatorStack[operatorStack.length - 1].type] <= p)
+                    ) {
+                        postfix.push(operatorStack.pop());
+                    }
+
+                    operatorStack.push(tok);
+                    break;
+                case "SPATIAL":
+                case "NOT":
+                case "LPAREN":
+                    operatorStack.push(tok);
+                    break;
+                case "RPAREN":
+                    while (operatorStack.length > 0 &&
+                        (operatorStack[operatorStack.length - 1].type != "LPAREN")
+                    ) {
+                        postfix.push(operatorStack.pop());
+                    }
+                    operatorStack.pop(); // toss out the LPAREN
+
+                    if (operatorStack.length > 0 &&
+                        operatorStack[operatorStack.length-1].type == "SPATIAL") {
+                        postfix.push(operatorStack.pop());
+                    }
+                case "COMMA":
+                case "END":
+                    break;
+                default:
+                    throw new Error("Unknown token type " + tok.type);
+            }
+        }
+
+        while (operatorStack.length > 0) {
+            postfix.push(operatorStack.pop());
+        }
+
+        function buildTree() {
+            var tok = postfix.pop();
+            switch (tok.type) {
+                case "LOGICAL":
+                    var rhs = buildTree(),
+                        lhs = buildTree();
+                    return new OpenLayers.Filter.Logical({
+                        filters: [lhs, rhs],
+                        type: logicals[tok.text.toUpperCase()]
+                    });
+                case "NOT":
+                    var operand = buildTree();
+                    return new OpenLayers.Filter.Logical({
+                        filters: [operand],
+                        type: OpenLayers.Filter.Logical.NOT
+                    });
+                case "BETWEEN":
+                    var min, max, property;
+                    postfix.pop(); // unneeded AND token here
+                    max = buildTree();
+                    min = buildTree();
+                    property = buildTree();
+                    return new OpenLayers.Filter.Comparison({
+                        property: property,
+                        lowerBoundary: min,
+                        upperBoundary: max,
+                        type: OpenLayers.Filter.Comparison.BETWEEN
+                    });
+                case "COMPARISON":
+                    var value = buildTree(),
+                        property = buildTree();
+                    return new OpenLayers.Filter.Comparison({
+                        property: property,
+                        value: value,
+                        type: operators[tok.text.toUpperCase()]
+                    });
+                case "VALUE":
+                    if ((/^'.*'$/).test(tok.text)) {
+                        return tok.text.substr(1, tok.text.length - 2);
+                    } else {
+                        return Number(tok.text);
+                    }
+                case "SPATIAL":
+                    switch(tok.text.toUpperCase()) {
+                        case "BBOX":
+                            var maxy = buildTree(),
+                                maxx = buildTree(),
+                                miny = buildTree(),
+                                minx = buildTree(),
+                                prop = buildTree();
+
+                            return new OpenLayers.Filter.Spatial({
+                                type: OpenLayers.Filter.Spatial.BBOX,
+                                property: prop,
+                                value: OpenLayers.Bounds.fromArray(
+                                    [minx, miny, maxx, maxy]
+                                )
+                            });
+                        case "INTERSECTS":
+                            var value = buildTree(),
+                                property = buildTree();
+                            return new OpenLayers.Filter.Spatial({
+                                type: OpenLayers.Filter.Spatial.INTERSECTS,
+                                property: property,
+                                value: value
+                            });
+                        case "WITHIN":
+                            var value = buildTree(),
+                                property = buildTree();
+                            return new OpenLayers.Filter.Spatial({
+                                type: OpenLayers.Filter.Spatial.WITHIN,
+                                property: property,
+                                value: value
+                            });
+                        case "CONTAINS":
+                            var value = buildTree(),
+                                property = buildTree();
+                            return new OpenLayers.Filter.Spatial({
+                                type: OpenLayers.Filter.Spatial.CONTAINS,
+                                property: property,
+                                value: value
+                            });
+                        case "DWITHIN":
+                            var distance = buildTree(),
+                                value = buildTree(),
+                                property = buildTree();
+                            return new OpenLayers.Filter.Spatial({
+                                type: OpenLayers.Filter.Spatial.DWITHIN,
+                                value: value,
+                                property: property,
+                                distance: Number(distance)
+                            });
+                    }
+                case "GEOMETRY":
+                    return OpenLayers.Geometry.fromWKT(tok.text);
+                default:
+                    return tok.text;
+            }
+        }
+
+        var result = buildTree();
+        if (postfix.length > 0) {
+            var msg = "Remaining tokens after building AST: \n";
+            for (var i = postfix.length - 1; i >= 0; i--) {
+                msg += postfix[i].type + ": " + postfix[i].text + "\n";
+            }
+            throw new Error(msg);
+        }
+
+        return result;
+    }
+
+    return OpenLayers.Class(OpenLayers.Format, {
+        /**
+         * APIMethod: read
+         * Generate a filter from a CQL string.
+
+         * Parameters:
+         * text - {String} The CQL text.
+         *
+         * Returns:
+         * {<OpenLayers.Filter>} A filter based on the CQL text.
+         */
+        read: function(text) { 
+            var result = buildAst(tokenize(text));
+            if (this.keepData) {
+                this.data = result;
+            };
+            return result;
+        },
+
+        /**
+         * APIMethod: write
+         * Convert a filter into a CQL string.
+
+         * Parameters:
+         * filter - {<OpenLayers.Filter>} The filter.
+         *
+         * Returns:
+         * {String} A CQL string based on the filter.
+         */
+        write: function(filter) {
+            if (filter instanceof OpenLayers.Geometry) {
+                return filter.toString();
+            }
+            switch (filter.CLASS_NAME) {
+                case "OpenLayers.Filter.Spatial":
+                    switch(filter.type) {
+                        case OpenLayers.Filter.Spatial.BBOX:
+                            return "BBOX(" +
+                                filter.property + "," +
+                                filter.value.toBBOX() +
+                                ")";
+                        case OpenLayers.Filter.Spatial.DWITHIN:
+                            return "DWITHIN(" +
+                                filter.property + ", " +
+                                this.write(filter.value) + ", " +
+                                filter.distance + ")";
+                        case OpenLayers.Filter.Spatial.WITHIN:
+                            return "WITHIN(" +
+                                filter.property + ", " +
+                                this.write(filter.value) + ")";
+                        case OpenLayers.Filter.Spatial.INTERSECTS:
+                            return "INTERSECTS(" +
+                                filter.property + ", " +
+                                this.write(filter.value) + ")";
+                        case OpenLayers.Filter.Spatial.CONTAINS:
+                            return "CONTAINS(" +
+                                filter.property + ", " +
+                                this.write(filter.value) + ")";
+                        default:
+                            throw new Error("Unknown spatial filter type: " + filter.type);
+                    }
+                case "OpenLayers.Filter.Logical":
+                    if (filter.type == OpenLayers.Filter.Logical.NOT) {
+                        // TODO: deal with precedence of logical operators to 
+                        // avoid extra parentheses (not urgent)
+                        return "NOT (" + this.write(filter.filters[0]) + ")";
+                    } else {
+                        var res = "(";
+                        var first = true;
+                        for (var i = 0; i < filter.filters.length; i++) {
+                            if (first) {
+                                first = false;
+                            } else {
+                                res += ") " + logicalReverse[filter.type] + " (";
+                            }
+                            res += this.write(filter.filters[i]);
+                        }
+                        return res + ")";
+                    }
+                case "OpenLayers.Filter.Comparison":
+                    if (filter.type == OpenLayers.Filter.Comparison.BETWEEN) {
+                        return filter.property + " BETWEEN " + 
+                            this.write(filter.lowerBoundary) + " AND " + 
+                            this.write(filter.upperBoundary);
+                    } else {
+                        
+                        return filter.property +
+                            " " + operatorReverse[filter.type] + " " + 
+                            this.write(filter.value);
+                    }
+                case undefined:
+                    if (typeof filter === "string") {
+                        return "'" + filter + "'";
+                    } else if (typeof filter === "number") {
+                        return String(filter);
+                    }
+                default:
+                    throw new Error("Can't encode: " + filter.CLASS_NAME + " " + filter);
+            }
+        },
+
+        CLASS_NAME: "OpenLayers.Format.CQL"
+
+    });
+})();
+

Modified: trunk/openlayers/lib/OpenLayers.js
===================================================================
--- trunk/openlayers/lib/OpenLayers.js	2011-01-27 20:49:34 UTC (rev 11064)
+++ trunk/openlayers/lib/OpenLayers.js	2011-01-28 23:15:10 UTC (rev 11065)
@@ -251,6 +251,7 @@
             "OpenLayers/Format/WMSDescribeLayer.js",
             "OpenLayers/Format/WMSDescribeLayer/v1_1.js",
             "OpenLayers/Format/WKT.js",
+            "OpenLayers/Format/CQL.js",
             "OpenLayers/Format/OSM.js",
             "OpenLayers/Format/GPX.js",
             "OpenLayers/Format/Filter.js",

Added: trunk/openlayers/tests/Format/CQL.html
===================================================================
--- trunk/openlayers/tests/Format/CQL.html	                        (rev 0)
+++ trunk/openlayers/tests/Format/CQL.html	2011-01-28 23:15:10 UTC (rev 11065)
@@ -0,0 +1,287 @@
+<html>
+    <head>
+        <script src="../../lib/OpenLayers.js"></script>
+
+        <script type="text/javascript">
+
+function test_CQL_Constructor(t) {
+    t.plan(5);
+    var options = {'foo': 'bar'};
+    var format  = new OpenLayers.Format.CQL(options);
+    t.ok(format instanceof OpenLayers.Format.CQL,
+         "new OpenLayers.Format.CQL object");
+    t.eq(format.foo, "bar", "constructor sets options correctly")
+    t.eq(typeof format.read, 'function', 'format has a read function');
+    t.eq(typeof format.write, 'function', 'format has a write function');
+    t.eq(format.options, options, "format.options correctly set");
+}
+
+function test_Comparison_string(t) {
+    t.plan(5);
+    var test_cql, format, filter;
+    test_cql = "X >= 'B'";
+    format = new OpenLayers.Format.CQL();
+    filter = format.read(test_cql);
+    t.ok(filter instanceof OpenLayers.Filter.Comparison,
+         "Parsing a simple >= filter produces a Filter.Comparison");
+    t.eq(filter.type, OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
+         ">= parsed as Filter.Comparison.GREATER_THAN_OR_EQUAL_TO");
+    t.eq(filter.property, 'X',
+         "Property extracted from CQL text");
+    t.eq(filter.value, 'B',
+         "Value extracted from CQL text");
+         
+         
+    t.eq(format.write(filter), test_cql, "write returned test cql");
+}
+
+function test_Comparison_number(t) {
+    t.plan(5);
+    var test_cql, format, filter;
+    test_cql = "X >= 10";
+    format = new OpenLayers.Format.CQL();
+    filter = format.read(test_cql);
+    t.ok(filter instanceof OpenLayers.Filter.Comparison,
+         "Parsing a simple >= filter produces a Filter.Comparison");
+    t.eq(filter.type, OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
+         ">= parsed as Filter.Comparison.GREATER_THAN_OR_EQUAL_TO");
+    t.eq(filter.property, 'X',
+         "Property extracted from CQL text");
+    t.eq(filter.value, 10,
+         "Value extracted from CQL text");
+         
+         
+    t.eq(format.write(filter), test_cql, "write returned test cql");
+}
+
+function test_Logical(t) {
+    t.plan(7);
+    var test_cql, format, filter;
+    test_cql = "X >= 'B' AND X < 'M'";
+    format = new OpenLayers.Format.CQL();
+    filter = format.read(test_cql);
+    t.ok(filter instanceof OpenLayers.Filter.Logical,
+         "Parsing ANDed filters produces a Filter.Logical");
+    t.eq(filter.type, OpenLayers.Filter.Logical.AND,
+         "AND parsed as Filter.Logical.AND");
+    t.eq(filter.filters.length, 2,
+         "AND Filter contains two subfilters");
+    t.ok(filter.filters[0] instanceof OpenLayers.Filter.Comparison,
+         "First sub-filter is a Filter.Comparison");
+    t.eq(filter.filters[0].type, OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO,
+         "First sub-filter is the first filter in the CQL text");
+    t.ok(filter.filters[1] instanceof OpenLayers.Filter.Comparison,
+         "Second sub-filter is a Filter.Comparison");
+    t.eq(filter.filters[1].type, OpenLayers.Filter.Comparison.LESS_THAN,
+         "Second sub-filter is the second filter in the CQL text");
+
+}
+
+function test_Logical_write(t) {
+    t.plan(1);
+    var cql = "(X >= 'B') AND (X < 'M')";
+    var format = new OpenLayers.Format.CQL();
+    var filter = format.read(cql);
+    t.eq(format.write(filter), cql, "write returned test cql");
+}
+
+function test_Logical_spatial(t) {
+    t.plan(9);
+    var test_cql, format, filter;
+    test_cql = "INTERSECTS(the_geom, POLYGON((-111 41,-115 41,-115 45,-110 45,-111 41))) AND CONTAINS(the_geom, POINT(-111 41))";
+    format = new OpenLayers.Format.CQL();
+    filter = format.read(test_cql);
+    t.ok(filter instanceof OpenLayers.Filter.Logical,
+         "Parsing ANDed filters produces a Filter.Logical");
+    t.eq(filter.type, OpenLayers.Filter.Logical.AND,
+         "AND parsed as Filter.Logical.AND");
+    t.eq(filter.filters.length, 2,
+         "AND Filter contains two subfilters");
+    t.ok(filter.filters[0] instanceof OpenLayers.Filter.Spatial,
+         "First sub-filter is a Filter.Spatial");
+    t.eq(filter.filters[0].type, OpenLayers.Filter.Spatial.INTERSECTS,
+         "First sub-filter is the first filter in the CQL text");
+    t.geom_eq(filter.filters[0].value, OpenLayers.Geometry.fromWKT("POLYGON((-111 41,-115 41,-115 45,-110 45,-111 41))"),
+         "First sub-filter is has correct geometry");
+    t.ok(filter.filters[1] instanceof OpenLayers.Filter.Spatial,
+         "Second sub-filter is a Filter.Comparison");
+    t.eq(filter.filters[1].type, OpenLayers.Filter.Spatial.CONTAINS,
+         "Second sub-filter is the second filter in the CQL text");
+    t.geom_eq(filter.filters[1].value, OpenLayers.Geometry.fromWKT("POINT(-111 41)"),
+         "Second sub-filter is has correct geometry");
+}
+
+function test_Logical_spatial_write(t) {
+    // TODO: remove this if extra parentheses are avoided by checking logical operator precedence
+    t.plan(1);
+    var cql = "(INTERSECTS(the_geom, POLYGON((-111 41,-115 41,-115 45,-110 45,-111 41)))) AND (CONTAINS(the_geom, POINT(-111 41)))";
+    var format = new OpenLayers.Format.CQL();
+    var filter = format.read(cql);
+    t.eq(format.write(filter), cql, "write returned test cql");
+}
+
+function test_Parentheticals(t) {
+    t.plan(2);
+    var format, cqlA, filterA, cqlB, filterB;
+    format = new OpenLayers.Format.CQL();
+    cqlA = "A = '1' AND B = '2' OR C = '3'";
+    cqlB = "A = '1' AND (B = '2' OR C = '3')";
+    filterA = format.read(cqlA);
+    filterB = format.read(cqlB);
+
+    t.ok(filterA instanceof OpenLayers.Filter.Logical &&
+         filterA.filters[0] instanceof OpenLayers.Filter.Logical &&
+         filterA.filters[1] instanceof OpenLayers.Filter.Comparison,
+         "Unparenthesized expression groups left to right");
+    t.ok(filterB instanceof OpenLayers.Filter.Logical &&
+         filterB.filters[0] instanceof OpenLayers.Filter.Comparison &&
+         filterB.filters[1] instanceof OpenLayers.Filter.Logical,
+         "Parenthesized expression groups as specified by parentheses");
+}
+
+function test_Parentheticals_write(t) {
+    // TODO: remove this if extra parentheses are avoided by checking logical operator precedence
+    t.plan(1);
+    var format = new OpenLayers.Format.CQL();
+    var cql = "(A = '1') AND ((B = '2') OR (C = '3'))";
+    var filter = format.read(cql);
+    t.eq(format.write(filter), cql, "write returned test cql");
+}
+
+function test_BBOX(t) {
+    t.plan(5);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "BBOX(the_geom,1,2,3,4)",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Spatial,
+         "Parsing BBOX expression produces Filter.Spatial");
+    t.eq(filter.type, OpenLayers.Filter.Spatial.BBOX,
+         "Spatial filter is a bbox filter");
+    t.eq(filter.property, "the_geom",
+         "Property name is as specified in CQL");
+    t.eq(filter.value.toBBOX(), "1,2,3,4",
+         "Value is as specified in CQL");
+
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+function test_INTERSECTS(t) {
+    t.plan(5);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "INTERSECTS(the_geom, POINT(1 2))",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Spatial,
+         "Parsing BBOX expression produces Filter.Spatial");
+    t.eq(filter.type, OpenLayers.Filter.Spatial.INTERSECTS,
+         "Spatial filter is an intersects filter");
+    t.eq(filter.property, "the_geom",
+         "Property name is as specified in CQL");
+    t.ok(filter.value instanceof OpenLayers.Geometry,
+         "Value is a geometry");
+    
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+function test_WITHIN(t) {
+    t.plan(5);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "WITHIN(the_geom, POLYGON((1 2,3 4,5 6,3 8,1 6,1 2)))",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Spatial,
+         "Parsing BBOX expression produces Filter.Spatial");
+    t.eq(filter.type, OpenLayers.Filter.Spatial.WITHIN,
+         "Spatial filter is a within filter");
+    t.eq(filter.property, "the_geom",
+         "Property name is as specified in CQL");
+    t.ok(filter.value instanceof OpenLayers.Geometry,
+         "Value is a geometry");
+
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+function test_DWITHIN(t) {
+    t.plan(6);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "DWITHIN(the_geom, POINT(1 2), 6)",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Spatial,
+         "Parsing DWITHIN expression produces Filter.Spatial");
+    t.eq(filter.type, OpenLayers.Filter.Spatial.DWITHIN,
+         "Spatial filter is a DWITHIN filter");
+    t.eq(filter.property, "the_geom",
+         "Property name is as specified in CQL");
+    t.ok(filter.value instanceof OpenLayers.Geometry,
+         "Value is a geometry");
+    t.eq(filter.distance, 6,
+         "Distance is as specified in CQL");
+
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+function test_CONTAINS(t) {
+    t.plan(5);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "CONTAINS(the_geom, POINT(1 2))",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Spatial,
+         "Parsing BBOX expression produces Filter.Spatial");
+    t.eq(filter.type, OpenLayers.Filter.Spatial.CONTAINS,
+         "Spatial filter is a within filter");
+    t.eq(filter.property, "the_geom",
+         "Property name is as specified in CQL");
+    t.ok(filter.value instanceof OpenLayers.Geometry,
+         "Value is a geometry");
+
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+function test_NOT(t) {
+    t.plan(4);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "NOT X < 12",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Logical,
+         "Parsing NOT expression produces Logical.Not");
+    t.eq(filter.type, OpenLayers.Filter.Logical.NOT,
+         "Logical filter is a NOT filter");
+    t.eq(filter.filters[0].property, "X",
+         "Property name is as specified in CQL");
+    t.eq(filter.filters[0].value, 12, "Value is as specified in CQL");
+}
+
+function test_NOT_write(t) {
+    // TODO: remove this if extra parentheses are avoided by checking logical operator precedence
+    t.plan(1);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "NOT (X < 12)",
+        filter = format.read(cql);
+    t.eq(format.write(filter), cql, "write returned test cql");
+}
+
+function test_BETWEEN(t) {
+    t.plan(6);
+    var format = new OpenLayers.Format.CQL(),
+        cql = "A BETWEEN 0 AND 5",
+        filter = format.read(cql);
+    t.ok(filter instanceof OpenLayers.Filter.Comparison,
+         "Parsing BETWEEN expression produces Filter.Comparison");
+    t.eq(filter.type, OpenLayers.Filter.Comparison.BETWEEN,
+         "Comparison filter is a between filter");
+    t.eq(filter.property, "A",
+         "Property name is as specified in CQL");
+    t.eq(filter.lowerBoundary, 0, 'Lower boundary is as specified in CQL');
+    t.eq(filter.upperBoundary, 5, 'Upper bondary is as specified in CQL');
+
+    t.eq(format.write(filter), cql, "write returned test cql");
+
+}
+
+        </script>
+    </head>
+    <body></body>
+</html>

Modified: trunk/openlayers/tests/list-tests.html
===================================================================
--- trunk/openlayers/tests/list-tests.html	2011-01-27 20:49:34 UTC (rev 11064)
+++ trunk/openlayers/tests/list-tests.html	2011-01-28 23:15:10 UTC (rev 11065)
@@ -53,6 +53,7 @@
     <li>Format/Atom.html</li>
     <li>Format/ArcXML.html</li>
     <li>Format/ArcXML/Features.html</li>
+    <li>Format/CQL.html</li>
     <li>Format/GeoJSON.html</li>
     <li>Format/GeoRSS.html</li>
     <li>Format/GML.html</li>



More information about the Commits mailing list