source: trunk/zoo-project/zoo-client/lib/js/wps-client/zoo.js @ 480

Last change on this file since 480 was 480, checked in by samsouk, 10 years ago

Libraries and templates for the Zoo WPS client Javascript implementation.

File size: 13.9 KB
Line 
1// Filename: zoo-process.js
2/**
3 * Author : Samuel Souk aloun
4 *
5 * Copyright (c) 2014 GeoLabs SARL
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25
26define([
27    'xml2json', 'queryString', 'wpsPayload', 'utils'
28], function(X2JS, qs, wpsPayload, utils) {
29
30    var ZooProcess = function(params) {
31       
32        /**
33         * Private
34         */       
35       
36        var _x2js = new X2JS({
37            arrayAccessFormPaths: [
38            'ProcessDescriptions.ProcessDescription.DataInputs.Input',
39            'ProcessDescriptions.ProcessDescription.DataInputs.Input.ComplexData.Supported.Format',
40            'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output',
41            'ProcessDescriptions.ProcessDescription.ProcessOutputs.Output.ComplexOutput.Supported.Format',
42            'Capabilities.ServiceIdentification.Keywords'
43            ],   
44        });
45
46       
47        /**
48         * Public
49         */
50         
51        this.url = params.url;
52       
53        this.statusLocation = {};
54        this.launched = {};
55        this.terminated = {};
56        this.percent = {};
57        this.delay = params.delay || 2000,
58       
59        //
60        this.describeProcess = function(params) {
61            var closure = this;
62
63            if (!params.hasOwnProperty('type')) {
64                params.type = 'GET';
65            }
66
67            var zoo_request_params = {
68                Identifier: params.identifier,
69                metapath: params.metapath ? params.metapath : '',
70                request: 'DescribeProcess',
71                service: 'WPS',
72                version: '1.0.0',
73            }
74
75            this.request(zoo_request_params, params.success, params.error, params.type);
76        };
77       
78        //
79        this.getCapabilities = function(params) {
80            var closure = this;
81
82            if (!params.hasOwnProperty('type')) {
83                params.type = 'GET';
84            }
85
86            // http://zoo-server/cgi-bin/zoo_loader.cgi?ServiceProvider=&metapath=&Service=WPS&Request=GetCapabilities&Version=1.0.0
87            var zoo_request_params = {
88                ServiceProvider: '',
89                metapath: params.metapath ? params.metapath : '',
90                request: 'GetCapabilities',
91                service: 'WPS',
92                version: '1.0.0',
93            }
94
95            this.request(zoo_request_params, params.success, params.error, params.type);
96        };
97       
98        //
99        this.execute = function(params) {
100            var closure = this;
101            console.log("======== Execute "+params.identifier);
102            console.log(params);
103
104            if (!params.hasOwnProperty('type')) {
105                params.type = 'GET';
106            }
107
108            var zoo_request_params = {
109                request: 'Execute',
110                service: 'WPS',
111                version: '1.0.0',
112                Identifier: params.identifier,
113                DataInputs: params.dataInputs ? params.dataInputs : '',
114                DataOutputs: params.dataOutputs ? params.dataOutputs : '',
115
116                //storeExecuteResponse: params.storeExecuteResponse ? 'true' : 'false',
117                //status: params.status ? 'true' : 'false',
118            }
119
120
121            if (params.hasOwnProperty('responseDocument')) {
122                zoo_request_params.ResponseDocument = params.responseDocument;
123            }
124            if (params.hasOwnProperty('storeExecuteResponse') &&  params.storeExecuteResponse) {
125                zoo_request_params.storeExecuteResponse = 'true';
126            }
127            if (params.hasOwnProperty('status') &&  params.status) {
128                zoo_request_params.status = 'true';
129            }
130            if (params.hasOwnProperty('lineage') &&  params.lineage) {
131                zoo_request_params.lineage = 'true';
132            }
133
134
135            this.request(zoo_request_params, params.success, params.error, params.type);
136        };
137
138       
139        //
140        this.request = function(params, onSuccess, onError, type) {
141            var closure = this;
142            console.log('======== REQUEST type='+type);
143            console.log(params);
144
145            var url = this.url;
146            var payload;
147            var headers;
148
149            if (type == 'GET') {
150                url += '?' + this.getQueryString(params);
151            } else if (type == 'POST') {
152                payload = wpsPayload.getPayload(params);
153                console.log("======== POST PAYLOAD ========");
154                console.log(payload);
155
156                headers = {
157                    "Content-Type": "text/xml"       
158                };
159            }
160           
161            console.log("ajax url: "+url);
162
163            $.ajax({
164                type: type,
165                url: url,
166                dataType: "xml",
167                data: payload,
168                headers: headers
169            })
170            .always(
171                function() {
172                    //console.log("ALWAYS");
173                }
174            )
175            .fail(
176                function(jqXHR, textStatus, errorThrown) {
177                    console.log("======== ERROR ========"); 
178                    onError(jqXHR);       
179                }
180            )
181            .done(
182                function(data, textStatus, jqXHR) {
183                    console.log("======== SUCCESS ========");
184                    //console.log(data);
185                    console.log(utils.xmlToString(data));
186
187                    // TODO: move this transformation
188                    data = _x2js.xml2json( data );
189
190                    console.log(data);
191                    //------
192
193                    var launched;
194
195                    if (params.storeExecuteResponse == 'true' && params.status == 'true') {
196                        launched = closure.parseStatusLocation(data);           
197                        console.log(launched);
198                        closure.statusLocation[launched.sid] = launched.statusLocation;
199
200                        if (launched.hasOwnProperty('sid') && !closure.launched.hasOwnProperty(launched.sid)) {                   
201                            closure.launched[launched.sid] = launched.params;
202                            //closure.emit('launched', launched);
203                        }           
204                    }
205                    onSuccess(data, launched);
206            });
207        };
208       
209        //
210        this.watch = function(sid, handlers) {
211            //onPercentCompleted, onProcessSucceeded, onError
212            var closure = this;
213
214            console.log("WATCH: "+sid);
215
216            function onSuccess(data) {
217                console.log("++++ getStatus SUCCESS "+sid);
218                console.log(data);
219
220                if (data.ExecuteResponse.Status.ProcessStarted) {
221                    console.log("#### ProcessStarted");
222
223                    var ret = {
224                        sid: sid,
225                        percentCompleted: data.ExecuteResponse.Status.ProcessStarted._percentCompleted,
226                        text: data.ExecuteResponse.Status.ProcessStarted.__text,
227                        creationTime: data.ExecuteResponse.Status.ProcessStarted._creationTime,
228                    };
229
230                    closure.percent[sid] = ret.percentCompleted;
231                    //closure.emit('percent', ret);
232
233                    if (handlers.onPercentCompleted instanceof Function) {
234                        handlers.onPercentCompleted(ret);
235                    }
236                }
237                else if (data.ExecuteResponse.Status.ProcessSucceeded) {
238                console.log("#### ProcessSucceeded");
239
240                    var text = data.ExecuteResponse.Status.ProcessSucceeded.__text;
241                    closure.terminated[sid] = true;
242
243                    ret = {
244                        sid: sid,
245                        text: text,
246                        result: data
247                    };
248
249                    //closure.emit('success', ret);
250                    if (handlers.onProcessSucceeded instanceof Function) {
251                        handlers.onProcessSucceeded(ret);
252                    }
253                }
254                else {
255                    console.log("#### UNHANDLED EXCEPTION");
256                    closure.terminated[sid] = true;
257                    ret = {
258                        sid: sid,
259                        code: 'BAD',
260                        text: 'UNHANDLED EXCEPTION'
261                    };
262
263                    //closure.emit('exception', ret);
264                    if (handlers.onError instanceof Function) {
265                        handlers.onError(ret);
266                    }
267                }   
268            }
269
270            function onError(data) {
271                console.log("++++ getStatus ERROR "+sid);
272                console.log(data);
273            }
274
275            function ping(sid) {
276                console.log("PING: "+sid);
277                closure.getStatus(sid, onSuccess, onError);
278                if (closure.terminated[sid]) {
279                    console.log("++++ getStatus TERMINATED "+sid);           
280                }
281                else if (!closure.percent.hasOwnProperty(sid) || closure.percent[sid]<100) {
282                    setTimeout( function() {
283                        ping(sid);
284                    }, closure.delay);           
285                } else {
286                    console.log(closure.percent);
287                }
288            }
289
290            ping(sid);
291        };
292       
293        //
294        this.getStatus = function(sid, onSuccess, onError) {
295            var closure = this;
296
297            console.log("GET STATUS: "+sid);
298
299            if (closure.terminated[sid]) {
300                console.log("DEBUG TERMINATED");
301                return;
302            }
303            if (!closure.launched[sid]) {
304                console.log("DEBUG LAUNCHED");
305                return;
306            }
307            console.log("PARSE URI: "+closure.statusLocation[sid]);
308            var parsed_url = utils.parseUri(closure.statusLocation[sid]);
309            console.log(parsed_url);
310            zoo_request_params = parsed_url.queryKey;
311
312            this.request(zoo_request_params, onSuccess, onError, 'GET');
313        };
314       
315        //
316        this.getQueryString = function(params) {
317
318            var ret = '';
319
320            // TODO: serialize attributes
321            serializeInputs = function(obj) {
322              console.log("SERIALIZE dataInputs");
323              console.log(obj);
324              if($.type(obj) === "string") {
325                return obj;
326              }
327              var str = [];
328              for(var p in obj){
329                if (obj.hasOwnProperty(p)) {
330                  //str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
331                  str.push(p + "=" + obj[p]);
332                }
333              }
334              return str.join(";");
335            }
336
337            var responseDocument = params.ResponseDocument;
338            var tmp_params = {};
339
340            var objectKeys = Object.keys || function (obj) {
341                var keys = [];
342                for (var key in obj) keys.push(key);
343                return keys;
344            };
345
346            var skip = {
347                'DataInputs': true,
348                'DataOuptputs': true,
349                'ResponseDocument': true,
350            }
351            var keys = objectKeys(params);
352            for (var i = 0; i < keys.length; i++) {
353                var key = keys[i];
354                if (skip.hasOwnProperty(key) && skip[key]) {
355                    continue;
356                }
357                if (params.hasOwnProperty(key)) {
358                    tmp_params[key] = params[key];
359                }
360            }
361
362            ret = qs.stringify(tmp_params);
363
364            //req_options.path = req_options.path.replace("&DataInputs=sid%3D", "&DataInputs=sid=")
365            if (params.hasOwnProperty('DataInputs')) {
366              //var dataInputs = params.DataInputs;
367              var dataInputs = serializeInputs(params.DataInputs);
368              console.log("dataInputs: "+dataInputs);
369              ret += '&DataInputs=' + dataInputs;
370            }
371            /*
372            if (params.hasOwnProperty('DataOutputs')) {
373              var dataOutputs = serializeOutputs(params.DataOutputs);
374              console.log("dataOutputs: "+dataOutputs);
375              ret += '&DataOutputs=' + dataOutputs;
376            }
377            */
378            //ResponseDocument=Result ou RawDataOutput=Result
379
380            if (params.ResponseDocument) {
381                ret += '&ResponseDocument=' + params.ResponseDocument;
382            }
383
384            return ret;
385        };
386       
387        this.parseStatusLocation = function(data) {
388            var closure = this;
389
390            if (statusLocation = data.ExecuteResponse._statusLocation) {
391                console.log("statusLocation: "+statusLocation);
392
393                var parsed_url = utils.parseUri(statusLocation);
394                console.log(parsed_url);
395                var parsed_params = parsed_url.queryKey;
396
397                return {sid: parsed_url.queryKey.DataInputs, params: parsed_params, statusLocation: statusLocation};
398            }
399        };       
400    };
401   
402
403    return ZooProcess;
404
405});
Note: See TracBrowser for help on using the repository browser.

Search

Context Navigation

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png