Debian Codegraph @

closure-library/closure/goog/datasource/jsxmlhttpdatasource.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview
17 * DataSource implementation that uses XMLHttpRequest as transport, with
18 * response as valid JSON.
19 *
20 * Response can have unexecutable starting/ending text to prevent inclusion
21 * using <script src="...">
22 *
23 */
24
25
26 goog.provide('goog.ds.JsXmlHttpDataSource');
27
28 goog.require('goog.Uri');
29 goog.require('goog.ds.DataManager');
30 goog.require('goog.ds.FastDataNode');
31 goog.require('goog.ds.LoadState');
32 goog.require('goog.ds.logger');
33 goog.require('goog.events');
34 goog.require('goog.log');
35 goog.require('goog.net.EventType');
36 goog.require('goog.net.XhrIo');
37
38
39
40 /**
41 * Similar to JsonDataSource, with using XMLHttpRequest for transport
42 * Currently requires the result be a valid JSON.
43 *
44 * @param {(string|goog.Uri)} uri URI for the request.
45 * @param {string} name Name of the datasource.
46 * @param {string=} opt_startText Text to expect/strip before JS response.
47 * @param {string=} opt_endText Text to expect/strip after JS response.
48 * @param {boolean=} opt_usePost If true, use POST. Defaults to false (GET).
49 *
50 * @extends {goog.ds.FastDataNode}
51 * @constructor
52 * @final
53 */
54 goog.ds.JsXmlHttpDataSource = function(
55 uri, name, opt_startText, opt_endText, opt_usePost) {
56 goog.ds.FastDataNode.call(this, {}, name, null);
57 if (uri) {
58 this.uri_ = new goog.Uri(uri);
59 this.xhr_ = new goog.net.XhrIo();
60 this.usePost_ = !!opt_usePost;
61
62 goog.events.listen(
63 this.xhr_, goog.net.EventType.COMPLETE, this.completed_, false, this);
64 } else {
65 this.uri_ = null;
66 }
67 this.startText_ = opt_startText;
68 this.endText_ = opt_endText;
69 };
70 goog.inherits(goog.ds.JsXmlHttpDataSource, goog.ds.FastDataNode);
71
72
73 /**
74 * Delimiter for start of JSON data in response.
75 * null = starts at first character of response
76 * @type {string|undefined}
77 * @private
78 */
79 goog.ds.JsXmlHttpDataSource.prototype.startText_;
80
81
82 /**
83 * Delimiter for end of JSON data in response.
84 * null = ends at last character of response
85 * @type {string|undefined}
86 * @private
87 */
88 goog.ds.JsXmlHttpDataSource.prototype.endText_;
89
90
91 /**
92 * Gets the state of the backing data for this node
93 * @return {goog.ds.LoadState} The state.
94 * @override
95 */
96 goog.ds.JsXmlHttpDataSource.prototype.getLoadState = function() {
97 return this.loadState_;
98 };
99
100
101 /**
102 * Sets the request data. This can be used if it is required to
103 * send a specific body rather than build the body from the query
104 * parameters. Only used in POST requests.
105 * @param {string} data The data to send in the request body.
106 */
107 goog.ds.JsXmlHttpDataSource.prototype.setQueryData = function(data) {
108 this.queryData_ = data;
109 };
110
111
112 /**
113 * Load or reload the backing data for this node.
114 * Fires the JsonDataSource
115 * @override
116 */
117 goog.ds.JsXmlHttpDataSource.prototype.load = function() {
118 goog.log.info(
119 goog.ds.logger, 'Sending JS request for DataSource ' +
120 this.getDataName() + ' to ' + this.uri_);
121
122 if (this.uri_) {
123 if (this.usePost_) {
124 var queryData;
125 if (!this.queryData_) {
126 queryData = this.uri_.getQueryData().toString();
127 } else {
128 queryData = this.queryData_;
129 }
130
131 var uriNoQuery = this.uri_.clone();
132 uriNoQuery.setQueryData(null);
133 this.xhr_.send(String(uriNoQuery), 'POST', queryData);
134 } else {
135 this.xhr_.send(String(this.uri_));
136 }
137 } else {
138 this.loadState_ = goog.ds.LoadState.NOT_LOADED;
139 }
140 };
141
142
143 /**
144 * Called on successful request.
145 * @private
146 */
147 goog.ds.JsXmlHttpDataSource.prototype.success_ = function() {
148 goog.ds.DataManager.getInstance().fireDataChange(this.getDataName());
149 };
150
151
152 /**
153 * Completed callback. Loads data if successful, otherwise sets
154 * state to FAILED
155 * @param {goog.events.Event} e Event object, Xhr is target.
156 * @private
157 */
158 goog.ds.JsXmlHttpDataSource.prototype.completed_ = function(e) {
159 if (this.xhr_.isSuccess()) {
160 goog.log.info(
161 goog.ds.logger, 'Got data for DataSource ' + this.getDataName());
162 var text = this.xhr_.getResponseText();
163
164 // Look for start and end token and trim text
165 if (this.startText_) {
166 var startpos = text.indexOf(this.startText_);
167 text = text.substring(startpos + this.startText_.length);
168 }
169 if (this.endText_) {
170 var endpos = text.lastIndexOf(this.endText_);
171 text = text.substring(0, endpos);
172 }
173
174 // Parse result.
175
176 try {
177 var jsonObj = /** @type {!Object} */ (JSON.parse(text));
178 this.extendWith(jsonObj);
179 this.loadState_ = goog.ds.LoadState.LOADED;
180 } catch (ex) {
181 // Invalid JSON.
182 this.loadState_ = goog.ds.LoadState.FAILED;
183 goog.log.error(goog.ds.logger, 'Failed to parse data: ' + ex.message);
184 }
185
186 // Call on a timer to avoid threading issues on IE.
187 goog.global.setTimeout(goog.bind(this.success_, this), 0);
188 } else {
189 goog.log.info(
190 goog.ds.logger,
191 'Data retrieve failed for DataSource ' + this.getDataName());
192 this.loadState_ = goog.ds.LoadState.FAILED;
193 }
194 };