Bienvenue sur PostGIS.fr

Bienvenue sur PostGIS.fr , le site de la communauté des utilisateurs francophones de PostGIS.

PostGIS ajoute le support d'objets géographique à la base de données PostgreSQL. En effet, PostGIS "spatialise" le serverur PostgreSQL, ce qui permet de l'utiliser comme une base de données SIG.

Maintenu à jour, en fonction de nos disponibilités et des diverses sorties des outils que nous testons, nous vous proposons l'ensemble de nos travaux publiés en langue française.

source: trunk/workshop-routing-foss4g/web/OpenLayers/lib/OpenLayers/Protocol/HTTP.js @ 76

Revision 76, 22.5 KB checked in by djay, 12 years ago (diff)

Ajout du répertoire web

  • Property svn:executable set to *
Line 
1/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for
2 * full list of contributors). Published under the Clear BSD license. 
3 * See http://svn.openlayers.org/trunk/openlayers/license.txt for the
4 * full text of the license. */
5
6/**
7 * @requires OpenLayers/Protocol.js
8 * @requires OpenLayers/Feature/Vector.js
9 * @requires OpenLayers/Filter/Spatial.js
10 * @requires OpenLayers/Filter/Comparison.js
11 * @requires OpenLayers/Filter/Logical.js
12 * @requires OpenLayers/Request/XMLHttpRequest.js
13 */
14
15/**
16 * Class: OpenLayers.Protocol.HTTP
17 * A basic HTTP protocol for vector layers.  Create a new instance with the
18 *     <OpenLayers.Protocol.HTTP> constructor.
19 *
20 * Inherits from:
21 *  - <OpenLayers.Protocol>
22 */
23OpenLayers.Protocol.HTTP = OpenLayers.Class(OpenLayers.Protocol, {
24
25    /**
26     * Property: url
27     * {String} Service URL, read-only, set through the options
28     *     passed to constructor.
29     */
30    url: null,
31
32    /**
33     * Property: headers
34     * {Object} HTTP request headers, read-only, set through the options
35     *     passed to the constructor,
36     *     Example: {'Content-Type': 'plain/text'}
37     */
38    headers: null,
39
40    /**
41     * Property: params
42     * {Object} Parameters of GET requests, read-only, set through the options
43     *     passed to the constructor,
44     *     Example: {'bbox': '5,5,5,5'}
45     */
46    params: null,
47   
48    /**
49     * Property: callback
50     * {Object} Function to be called when the <read>, <create>,
51     *     <update>, <delete> or <commit> operation completes, read-only,
52     *     set through the options passed to the constructor.
53     */
54    callback: null,
55
56    /**
57     * Property: scope
58     * {Object} Callback execution scope, read-only, set through the
59     *     options passed to the constructor.
60     */
61    scope: null,
62
63    /**
64     * Property: readWithPOST
65     * {Boolean} true if read operations are done with POST requests
66     *     instead of GET, defaults to false.
67     */
68    readWithPOST: false,
69
70    /**
71     * Property: wildcarded.
72     * {Boolean} If true percent signs are added around values
73     *     read from LIKE filters, for example if the protocol
74     *     read method is passed a LIKE filter whose property
75     *     is "foo" and whose value is "bar" the string
76     *     "foo__ilike=%bar%" will be sent in the query string;
77     *     defaults to false.
78     */
79    wildcarded: false,
80
81    /**
82     * Constructor: OpenLayers.Protocol.HTTP
83     * A class for giving layers generic HTTP protocol.
84     *
85     * Parameters:
86     * options - {Object} Optional object whose properties will be set on the
87     *     instance.
88     *
89     * Valid options include:
90     * url - {String}
91     * headers - {Object}
92     * params - {Object}
93     * format - {<OpenLayers.Format>}
94     * callback - {Function}
95     * scope - {Object}
96     */
97    initialize: function(options) {
98        options = options || {};
99        this.params = {};
100        this.headers = {};
101        OpenLayers.Protocol.prototype.initialize.apply(this, arguments);
102    },
103   
104    /**
105     * APIMethod: destroy
106     * Clean up the protocol.
107     */
108    destroy: function() {
109        this.params = null;
110        this.headers = null;
111        OpenLayers.Protocol.prototype.destroy.apply(this);
112    },
113   
114    /**
115     * APIMethod: read
116     * Construct a request for reading new features.
117     *
118     * Parameters:
119     * options - {Object} Optional object for configuring the request.
120     *     This object is modified and should not be reused.
121     *
122     * Valid options:
123     * url - {String} Url for the request.
124     * params - {Object} Parameters to get serialized as a query string.
125     * headers - {Object} Headers to be set on the request.
126     * filter - {<OpenLayers.Filter>} Filter to get serialized as a
127     *     query string.
128     * readWithPOST - {Boolean} If the request should be done with POST.
129     *
130     * Returns:
131     * {<OpenLayers.Protocol.Response>} A response object, whose "priv" property
132     *     references the HTTP request, this object is also passed to the
133     *     callback function when the request completes, its "features" property
134     *     is then populated with the the features received from the server.
135     */
136    read: function(options) {
137        OpenLayers.Protocol.prototype.read.apply(this, arguments);
138        options = OpenLayers.Util.applyDefaults(options, this.options);
139        options.params = OpenLayers.Util.applyDefaults(
140            options.params, this.options.params);
141        if(options.filter) {
142            options.params = this.filterToParams(
143                options.filter, options.params);
144        }
145        var readWithPOST = (options.readWithPOST !== undefined) ?
146                           options.readWithPOST : this.readWithPOST;
147        var resp = new OpenLayers.Protocol.Response({requestType: "read"});
148        if(readWithPOST) {
149            resp.priv = OpenLayers.Request.POST({
150                url: options.url,
151                callback: this.createCallback(this.handleRead, resp, options),
152                data: OpenLayers.Util.getParameterString(options.params),
153                headers: {
154                    "Content-Type": "application/x-www-form-urlencoded"
155                }
156            });
157        } else {
158            resp.priv = OpenLayers.Request.GET({
159                url: options.url,
160                callback: this.createCallback(this.handleRead, resp, options),
161                params: options.params,
162                headers: options.headers
163            });
164        }
165        return resp;
166    },
167
168    /**
169     * Method: handleRead
170     * Individual callbacks are created for read, create and update, should
171     *     a subclass need to override each one separately.
172     *
173     * Parameters:
174     * resp - {<OpenLayers.Protocol.Response>} The response object to pass to
175     *     the user callback.
176     * options - {Object} The user options passed to the read call.
177     */
178    handleRead: function(resp, options) {
179        this.handleResponse(resp, options);
180    },
181
182    /**
183     * Method: filterToParams
184     * Convert an <OpenLayers.Filter> object to parameters.
185     *
186     * Parameters:
187     * filter - {OpenLayers.Filter} filter to convert.
188     * params - {Object} The parameters object.
189     *
190     * Returns:
191     * {Object} The resulting parameters object.
192     */
193    filterToParams: function(filter, params) {
194        params = params || {};
195        var className = filter.CLASS_NAME;
196        var filterType = className.substring(className.lastIndexOf(".") + 1);
197        switch(filterType) {
198            case "Spatial":
199                switch(filter.type) {
200                    case OpenLayers.Filter.Spatial.BBOX:
201                        params.bbox = filter.value.toArray();
202                        break;
203                    case OpenLayers.Filter.Spatial.DWITHIN:
204                        params.tolerance = filter.distance;
205                        // no break here
206                    case OpenLayers.Filter.Spatial.WITHIN:
207                        params.lon = filter.value.x;
208                        params.lat = filter.value.y;
209                        break;
210                    default:
211                        OpenLayers.Console.warn(
212                            "Unknown spatial filter type " + filter.type);
213                }
214                break;
215            case "Comparison":
216                var op = OpenLayers.Protocol.HTTP.COMP_TYPE_TO_OP_STR[filter.type];
217                if(op !== undefined) {
218                    var value = filter.value;
219                    if(filter.type == OpenLayers.Filter.Comparison.LIKE) {
220                        value = this.regex2value(value);
221                        if(this.wildcarded) {
222                            value = "%" + value + "%";
223                        }
224                    }
225                    params[filter.property + "__" + op] = value;
226                    params.queryable = params.queryable || [];
227                    params.queryable.push(filter.property);
228                } else {
229                    OpenLayers.Console.warn(
230                        "Unknown comparison filter type " + filter.type);
231                }
232                break;
233            case "Logical":
234                if(filter.type === OpenLayers.Filter.Logical.AND) {
235                    for(var i=0,len=filter.filters.length; i<len; i++) {
236                        params = this.filterToParams(filter.filters[i], params);
237                    }
238                } else {
239                    OpenLayers.Console.warn(
240                        "Unsupported logical filter type " + filter.type);
241                }
242                break;
243            default:
244                OpenLayers.Console.warn("Unknown filter type " + filterType);
245        }
246        return params;
247    },
248
249    /**
250     * Method: regex2value
251     * Convert the value from a regular expression string to a LIKE/ILIKE
252     * string known to the web service.
253     *
254     * Parameters:
255     * value - {String} The regex string.
256     *
257     * Returns:
258     * {String} The converted string.
259     */
260    regex2value: function(value) {
261
262        // highly sensitive!! Do not change this without running the
263        // Protocol/HTTP.html unit tests
264
265        // convert % to \%
266        value = value.replace(/%/g, "\\%");
267
268        // convert \\. to \\_ (\\.* occurences converted later)
269        value = value.replace(/\\\\\.(\*)?/g, function($0, $1) {
270            return $1 ? $0 : "\\\\_";
271        });
272
273        // convert \\.* to \\%
274        value = value.replace(/\\\\\.\*/g, "\\\\%");
275
276        // convert . to _ (\. and .* occurences converted later)
277        value = value.replace(/(\\)?\.(\*)?/g, function($0, $1, $2) {
278            return $1 || $2 ? $0 : "_";
279        });
280
281        // convert .* to % (\.* occurnces converted later)
282        value = value.replace(/(\\)?\.\*/g, function($0, $1) {
283            return $1 ? $0 : "%";
284        });
285
286        // convert \. to .
287        value = value.replace(/\\\./g, ".");
288
289        // replace \* with * (watching out for \\*)
290        value = value.replace(/(\\)?\\\*/g, function($0, $1) {
291            return $1 ? $0 : "*";
292        });
293
294        return value;
295    },
296
297    /**
298     * APIMethod: create
299     * Construct a request for writing newly created features.
300     *
301     * Parameters:
302     * features - {Array({<OpenLayers.Feature.Vector>})} or
303     *     {<OpenLayers.Feature.Vector>}
304     * options - {Object} Optional object for configuring the request.
305     *     This object is modified and should not be reused.
306     *
307     * Returns:
308     * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
309     *     object, whose "priv" property references the HTTP request, this
310     *     object is also passed to the callback function when the request
311     *     completes, its "features" property is then populated with the
312     *     the features received from the server.
313     */
314    create: function(features, options) {
315        options = OpenLayers.Util.applyDefaults(options, this.options);
316
317        var resp = new OpenLayers.Protocol.Response({
318            reqFeatures: features,
319            requestType: "create"
320        });
321
322        resp.priv = OpenLayers.Request.POST({
323            url: options.url,
324            callback: this.createCallback(this.handleCreate, resp, options),
325            headers: options.headers,
326            data: this.format.write(features)
327        });
328
329        return resp;
330    },
331
332    /**
333     * Method: handleCreate
334     * Called the the request issued by <create> is complete.  May be overridden
335     *     by subclasses.
336     *
337     * Parameters:
338     * resp - {<OpenLayers.Protocol.Response>} The response object to pass to
339     *     any user callback.
340     * options - {Object} The user options passed to the create call.
341     */
342    handleCreate: function(resp, options) {
343        this.handleResponse(resp, options);
344    },
345
346    /**
347     * APIMethod: update
348     * Construct a request updating modified feature.
349     *
350     * Parameters:
351     * feature - {<OpenLayers.Feature.Vector>}
352     * options - {Object} Optional object for configuring the request.
353     *     This object is modified and should not be reused.
354     *
355     * Returns:
356     * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
357     *     object, whose "priv" property references the HTTP request, this
358     *     object is also passed to the callback function when the request
359     *     completes, its "features" property is then populated with the
360     *     the feature received from the server.
361     */
362    update: function(feature, options) {
363        options = options || {};
364        var url = options.url ||
365                  feature.url ||
366                  this.options.url + "/" + feature.fid;
367        options = OpenLayers.Util.applyDefaults(options, this.options);
368
369        var resp = new OpenLayers.Protocol.Response({
370            reqFeatures: feature,
371            requestType: "update"
372        });
373
374        resp.priv = OpenLayers.Request.PUT({
375            url: url,
376            callback: this.createCallback(this.handleUpdate, resp, options),
377            headers: options.headers,
378            data: this.format.write(feature)
379        });
380
381        return resp;
382    },
383
384    /**
385     * Method: handleUpdate
386     * Called the the request issued by <update> is complete.  May be overridden
387     *     by subclasses.
388     *
389     * Parameters:
390     * resp - {<OpenLayers.Protocol.Response>} The response object to pass to
391     *     any user callback.
392     * options - {Object} The user options passed to the update call.
393     */
394    handleUpdate: function(resp, options) {
395        this.handleResponse(resp, options);
396    },
397
398    /**
399     * APIMethod: delete
400     * Construct a request deleting a removed feature.
401     *
402     * Parameters:
403     * feature - {<OpenLayers.Feature.Vector>}
404     * options - {Object} Optional object for configuring the request.
405     *     This object is modified and should not be reused.
406     *
407     * Returns:
408     * {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
409     *     object, whose "priv" property references the HTTP request, this
410     *     object is also passed to the callback function when the request
411     *     completes.
412     */
413    "delete": function(feature, options) {
414        options = options || {};
415        var url = options.url ||
416                  feature.url ||
417                  this.options.url + "/" + feature.fid;
418        options = OpenLayers.Util.applyDefaults(options, this.options);
419
420        var resp = new OpenLayers.Protocol.Response({
421            reqFeatures: feature,
422            requestType: "delete"
423        });
424
425        resp.priv = OpenLayers.Request.DELETE({
426            url: url,
427            callback: this.createCallback(this.handleDelete, resp, options),
428            headers: options.headers
429        });
430
431        return resp;
432    },
433
434    /**
435     * Method: handleDelete
436     * Called the the request issued by <delete> is complete.  May be overridden
437     *     by subclasses.
438     *
439     * Parameters:
440     * resp - {<OpenLayers.Protocol.Response>} The response object to pass to
441     *     any user callback.
442     * options - {Object} The user options passed to the delete call.
443     */
444    handleDelete: function(resp, options) {
445        this.handleResponse(resp, options);
446    },
447
448    /**
449     * Method: handleResponse
450     * Called by CRUD specific handlers.
451     *
452     * Parameters:
453     * resp - {<OpenLayers.Protocol.Response>} The response object to pass to
454     *     any user callback.
455     * options - {Object} The user options passed to the create, read, update,
456     *     or delete call.
457     */
458    handleResponse: function(resp, options) {
459        var request = resp.priv;
460        if(options.callback) {
461            if(request.status >= 200 && request.status < 300) {
462                // success
463                if(resp.requestType != "delete") {
464                    resp.features = this.parseFeatures(request);
465                }
466                resp.code = OpenLayers.Protocol.Response.SUCCESS;
467            } else {
468                // failure
469                resp.code = OpenLayers.Protocol.Response.FAILURE;
470            }
471            options.callback.call(options.scope, resp);
472        }
473    },
474
475    /**
476     * Method: parseFeatures
477     * Read HTTP response body and return features.
478     *
479     * Parameters:
480     * request - {XMLHttpRequest} The request object
481     *
482     * Returns:
483     * {Array({<OpenLayers.Feature.Vector>})} or
484     *     {<OpenLayers.Feature.Vector>} Array of features or a single feature.
485     */
486    parseFeatures: function(request) {
487        var doc = request.responseXML;
488        if (!doc || !doc.documentElement) {
489            doc = request.responseText;
490        }
491        if (!doc || doc.length <= 0) {
492            return null;
493        }
494        return this.format.read(doc);
495    },
496
497    /**
498     * APIMethod: commit
499     * Iterate over each feature and take action based on the feature state.
500     *     Possible actions are create, update and delete.
501     *
502     * Parameters:
503     * features - {Array({<OpenLayers.Feature.Vector>})}
504     * options - {Object} Optional object for setting up intermediate commit
505     *     callbacks.
506     *
507     * Valid options:
508     * create - {Object} Optional object to be passed to the <create> method.
509     * update - {Object} Optional object to be passed to the <update> method.
510     * delete - {Object} Optional object to be passed to the <delete> method.
511     * callback - {Function} Optional function to be called when the commit
512     *     is complete.
513     * scope - {Object} Optional object to be set as the scope of the callback.
514     *
515     * Returns:
516     * {Array(<OpenLayers.Protocol.Response>)} An array of response objects,
517     *     one per request made to the server, each object's "priv" property
518     *     references the corresponding HTTP request.
519     */
520    commit: function(features, options) {
521        options = OpenLayers.Util.applyDefaults(options, this.options);
522        var resp = [], nResponses = 0;
523       
524        // Divide up features before issuing any requests.  This properly
525        // counts requests in the event that any responses come in before
526        // all requests have been issued.
527        var types = {};
528        types[OpenLayers.State.INSERT] = [];
529        types[OpenLayers.State.UPDATE] = [];
530        types[OpenLayers.State.DELETE] = [];
531        var feature, list, requestFeatures = [];
532        for(var i=0, len=features.length; i<len; ++i) {
533            feature = features[i];
534            list = types[feature.state];
535            if(list) {
536                list.push(feature);
537                requestFeatures.push(feature); 
538            }
539        }
540        // tally up number of requests
541        var nRequests = (types[OpenLayers.State.INSERT].length > 0 ? 1 : 0) +
542            types[OpenLayers.State.UPDATE].length +
543            types[OpenLayers.State.DELETE].length;
544       
545        // This response will be sent to the final callback after all the others
546        // have been fired.
547        var success = true;
548        var finalResponse = new OpenLayers.Protocol.Response({
549            reqFeatures: requestFeatures       
550        });
551       
552        function insertCallback(response) {
553            var len = response.features ? response.features.length : 0;
554            var fids = new Array(len);
555            for(var i=0; i<len; ++i) {
556                fids[i] = response.features[i].fid;
557            }   
558            finalResponse.insertIds = fids;
559            callback.apply(this, [response]);
560        }
561 
562        function callback(response) {
563            this.callUserCallback(response, options);
564            success = success && response.success();
565            nResponses++;
566            if (nResponses >= nRequests) {
567                if (options.callback) {
568                    finalResponse.code = success ? 
569                        OpenLayers.Protocol.Response.SUCCESS :
570                        OpenLayers.Protocol.Response.FAILURE;
571                    options.callback.apply(options.scope, [finalResponse]);
572                }   
573            }
574        }
575
576        // start issuing requests
577        var queue = types[OpenLayers.State.INSERT];
578        if(queue.length > 0) {
579            resp.push(this.create(
580                queue, OpenLayers.Util.applyDefaults(
581                    {callback: insertCallback, scope: this}, options.create
582                )
583            ));
584        }
585        queue = types[OpenLayers.State.UPDATE];
586        for(var i=queue.length-1; i>=0; --i) {
587            resp.push(this.update(
588                queue[i], OpenLayers.Util.applyDefaults(
589                    {callback: callback, scope: this}, options.update
590                ))
591            );
592        }
593        queue = types[OpenLayers.State.DELETE];
594        for(var i=queue.length-1; i>=0; --i) {
595            resp.push(this["delete"](
596                queue[i], OpenLayers.Util.applyDefaults(
597                    {callback: callback, scope: this}, options["delete"]
598                ))
599            );
600        }
601        return resp;
602    },
603
604    /**
605     * APIMethod: abort
606     * Abort an ongoing request, the response object passed to
607     * this method must come from this HTTP protocol (as a result
608     * of a create, read, update, delete or commit operation).
609     *
610     * Parameters:
611     * response - {<OpenLayers.Protocol.Response>}
612     */
613    abort: function(response) {
614        if (response) {
615            response.priv.abort();
616        }
617    },
618
619    /**
620     * Method: callUserCallback
621     * This method is used from within the commit method each time an
622     *     an HTTP response is received from the server, it is responsible
623     *     for calling the user-supplied callbacks.
624     *
625     * Parameters:
626     * resp - {<OpenLayers.Protocol.Response>}
627     * options - {Object} The map of options passed to the commit call.
628     */
629    callUserCallback: function(resp, options) {
630        var opt = options[resp.requestType];
631        if(opt && opt.callback) {
632            opt.callback.call(opt.scope, resp);
633        }
634    },
635
636    CLASS_NAME: "OpenLayers.Protocol.HTTP" 
637});
638
639/**
640 * Property: OpenLayers.Protocol.HTTP.COMP_TYPE_TO_OP_STR
641 * {Object} A private class-level property mapping the
642 *     OpenLayers.Filter.Comparison types to the operation
643 *     strings of the protocol.
644 */
645(function() {
646    var o = OpenLayers.Protocol.HTTP.COMP_TYPE_TO_OP_STR = {};
647    o[OpenLayers.Filter.Comparison.EQUAL_TO]                 = "eq";
648    o[OpenLayers.Filter.Comparison.NOT_EQUAL_TO]             = "ne";
649    o[OpenLayers.Filter.Comparison.LESS_THAN]                = "lt";
650    o[OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO]    = "lte";
651    o[OpenLayers.Filter.Comparison.GREATER_THAN]             = "gt";
652    o[OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO] = "gte";
653    o[OpenLayers.Filter.Comparison.LIKE]                     = "ilike";
654})();
655
Note: See TracBrowser for help on using the repository browser.