Debian Codegraph @

src/site/resources/js/jolokia.js

raw
1 /*
2 * Copyright 2009-2012 Roland Huss
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 j * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 /* =================================
18 * Jolokia Javascript Client Library
19 * =================================
20 *
21 * Requires jquery.js and json2.js
22 * (if no native JSON.stringify() support is available)
23 */
24
25 (function() {
26
27 var _jolokiaConstructorFunc = function ($) {
28
29 // Default paramerters for GET and POST requests
30 var DEFAULT_CLIENT_PARAMS = {
31 type:"POST",
32 jsonp:false
33 };
34
35 var GET_AJAX_PARAMS = {
36 type:"GET"
37 };
38
39 var POST_AJAX_PARAMS = {
40 type:"POST",
41 processData:false,
42 dataType:"json",
43 contentType:"text/json"
44 };
45
46 // Processing parameters which are added to the
47 // URL as query parameters if given as options
48 var PROCESSING_PARAMS = ["maxDepth", "maxCollectionSize", "maxObjects", "ignoreErrors", "canonicalNaming",
49 "serializeException", "includeStackTrace", "ifModifiedSince"];
50
51 /**
52 * Constructor for creating a client to the Jolokia agent.
53 *
54 * An object containing the default parameters can be provided as argument. For the possible parameters
55 * see {@link #request()}.
56 *
57 * @param param either a string in which case it is used as the URL to the agent or
58 * an object with the default parameters as key-value pairs
59 */
60 function Jolokia(param) {
61 // If called without 'new', we are constructing an object
62 // nevertheless
63 if (!(this instanceof arguments.callee)) {
64 return new Jolokia(param);
65 }
66
67 // Jolokia Javascript Client version
68 this.CLIENT_VERSION = "1.2.2";
69
70 // Registered requests for fetching periodically
71 var jobs = [];
72
73 // Options used for every request
74 var agentOptions = {};
75
76 // State of the scheduler
77 var pollerIsRunning = false;
78
79 // Allow a single URL parameter as well
80 if (typeof param === "string") {
81 param = {url:param};
82 }
83 $.extend(agentOptions, DEFAULT_CLIENT_PARAMS, param);
84
85 // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
86 // Public methods
87
88 /**
89 * The request method using one or more JSON requests and sending it to the agent. Beside the
90 * request a bunch of options can be given, which are merged with the options provided
91 * at the constructor (where the options given here take precedence).
92 *
93 * Known options are:
94 *
95 * <dl>
96 * <dt>url</dt>
97 * <dd>Agent URL, which is mandatory</dd>
98 * <dt>method</dt>
99 * <dd>
100 * Either "post" or "get" depending on the desired HTTP method (case does not matter).
101 * Please note, that bulk requests are not possible with "get". On the other
102 * hand, JSONP requests are not possible with "post" (which obviously implies
103 * that bulk request cannot be used with JSONP requests). Also, when using a
104 * <code>read</code> type request for multiple attributes, this also can
105 * only be sent as "post" requests. If not given, a HTTP method is determined
106 * dyamically. If a method is selected which doesn't fit to the request, an error
107 * is raised.
108 * </dd>
109 * <dt>jsonp</dt>
110 * <dd>
111 * Whether the request should be sent via JSONP (a technique for allowing cross
112 * domain request circumventing the infamous "same-origin-policy"). This can be
113 * used only with HTTP "get" requests.
114 * </dd>
115 * <dt>success</dt>
116 * <dd>
117 * Callback function which is called for a successful request. The callback receives
118 * the response as single argument. If no <code>success</code> callback is given, then
119 * the request is performed synchronously and gives back the response as return
120 * value.
121 * </dd>
122 * <dt>error</dt>
123 * <dd>
124 * Callback in case a Jolokia error occurs. A Jolokia error is one, in which the HTTP request
125 * suceeded with a status code of 200, but the response object contains a status other
126 * than OK (200) which happens if the request JMX operation fails. This callback receives
127 * the full Jolokia response object (with a key <code>error</code> set). If no error callback
128 * is given, but an asynchronous operation is performed, the error response is printed
129 * to the Javascript console by default.
130 * </dd>
131 * <dt>ajaxError</dt>
132 * <dd>
133 * Global error callback called when the Ajax request itself failed. It obtains the same arguments
134 * as the error callback given for <code>jQuery.ajax()</code>, i.e. the <code>XmlHttpResonse</code>,
135 * a text status and an error thrown. Refer to the jQuery documentation for more information about
136 * this error handler.
137 * </dd>
138 * <dt>username</dt>
139 * <dd>A username used for HTTP authentication</dd>
140 * <dt>password</dt>
141 * <dd>A password used for HTTP authentication</dd>
142 * <dt>timeout</dt>
143 * <dd>Timeout for the HTTP request</dd>
144 * <dt>maxDepth</dt>
145 * <dd>Maximum traversal depth for serialization of complex return values</dd>
146 * <dt>maxCollectionSize</dt>
147 * <dd>
148 * Maximum size of collections returned during serialization.
149 * If larger, the collection is returned truncated.
150 * </dd>
151 * <dt>maxObjects</dt>
152 * <dd>
153 * Maximum number of objects contained in the response.
154 * </dd>
155 * <dt>ignoreErrors</dt>
156 * <dd>
157 * If set to true, errors during JMX operations and JSON serialization
158 * are ignored. Otherwise if a single deserialization fails, the whole request
159 * returns with an error. This works only for certain operations like pattern reads..
160 * </dd>
161 * </dl>
162 *
163 * @param request the request to send
164 * @param params parameters used for sending the request
165 * @return the response object if called synchronously or nothing if called for asynchronous operation.
166 */
167 this.request = function (request, params) {
168 var opts = $.extend({}, agentOptions, params);
169 assertNotNull(opts.url, "No URL given");
170
171 var ajaxParams = {};
172
173 // Copy over direct params for the jQuery ajax call
174 $.each(["username", "password", "timeout"], function (i, key) {
175 if (opts[key]) {
176 ajaxParams[key] = opts[key];
177 }
178 });
179
180 if (extractMethod(request, opts) === "post") {
181 $.extend(ajaxParams, POST_AJAX_PARAMS);
182 ajaxParams.data = JSON.stringify(request);
183 ajaxParams.url = ensureTrailingSlash(opts.url);
184 } else {
185 $.extend(ajaxParams, GET_AJAX_PARAMS);
186 ajaxParams.dataType = opts.jsonp ? "jsonp" : "json";
187 ajaxParams.url = opts.url + "/" + constructGetUrlPath(request);
188 }
189
190 // Add processing parameters as query parameters
191 ajaxParams.url = addProcessingParameters(ajaxParams.url, opts);
192
193 // Global error handler
194 if (opts.ajaxError) {
195 ajaxParams.error = opts.ajaxError;
196 }
197
198 // Dispatch Callbacks to error and success handlers
199 if (opts.success) {
200 var success_callback = constructCallbackDispatcher(opts.success);
201 var error_callback = constructCallbackDispatcher(opts.error);
202 ajaxParams.success = function (data) {
203 var responses = $.isArray(data) ? data : [ data ];
204 for (var idx = 0; idx < responses.length; idx++) {
205 var resp = responses[idx];
206 if (Jolokia.isError(resp)) {
207 error_callback(resp, idx);
208 } else {
209 success_callback(resp, idx);
210 }
211 }
212 };
213
214 // Perform the request
215 $.ajax(ajaxParams);
216 return null;
217 } else {
218 // Synchronous operation requested (i.e. no callbacks provided)
219 if (opts.jsonp) {
220 throw Error("JSONP is not supported for synchronous requests");
221 }
222 ajaxParams.async = false;
223 var xhr = $.ajax(ajaxParams);
224 if (httpSuccess(xhr)) {
225 return $.parseJSON(xhr.responseText);
226 } else {
227 return null;
228 }
229 }
230 };
231
232 // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
233 // Scheduler related methods
234
235 /**
236 * Register one or more requests for periodically polling the agent along with a callback to call on receipt
237 * of the response.
238 *
239 * The first argument can be either an object or a function. The remaining arguments are interpreted
240 * as Jolokia request objects
241 *
242 * If a function is given or an object with an attribute <code>callback</code> holding a function, then
243 * this function is called with all responses received as argument, regardless whether the individual response
244 * indicates a success or error state.
245 *
246 * If the first argument is an object with two callback attributes <code>success</code> and <code>error</code>,
247 * these functions are called for <em>each</em> response separately, depending whether the response
248 * indicates success or an error state. If multiple requests have been registered along with this callback object,
249 * the callback is called multiple times, one for each request in the same order as the request are given.
250 * As second argument, the handle which is returned by this method is given and as third argument the index
251 * within the list of requests.
252 *
253 * If the first argument is an object, an additional 'config' attribute with processing parameters can
254 * be given which is used as default for the registered requests.
255 * Request with a 'config' section take precedence.
256 *
257 * @param callback and options specification.
258 * @param request, request, .... One or more requests to be registered for this single callback
259 * @return handle which can be used for unregistering the request again or for correlation purposes in the callbacks
260 */
261 this.register = function() {
262 if (arguments.length < 2) {
263 throw "At a least one request must be provided";
264 }
265 var callback = arguments[0],
266 requests = Array.prototype.slice.call(arguments,1),
267 job;
268 if (typeof callback === 'object') {
269 if (callback.success && callback.error) {
270 job = {
271 success: callback.success,
272 error: callback.error
273 };
274 } else if (callback.callback) {
275 job = {
276 callback: callback.callback
277 };
278 } else {
279 throw "Either 'callback' or ('success' and 'error') callback must be provided " +
280 "when registering a Jolokia job";
281 }
282 job = $.extend(job,{
283 config: callback.config,
284 onlyIfModified: callback.onlyIfModified
285 });
286 } else if (typeof callback === 'function') {
287 // Simplest version without config possibility
288 job = {
289 success: null,
290 error: null,
291 callback: callback
292 };
293 } else {
294 throw "First argument must be either a callback func " +
295 "or an object with 'success' and 'error' attributes";
296 }
297 if (!requests) {
298 throw "No requests given";
299 }
300 job.requests = requests;
301 var idx = jobs.length;
302 jobs[idx] = job;
303 return idx;
304 };
305
306 /**
307 * Unregister a one or more request which has been registered with {@link #registerRequest}. As parameter
308 * the handle returned during the registration process must be given
309 * @param handle
310 */
311 this.unregister = function(handle) {
312 if (handle < jobs.length) {
313 jobs[handle] = undefined;
314 }
315 };
316
317 /**
318 * Return an array of handles for currently registered jobs.
319 * @return Array of job handles or an empty array
320 */
321 this.jobs = function() {
322 var ret = [],
323 len = jobs.length;
324 for (var i = 0; i < len; i++) {
325 if (jobs[i]) {
326 ret.push(i);
327 }
328 }
329 return ret;
330 };
331
332 /**
333 * Start the poller. The interval between two polling attempts can be optionally given or are taken from
334 * the parameter <code>fetchInterval</code> given at construction time. If no interval is given at all,
335 * 30 seconds is the default.
336 *
337 * If the poller is already running (i.e. {@link #isRunning()} is <code>true</code> then the scheduler
338 * is restarted, but only if the new interval differs from the currently active one.
339 *
340 * @param interval interval in milliseconds between two polling attempts
341 */
342 this.start = function(interval) {
343 interval = interval || agentOptions.fetchInterval || 30000;
344 if (pollerIsRunning) {
345 if (interval === agentOptions.fetchInterval) {
346 // Nothing to do
347 return;
348 }
349 // Re-start with new interval
350 this.stop();
351 }
352 agentOptions.fetchInterval = interval;
353 this.timerId = setInterval(callJolokia(this,jobs), interval);
354
355 pollerIsRunning = true;
356 };
357
358 /**
359 * Stop the poller. If the poller is not running, no operation is performed.
360 */
361 this.stop = function() {
362 if (!pollerIsRunning && this.timerId != undefined) {
363 return;
364 }
365 clearInterval(this.timerId);
366 this.timerId = null;
367
368 pollerIsRunning = false;
369 };
370
371 /**
372 * Check whether the poller is running.
373 * @return true if the poller is running, false otherwise.
374 */
375 this.isRunning = function() {
376 return pollerIsRunning;
377 };
378
379 // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
380 }
381
382
383 // ========================================================================
384 // Private Methods:
385
386 // Create a function called by a timer, which requests the registered requests
387 // calling the stored callback on receipt. jolokia and jobs are put into the closure
388 function callJolokia(jolokia,jobs) {
389 return function() {
390 var errorCbs = [],
391 successCbs = [],
392 i, j,
393 len = jobs.length;
394 var requests = [];
395 for (i = 0; i < len; i++) {
396 var job = jobs[i];
397 // Can happen when job has been deleted
398 // TODO: Can be probably optimized so that only the existing keys of jobs can be visited
399 if (!job) { continue; }
400 var reqsLen = job.requests.length;
401 if (job.success) {
402 // Success/error pair of callbacks. For multiple request,
403 // these callback will be called multiple times
404 var successCb = cbSuccessClosure(job,i);
405 var errorCb = cbErrorClosure(job,i);
406 for (j = 0; j < reqsLen; j++) {
407 requests.push(prepareRequest(job,j));
408 successCbs.push(successCb);
409 errorCbs.push(errorCb);
410 }
411 } else {
412 // Job should have a single callback (job.callback) which will be
413 // called once with all responses at once as an array
414 var callback = cbCallbackClosure(job,jolokia);
415 // Add callbacks which collect the responses
416 for (j = 0; j < reqsLen - 1; j++) {
417 requests.push(prepareRequest(job,j));
418 successCbs.push(callback.cb);
419 errorCbs.push(callback.cb);
420 }
421 // Add final callback which finally will call the job.callback with all
422 // collected responses.
423 requests.push(prepareRequest(job,reqsLen-1));
424 successCbs.push(callback.lcb);
425 errorCbs.push(callback.lcb);
426 }
427 }
428 var opts = {
429 // Dispatch to the build up callbacks, request by request
430 success: function(resp, j) {
431 return successCbs[j].apply(jolokia, [resp, j]);
432 },
433 error: function(resp, j) {
434 return errorCbs[j].apply(jolokia, [resp, j]);
435 }
436 };
437 return jolokia.request(requests, opts);
438 };
439 }
440
441 // Prepare a request with the proper configuration
442 function prepareRequest(job,idx) {
443 var request = job.requests[idx],
444 config = job.config || {},
445 // Add the proper ifModifiedSince parameter if already called at least once
446 extra = job.onlyIfModified && job.lastModified ? { ifModifiedSince: job.lastModified } : {};
447
448 request.config = $.extend({}, config, request.config, extra);
449 return request;
450 }
451
452 // Closure for a full callback which stores the responses in an (closed) array
453 // which the finally is feed in to the callback as array
454 function cbCallbackClosure(job,jolokia) {
455 var responses = [],
456 callback = job.callback,
457 lastModified = 0;
458
459 return {
460 cb : addResponse,
461 lcb : function(resp,j) {
462 addResponse(resp);
463 // Callback is called only if at least one non-cached response
464 // is obtained. Update job's timestamp internally
465 if (responses.length > 0) {
466 job.lastModified = lastModified;
467 callback.apply(jolokia,responses);
468 }
469 }
470 };
471
472 function addResponse(resp,j) {
473 // Only remember responses with values and remember lowest timetamp, too.
474 if (resp.status != 304) {
475 if (lastModified == 0 || resp.timestamp < lastModified ) {
476 lastModified = resp.timestamp;
477 }
478 responses.push(resp);
479 }
480 }
481 }
482
483 // Own function for creating a closure to avoid reference to mutable state in the loop
484 function cbErrorClosure(job, i) {
485 var callback = job.error;
486 return function(resp,j) {
487 // If we get a "304 - Not Modified" 'error', we do nothing
488 if (resp.status == 304) {
489 return;
490 }
491 if (callback) {
492 callback(resp,i,j)
493 }
494 }
495 }
496
497 function cbSuccessClosure(job, i) {
498 var callback = job.success;
499 return function(resp,j) {
500 if (callback) {
501 // Remember last success callback
502 if (job.onlyIfModified) {
503 job.lastModified = resp.timestamp;
504 }
505 callback(resp,i,j)
506 }
507 }
508 }
509
510 // Construct a callback dispatcher for appropriately dispatching
511 // to a single callback or within an array of callbacks
512 function constructCallbackDispatcher(callback) {
513 if (callback == null) {
514 return function (response) {
515 console.warn("Ignoring response " + JSON.stringify(response));
516 };
517 } else if (callback === "ignore") {
518 // Ignore the return value
519 return function () {
520 };
521 }
522 var callbackArray = $.isArray(callback) ? callback : [ callback ];
523 return function (response, idx) {
524 callbackArray[idx % callbackArray.length](response, idx);
525 }
526 }
527
528 // Extract the HTTP-Method to use and make some sanity checks if
529 // the method was provided as part of the options, but dont fit
530 // to the request given
531 function extractMethod(request, opts) {
532 var methodGiven = opts && opts.method ? opts.method.toLowerCase() : null,
533 method;
534 if (methodGiven) {
535 if (methodGiven === "get") {
536 if ($.isArray(request)) {
537 throw new Error("Cannot use GET with bulk requests");
538 }
539 if (request.type.toLowerCase() === "read" && $.isArray(request.attribute)) {
540 throw new Error("Cannot use GET for read with multiple attributes");
541 }
542 if (request.target) {
543 throw new Error("Cannot use GET request with proxy mode");
544 }
545 if (request.config) {
546 throw new Error("Cannot use GET with request specific config");
547 }
548 }
549 method = methodGiven;
550 } else {
551 // Determine method dynamically
552 method = $.isArray(request) ||
553 request.config ||
554 (request.type.toLowerCase() === "read" && $.isArray(request.attribute)) ||
555 request.target ?
556 "post" : "get";
557 }
558 if (opts.jsonp && method === "post") {
559 throw new Error("Can not use JSONP with POST requests");
560 }
561 return method;
562 }
563
564 // Add processing parameters given as request options
565 // to an URL as GET query parameters
566 function addProcessingParameters(url, opts) {
567 var sep = url.indexOf("?") > 0 ? "&" : "?";
568 $.each(PROCESSING_PARAMS, function (i, key) {
569 if (opts[key] != null) {
570 url += sep + key + "=" + opts[key];
571 sep = "&";
572 }
573 });
574 return url;
575 }
576
577 // ========================================================================
578 // GET-Request handling
579
580 // Create the URL used for a GET request
581 function constructGetUrlPath(request) {
582 var type = request.type;
583 assertNotNull(type, "No request type given for building a GET request");
584 type = type.toLowerCase();
585 var extractor = GET_URL_EXTRACTORS[type];
586 assertNotNull(extractor, "Unknown request type " + type);
587 var result = extractor(request);
588 var parts = result.parts || {};
589 var url = type;
590 $.each(parts, function (i, v) {
591 url += "/" + Jolokia.escape(v)
592 });
593 if (result.path) {
594 url += (result.path[0] == '/' ? "" : "/") + result.path;
595 }
596 return url;
597 }
598
599 // For POST requests it is recommended to have a trailing slash at the URL
600 // in order to avoid a redirect which then results in a GET request.
601 // See also https://bugs.eclipse.org/bugs/show_bug.cgi?id=331194#c1
602 // for an explanation
603 function ensureTrailingSlash(url) {
604 // Squeeze any URL to a single one, optionally adding one
605 return url.replace(/\/*$/, "/");
606 }
607
608 // Extractors used for preparing a GET request, i.e. for creating a stack
609 // of arguments which gets appended to create the proper access URL
610 // key: lowercase request type.
611 // The return value is an object with two properties: The 'parts' to glue together, where
612 // each part gets escaped and a 'path' which is appended literally
613 var GET_URL_EXTRACTORS = {
614 "read":function (request) {
615 return { parts:[ request.mbean, request.attribute ], path:request.path };
616 },
617 "write":function (request) {
618 return { parts:[request.mbean, request.attribute, valueToString(request.value)], path:request.path};
619 },
620 "exec":function (request) {
621 var ret = [ request.mbean, request.operation ];
622 if (request.arguments && request.arguments.length > 0) {
623 $.each(request.arguments, function (index, value) {
624 ret.push(valueToString(value));
625 });
626 }
627 return {parts:ret};
628 },
629 "version":function () {
630 return {};
631 },
632 "search":function (request) {
633 return { parts:[request.mbean]};
634 },
635 "list":function (request) {
636 return { path:request.path};
637 }
638 };
639
640 // Convert a value to a string for passing it to the Jolokia agent via
641 // a get request (write, exec). Value can be either a single object or an array
642 function valueToString(value) {
643 if (value == null) {
644 return "[null]";
645 }
646 if ($.isArray(value)) {
647 var ret = "";
648 for (var i = 0; i < value.length; i++) {
649 ret += value == null ? "[null]" : singleValueToString(value[i]);
650 if (i < value.length - 1) {
651 ret += ",";
652 }
653 }
654 return ret;
655 } else {
656 return singleValueToString(value);
657 }
658 }
659
660 // Single value conversion for write/exec GET requests
661 function singleValueToString(value) {
662 if (typeof value === "string" && value.length == 0) {
663 return "\"\"";
664 } else {
665 return value.toString();
666 }
667 }
668
669 // Check whether a synchronous request was a success or not
670 // Taken from jQuery 1.4
671 function httpSuccess(xhr) {
672 try {
673 return !xhr.status && location.protocol === "file:" ||
674 xhr.status >= 200 && xhr.status < 300 ||
675 xhr.status === 304 || xhr.status === 1223;
676 } catch (e) {
677 }
678 return false;
679 }
680
681 // ===============================================================================================
682 // Utility methods:
683
684 function assertNotNull(object, message) {
685 if (object == null) {
686 throw new Error(message);
687 }
688 }
689
690 // ================================================================================================
691
692 // Escape a path part, can be used as a static method outside this function too
693 Jolokia.prototype.escape = Jolokia.escape = function (part) {
694 return encodeURIComponent(part.replace(/!/g, "!!").replace(/\//g, "!/"));
695 };
696
697 /**
698 * Utility method which checks whether a response is an error or a success
699 * @param resp response to check
700 * @return true if response is an error, false otherwise
701 */
702 Jolokia.prototype.isError = Jolokia.isError = function(resp) {
703 return resp.status == null || resp.status != 200;
704 };
705
706 // Return back exported function/constructor
707 return Jolokia;
708 };
709
710 // =====================================================================================================
711 // Register either as global or as AMD module
712
713 (function (root, factory) {
714 if (typeof define === 'function' && define.amd) {
715 // AMD. Register as a named module
716 define(["jquery"], factory);
717 } else {
718 // Browser globals
719 root.Jolokia = factory(root.jQuery);
720 }
721 }(this, function (jQuery) {
722 return _jolokiaConstructorFunc(jQuery);
723 }));
724 }());
725