Debian Codegraph @

src/docbkx/client/javascript.xml

raw
1 <?xml version="1.0" encoding="utf-8"?>
2 <!--
3 ~ Copyright 2009-2013 Roland Huss
4 ~
5 ~ Licensed under the Apache License, Version 2.0 (the "License");
6 ~ you may not use this file except in compliance with the License.
7 ~ You may obtain a copy of the License at
8 ~
9 ~ http://www.apache.org/licenses/LICENSE-2.0
10 ~
11 ~ Unless required by applicable law or agreed to in writing, software
12 ~ distributed under the License is distributed on an "AS IS" BASIS,
13 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ~ See the License for the specific language governing permissions and
15 ~ limitations under the License.
16 -->
17
18 <section id="client-javascript">
19 <title>Javascript Client Library</title>
20 <para>
21 The Jolokia Javascript library provides a Javascript API to the
22 to the Jolokia agent. It comes with two layers, a
23 basic one which allows for sending Jolokia requests to the agent
24 synchronously or asynchronously and one with a simplified API
25 which is less powerful but easier to use. This library supports
26 bulk requests, HTTP GET and POST requests and JSONP for querying
27 agents which are located on a different server.
28 </para>
29 <para>
30 All methods of this library are available via the
31 <classname>Jolokia</classname> client object, which needs to be
32 instantiated up-front. In the following example a client object is
33 created and the used heap memory is requested synchronously via
34 the simple API. The agent is deployed within the same webarchive
35 which also serves this script.
36 </para>
37 <programlisting language="javascript"><![CDATA[
38 var j4p = new Jolokia("/jolokia");
39 var value = j4p.getAttribute("java.lang:type=Memory","HeapMemoryUsage","used");
40 console.log("Heap Memory used: " + value);
41 ]]></programlisting>
42 <section id="js-installation">
43 <title>Installation</title>
44 <para>
45 The Jolokia Javascript library is distributed in two parts, in
46 compressed and uncompressed forms:
47 </para>
48 <variablelist>
49 <varlistentry>
50 <term><filename>jolokia.js</filename> and
51 <filename>jolokia-min.js</filename></term>
52 <listitem>
53 <para>
54 Base library containing the Jolokia object definition
55 which carries the <methodname>request()</methodname>
56 </para>
57 </listitem>
58 </varlistentry>
59 <varlistentry>
60 <term><filename>jolokia-simple.js</filename> and <filename>jolokia-simple-min.js</filename></term>
61 <listitem>
62 <para>
63 Library containing the Jolokia simple API and which builds
64 up on <filename>jolokia.js</filename> It must be included
65 after <filename>jolokia.js</filename> since it adds methods
66 to the <classname>Jolokia</classname> object definition.
67 </para>
68 </listitem>
69 </varlistentry>
70 </variablelist>
71 <para>
72 All four files can be obtained from the <ulink
73 url="/download.html">download
74 page</ulink>. For production environments the compressed version
75 is highly recommended since the extensive API documentation
76 included in the original version is stripped off here. For Maven
77 users there is an even better way to integrate them, described in
78 <xref linkend="js-maven"/>.
79 </para>
80 <para>
81 <filename>jolokia.js</filename> uses <ulink
82 url="http://www.jquery.com">jQuery</ulink>, which must be
83 included as well. If the target platform doesn't support native
84 JSON serialization, <ulink
85 url="https://github.com/douglascrockford/JSON-js">json2.js</ulink>
86 needs to be included as well. As sample HTML head for including
87 all necessary parts looks like:
88 </para>
89 <programlisting language="html"><![CDATA[
90 <head>
91 <script src="jquery-1.7.2.js"></script>
92 <script src="json2.js"></script>
93 <script src="jolokia-min.js"></script>
94 <script src="jolokia-simple-min.js"></script>
95 </head>
96 ]]></programlisting>
97 <para>
98 A Jolokia client is always created as an instance of
99 <classname>Jolokia</classname>. Requests to the agent are sent
100 by calling methods on this object. The constructing function
101 takes a plain object, which provides default parameters which
102 are used in the <methodname>request()</methodname> if no
103 overriding are given there.
104 </para>
105 </section>
106
107 <section id="js-request">
108 <title>Usage</title>
109 <para>
110 All function of this library are available as methods of the
111 <classname>Jolokia</classname> object. The options needs to be
112 instantiated as usual and takes a set of default options, which
113 can be overwritten by subsequent requests. On the most basic
114 layer is a single <methodname>request()</methodname> method,
115 which takes two arguments: A request object and an optional
116 options object. For example, a synchronous request for obtaining
117 the agent's version for a agent running on the same server which
118 delivered the Javascript looks like:
119 </para>
120 <programlisting language="javascript"><![CDATA[
121 var j4p = new Jolokia({url: "/jolokia"});
122 var response = j4p.request({type: "version"},{method: "post"});
123 console.log("Agent Version: " + response.value.agent);]]></programlisting>
124 <para>
125 If the constructor is used with a single string argument, this
126 value is considered to be the agent's access URL. I.e. in the
127 example above the construction of the
128 <classname>Jolokia</classname> could have been performed with a
129 single string argument (<code>new Jolokia("/jolokia")</code>).
130 </para>
131 <section id="js-request-format">
132 <title>Requests</title>
133 <para>
134 Jolokia requests and responses are represented as JSON
135 objects. They have exactly the same format, which is expected
136 and returned by the agent as defined in <xref
137 linkend="protocol"/> for POST requests. All request types are
138 supported.
139 </para>
140 <para>
141 The <methodname>request()</methodname> expects as its first
142 argument either a single request object or, for bulk requests,
143 an array of request objects. Depending on this for synchronous
144 operations either a single response JSON object is returned or
145 an array of responses (in the order of the initial request
146 array). For asynchronous request one or more callbacks are
147 called for each response separately. See <xref
148 linkend="js-request-sync-async"/> for details.
149 </para>
150 <para>
151 The following example shows a single and bulk request call to
152 the Jolokia agent:
153 </para>
154 <programlisting language="javascript"><![CDATA[
155 var j4p = new Jolokia({url: "/jolokia"});
156 var req1 = { type: "read", mbean: "java.lang:type=Memory", attribute: "HeapMemoryUsage" };
157 var req2 = { type: "list" };
158 var response = j4p.request(req1);
159 var responses = j4p.request([ req1, req2 ]);]]></programlisting>
160 </section>
161 <section id="js-request-options">
162 <title>Request options</title>
163 <para>
164 Each request can be influenced by a set of optional options
165 provided either as default during construction of the
166 <classname>Jolokia</classname> object or as optional last
167 parameter for the request object. Also a request can carry a
168 <constant>config</constant> attribute, which can be used for all
169 processing parameters (<xref linkend="processing-parameters"/>).
170 The known options are summarized in <xref linkend="js-request-options-table"/>
171 </para>
172 <table id="js-request-options-table">
173 <title>Request options</title>
174 <thead>
175 <tr>
176 <td>Key</td>
177 <td>Description</td>
178 </tr>
179 </thead>
180 <tr>
181 <td><constant>url</constant></td>
182 <td>Agent URL (mandatory)</td>
183 </tr>
184 <tr>
185 <td><constant>method</constant></td>
186 <td>
187 Either "post" or "get" depending on the desired HTTP method
188 (case does not matter). Please note, that bulk requests are
189 not possible with "get". On the other hand, JSONP requests
190 are not possible with "post" (which obviously implies that
191 bulk request cannot be used with JSONP requests). Also, when
192 using a <constant>read</constant> type request for multiple
193 attributes, this also can only be sent as "post"
194 requests. If not given, a HTTP method is determined
195 dyamically. If a method is selected which doesn't fit to the
196 request, an error is raised.
197 </td>
198 </tr>
199 <tr>
200 <td><constant>jsonp</constant></td>
201 <td>
202 Whether the request should be sent via JSONP (a technique
203 for allowing cross domain request circumventing the infamous
204 "same-origin-policy"). This can be used only with HTTP "get"
205 requests.
206 </td>
207 </tr>
208 <tr>
209 <td><constant>success</constant></td>
210 <td>
211 Callback function which is called for a successful
212 request. The callback receives the response as single
213 argument. If no <constant>success</constant> callback is given, then
214 the request is performed synchronously and gives back the
215 response as return value. The value can be an array of
216 functions which is used for bulk requests to dispatch
217 multiple responses to multiple callbacks. See <xref
218 linkend="js-request-sync-async"/> for details.
219 </td>
220 </tr>
221 <tr>
222 <td><constant>error</constant></td>
223 <td>
224 Callback in case a Jolokia error occurs. A Jolokia error is
225 one, in which the HTTP request suceeded with a status code
226 of 200, but the response object contains a status other than
227 OK (200) which happens if the request JMX operation
228 fails. This callback receives the full Jolokia response
229 object (with a key <constant>error</constant> set). If no error
230 callback is given, but an asynchronous operation is
231 performed, the error response is printed to the Javascript
232 console by default.
233 </td>
234 </tr>
235 <tr>
236 <td><constant>ajaxError</constant></td>
237 <td>
238 Global error callback called when the Ajax request itself
239 failed. It obtains the same arguments as the error callback
240 given for <methodname>jQuery.ajax()</methodname>, i.e. the
241 <classname>XmlHttpResonse</classname>, a text status and an
242 error thrown. Refer to the jQuery documentation for more
243 information about this error handler.
244 </td>
245 </tr>
246 <tr>
247 <td><constant>username</constant></td>
248 <td>A username used for HTTP authentication</td>
249 </tr>
250 <tr>
251 <td><constant>password</constant></td>
252 <td>A password used for HTTP authentication</td>
253 </tr>
254 <tr>
255 <td><constant>timeout</constant></td>
256 <td>Timeout for the HTTP request</td>
257 </tr>
258 <tr>
259 <td><constant>maxDepth</constant></td>
260 <td>Maximum traversal depth for serialization of complex return values</td>
261 </tr>
262 <tr>
263 <td><constant>canonicalProperties</constant></td>
264 <td>Defaults to true for canonical (sorted) property lists on object names; if set to "false" then they are turned in their unsorted format.</td>
265 </tr>
266 <tr>
267 <td><constant>maxCollectionSize</constant></td>
268 <td>
269 Maximum size of collections returned during serialization.
270 If larger, the collection is returned truncated.
271 </td>
272 </tr>
273 <tr>
274 <td><constant>maxObjects</constant></td>
275 <td>
276 Maximum number of objects contained in the response.
277 </td>
278 </tr>
279 <tr>
280 <td><constant>ignoreErrors</constant></td>
281 <td>
282 If set to true, errors during JMX operations and JSON
283 serialization are ignored. Otherwise if a single
284 deserialization fails, the whole request returns with an
285 error. This works only for certain operations like pattern
286 reads.
287 </td>
288 </tr>
289 <tr>
290 <td><constant>serializeException</constant></td>
291 <td>
292 If true then in case of an error, the exception itself is returned in
293 it JSON representation under the key <constant>error_value</constant>
294 in the response object.
295 </td>
296 </tr>
297 <tr>
298 <td><constant>includeStackTrace</constant></td>
299 <td>
300 By default, a stacktrace is returned with every error (key: <constant>stacktrace</constant>)
301 This can be ommitted by setting the value of this option to false.
302 </td>
303 </tr>
304 <tr>
305 <td><constant>ifModifiedSince</constant></td>
306 <td>
307 The <constant>LIST</constant> operations provides an
308 optimization in that it remembers, when the set of
309 registered MBeans has been changes last. If a timestamp
310 (in epoch seconds) is provided with this parameter, then
311 the LIST operation returns an empty response
312 (i.e. <constant>value</constant> is null) and a
313 <constant>status</constant> code of 304 (Not Modified) if
314 the MBeans haven't changed. If you use the request
315 scheduler (<xref linkend="js-request-options-table"/>)
316 then this feature can be used to get the callbacks called
317 only if a value is returned. For the normal request, the
318 error callback is called which must check the status itself.
319 </td>
320 </tr>
321 </table>
322 </section>
323 <section id="js-request-sync-async">
324 <title>Operational modes</title>
325 </section>
326 <para>
327 Requests can be send either synchronously or asynchronously via
328 Ajax. If a <constant>success</constant> callback is given in the
329 request options, the request is performed asynchronously via an
330 Ajax HTTP request. The callback gets these arguments: a Jolokia JSON
331 response object (see <xref linkend="request-response"/>) and an
332 integer index indicating for which response this callback is being
333 called. For bulk requests, this index corresponds to the array
334 index of the request which lead to this response. The value of
335 this option can be an array of callback functions which are
336 called in a round robin fashion when multiple responses are
337 received in case of bulk requests. These callbacks are called
338 only when the returned Jolokia response has a status code of
339 <constant>200</constant>, otherwise the callback(s) given with
340 the <constant>error</constant> option are consulted. If no error
341 callback is given, the error is printed on the console by
342 default. As for success callbacks, error callbacks reveive the
343 Jolokia error response as a JSON object.
344 </para>
345 <para>
346 The following example shows asynchronous requests for a single
347 Jolokia request as well as for bulk request with multiple
348 callbacks.
349 </para>
350 <programlisting language="javascript"><![CDATA[
351 var j4p = new Jolokia("/jolokia");
352
353 // Single request with a single success callback
354 j4p.request(
355 { type: "read", mbean: "java.lang:type=Memory", attribute: "HeapMemoryUsage"},
356 { success: function(response) {
357 if (response.value.used / response.value.max > 0.9) {
358 alert("90% of heap memory exceeded");
359 }
360 },
361 error: function(response) {
362 alert("Jolokia request failed: " + response.error);
363 }
364 }
365 );
366
367 // Bulk request with multiple callbacks
368 j4p.request(
369 [
370 { type: "read", mbean: "java.lang:type=Threading", attribute: "ThreadCount"},
371 { type: "read", mbean: "java.lang:type=Runtime", attribute: ["VmName", "VmVendor"]}
372 ],
373 { success: [
374 function(response) {
375 console.log("Number of threads: " + response.value);
376 },
377 function(response) {
378 console.log("JVM: " + response.value.VmName + " -- "
379 + response.value.VmVendor);
380 }
381 ],
382 error: function(response) {
383 alert("Jolokia request failed: " + response.error);
384 }
385 }
386 );]]></programlisting>
387 <para>
388 Both callbacks, <constant>success</constant> and
389 <constant>error</constant>, are only called when the Ajax
390 request succeeds. In case of an error on the HTTP level, the
391 callback <constant>ajaxError</constant> is called with the
392 <classname>XMLHttpRequest</classname>, a
393 <constant>textStatus</constant> and an optional exception
394 object. It has the same signature as the underlying
395 <constant>error</constant> callback of the
396 <code>jQuery.ajax()</code> call. (See the <ulink
397 url="http://api.jquery.com/jQuery.ajax/">jQuery documentation</ulink>
398 for details).
399 </para>
400 <para>
401 The Jolokia agent also supports <ulink
402 url="http://en.wikipedia.org/wiki/JSONP">JSONP</ulink> requests
403 for cases where the Jolokia agent is served on a different server or port
404 than the Javascript client. By default, such access is forbidden by the so called
405 <emphasis>same-origin-policy</emphasis>. To swith on JSONP, the
406 option <constant>jsonp</constant> should be set to
407 <constant>"true"</constant>.
408 </para>
409 <para>
410 As explained in <xref linkend="request-response"/> the Jolokia
411 agent supports two HTTP methods, <constant>GET</constant> and
412 <constant>POST</constant>. <constant>POST</constant> is more
413 powerful since it supports more features. e.g. bulk requests and
414 JMX proxy requests are only possible with POST. By default, the
415 Jolokia Javascript library selects an HTTP method automatically,
416 which is <code>GET</code> for simple cases and <code>POST</code>
417 for more sophisticated requests. The HTTP method can be
418 overridden by setting the option <constant>method</constant> to
419 <constant>"get"</constant> or <constant>"post"</constant>.
420 </para>
421 <para>
422 There are some limitations in choosing the HTTP method depending
423 on the request and other options given:
424 </para>
425 <itemizedlist>
426 <listitem>
427 Bulk requests (i.e. an array of multiple requests) can only be
428 used with <constant>POST</constant>.
429 </listitem>
430 <listitem>
431 <constant>READ</constant> requests for multiple attributes
432 (i.e. the <constant>attribute</constant> request parameter is
433 an array of string values) can only be used with
434 <constant>POST</constant>.
435 </listitem>
436 <listitem>
437 The JMX proxy mode (see <xref linkend="proxy"/>) can only be used
438 with <constant>POST</constant>.
439 </listitem>
440 <listitem>
441 JSONP can only be used with <constant>GET</constant> and only
442 in asynchronous mode (i.e. a <constant>success</constant>
443 callback must be given). This is a limitation of the JSONP
444 technique itself.
445 </listitem>
446 </itemizedlist>
447 <para>
448 The restrictions above imply, that JSONP can only be used for
449 single, simple requests and not for JMX proxy calls.
450 </para>
451 </section>
452
453 <section id="js-simple">
454 <title>Simple API</title>
455 <para>
456 Building upon the basic
457 <methodname>Jolokia.request()</methodname> method, a simplified
458 access API is available. It is contained in
459 <filename>jolokia-simple.js</filename> which must be included after
460 <filename>jolokia.js</filename>. This API provides dedicated
461 method for the various request types and supports all options as
462 described in <xref linkend="js-request-options-table"/>. There
463 is one notable difference for asynchronous callbacks and
464 synchronous return values though: In case of a successful call,
465 the callback is fed with the response's
466 <constant>value</constant> object, not the full response
467 (i.e. <code>response.value</code>). Similar, for synchronous
468 operations the value itself is returned. In case of an error,
469 either an <constant>error</constant> callback is called with the
470 full response object or an <classname>Error</classname> is
471 thrown for synchronous operations.
472 </para>
473 <variablelist>
474 <varlistentry>
475 <term>getAttribute(mbean,attribute,path,opts)</term>
476 <listitem>
477 <para>
478 This method returns the value of an JMX attribute
479 <code>attribute</code> of an MBean <code>mbean</code>. A path
480 can be optionally given, and the optional request options are
481 given as last argument(s). The return value for synchronous
482 operations are the attribute's value, for asynchronous
483 operations (i.e. <code>opts.success != null</code>) it is
484 <constant>null</constant>. See <xref linkend="read"/> for
485 details.
486 </para>
487 <para>
488 For example, the following method call can be used
489 to synchronously fetch the current heap memory usage:
490 </para>
491 <programlisting language="javascript"><![CDATA[
492 var memoryUsed = j4p.getAttribute("java.lang:type=Memory","HeapMemoryUsage","used");
493 ]]></programlisting>
494 </listitem>
495 </varlistentry>
496 <varlistentry>
497 <term>setAttribute(mbean,attribute,value,path,opts)</term>
498 <listitem>
499 <para>
500 For setting an JMX attribute, this method takes the MBean's
501 name <code>mbean</code>, the attribute
502 <code>attribute</code> and the value to set as
503 <code>value</code>. The optional <code>path</code> is the
504 <emphasis>inner path</emphasis> of the attribute on which
505 to set the value (see <xref linkend="write"/> for
506 details). The old value of the attribute is returned or
507 given to a <constant>success</constant> callback.
508 </para>
509 <para>
510 To enable verbose mode in the memory-handling beans, use
511 </para>
512 <programlisting language="javascript"><![CDATA[
513 var gsLoggingWasOn = j4p.setAttribute("java.lang:type=Memory","Verbose",true);
514 ]]></programlisting>
515 </listitem>
516 </varlistentry>
517 <varlistentry>
518 <term>execute(mbean,operation,arg1,arg2,...,opts)</term>
519 <listitem>
520 <para>
521 With this method, a JMX operation can be executed on the
522 MBean <code>mbean</code>. Beside the operation's name
523 <code>operation</code>, one or more arguments can be given
524 depending on the signature of the JMX operation. The
525 return value is the return value of the operation. See
526 <xref linkend="exec"/> for details.
527 </para>
528 <para>
529 The following exampled asynchronously fetches a thread dump
530 as a JSON object and logs it into the console:
531 </para>
532 <programlisting language="javascript"><![CDATA[
533 j4p.execute("java.lang:type=Threading","dumpAllThreads",true,true,
534 {
535 success: function(value) {
536 console.log(JSON.stringify(value));
537 }
538 });
539 ]]></programlisting>
540 </listitem>
541 </varlistentry>
542 <varlistentry>
543 <term>search(mBeanPattern,opts)</term>
544 <listitem>
545 <para>
546 Searches for one or more MBeans whose object names fit the
547 pattern <code>mBeanPattern</code>. The return value is a list
548 of strings with the matching MBean names or <code>null</code>
549 if none is found. See <xref linkend="search"/> for details.
550 </para>
551 <para>
552 The following example looks up all application servers
553 available in all domains:
554 </para>
555 <programlisting language="javascript"><![CDATA[
556 var appServerNames = j4p.search("*:j2eeType=J2EEServer,*");
557 ]]></programlisting>
558 </listitem>
559 </varlistentry>
560 <varlistentry>
561 <term>list(path,opts)</term>
562 <listitem>
563 <para>
564 For getting meta information about registered MBeans,
565 the <methodname>list</methodname> command can be used. The
566 optional <code>path</code> points into this meta
567 information for retrieving partial information. The format
568 of the return value is described in detail in <xref
569 linkend="list"/>.
570 </para>
571 <para>
572 This example fetches only the meta information for the
573 attributes of the
574 <code>java.lang:type=OperatingSystem</code> MBean:
575 </para>
576 <programlisting language="javascript"><![CDATA[
577 var attributesMeta = j4p.list("java.lang/type=OperatingSystem/attr");
578 ]]></programlisting>
579 </listitem>
580 </varlistentry>
581 <varlistentry>
582 <term>version(opts)</term>
583 <listitem>
584 <para>
585 The <methodname>version</methodname> method returns the
586 agent's version, the protocol version, and possibly some
587 additional server-specific information. See
588 <xref linkend="version"/> for more information about this
589 method.
590 </para>
591 <para>
592 A sample return value for a Glassfish server looks like:
593 </para>
594 <programlisting language="javascript"><![CDATA[
595 {
596 protocol: "4.0",
597 agent: "0.82",
598 info: {
599 product: "glassfish",
600 vendor": "Sun",
601 extraInfo: {
602 amxBooted: false
603 }
604 }]]></programlisting>
605 </listitem>
606 </varlistentry>
607 </variablelist>
608 </section>
609
610 <section id="js-poller">
611 <title>Request scheduler</title>
612 <para>
613 A <classname>Jolokia</classname> object can be also used for
614 periodically sending requests to the agent. Therefore requests
615 can be registered to the client object, and a poller can be
616 started and stopped. All registered requests are send at once
617 with a single bulk request so this is a quite efficient method for
618 periodically polling multiple values.
619 </para>
620 <para>
621 Here is a simple example, which queries the heap memory usage
622 every 10 seconds and prints out the used memory on the console:
623 </para>
624 <programlisting language="javascript"><![CDATA[
625 var j4p = new Jolokia("/jolokia")
626 handle = j4p.register(function(resp) {
627 console.log("HeapMemory used: " + resp.value);
628 },
629 { type: "READ", mbean: "java.lang:type=Memory", attribute: "HeapMemoryUsage", path: "used"});
630
631 j4p.start(10000);
632 ]]></programlisting>
633 <variablelist>
634 <varlistentry>
635 <term>handle = j4p.register(callback,request,request,....)</term>
636 <listitem>
637 <para>
638 This method registers one or more request for being
639 periodically fetched. <code>callback</code> can be either a
640 function or an object.
641 </para>
642 <para>
643 If a function is given or an object with an attribute
644 <code>callback</code> holding a function, then this
645 function is called with all responses received as
646 argument, regardless whether the individual response
647 indicates a success or error state.
648 </para>
649 <para>
650 If the first argument is an object with two callback
651 attributes <code>success</code> and <code>error</code>,
652 these functions are called for <emphasis>each</emphasis> response
653 separately, depending whether the response indicates
654 success or an error state. If multiple requests have been
655 registered along with this callback object, the callback
656 is called multiple times, one for each request in the same
657 order as the request are given. As second argument, the
658 handle which is returned by this method is given and as
659 third argument the index within the list of requests.
660 </para>
661 <para>
662 If the first argument is an object, an additional
663 <constant>config</constant> attribute with processing
664 parameters can be given which is used as default for the
665 registered requests. Requests with a
666 <constant>config</constant> section take precedence.
667 </para>
668 <para>
669 Furthermore, if a <constant>onlyIfModified:
670 true</constant> exists in the callback object, then the
671 <constant>sucess</constant> and <constant>error</constant>
672 callbacks are called only if the result changed on the
673 server side. Currently, this is supported for the
674 <constant>list</constant> operation only in which case the
675 callback is only called when MBean has been registered or
676 deregistered since the last call of the scheduler. If a
677 single <constant>callback</constant> function is used
678 which gets all responses for a job at once, then this
679 function is called only with the responses, which carry a
680 value. If none of the registered requests produced a
681 response with value (i.e. the server decided that there
682 was no update for any request), then a call to the callback function is
683 skipped competely.
684 </para>
685 <para>
686 <code>register()</code> returns a handle which can be used
687 later for unregistering these requests.
688 </para>
689 <para>
690 In the following example two requests are registered along
691 with a single callback function, which takes two responses
692 as arguments:
693 </para>
694 <programlisting language="javascript"><![CDATA[
695 handle = j4p.register(function(resp1,resp2) {
696 console.log("HeapMemory used: " + resp1.value);
697 console.log("ThreadCount: " + resp2.value);
698 },
699 { type: "READ", mbean: "java.lang:type=Memory", attribute: "HeapMemoryUsage", path: "used"},
700 { type: "READ", mbean: "java.lang:type=Threading", attribute: "ThreadCount"});
701 ]]>
702 </programlisting>
703 <para>
704 In the next example, a dedicated <code>success</code>
705 and <code>error</code> callback are provided, which are
706 called individually for each request (in the given
707 order):
708 </para>
709 <programlisting language="javascript"><![CDATA[
710 j4p.register(
711 {
712 success: function(resp) {
713 console.log("MBean :" + resp.mbean + ", attr: " + resp.attribute + ", value: " + resp.value);
714 },
715 error: function(resp) {
716 console.log("Error: " + resp.error_text);
717 },
718 config: {
719 serializeException: true
720 },
721 onlyIfModified: true
722 },
723 { type: "LIST", config: { maxDepth: 2}},
724 { type: "READ", mbean: "java.lang:type=Threading",
725 attribute: "ThreadCount", config: { ignoreErrors: true }},
726 { type: "READ", mbean: "bla.blu:type=foo", attribute: "blubber"});
727 ]]>
728 </programlisting>
729 </listitem>
730 </varlistentry>
731 <varlistentry>
732 <term>j4p.unregister(handle)</term>
733 <listitem>
734 <para>
735 Unregister one or more requests registered with
736 <code>handle</code> so that they are no longer polled
737 with the scheduler.
738 </para>
739 </listitem>
740 </varlistentry>
741 <varlistentry>
742 <term>j4p.jobs()</term>
743 <listitem>
744 <para>
745 Return an array of handles for all registered jobs. This array can be freely manipulated, its a copy of
746 the handle list.
747 </para>
748 </listitem>
749 </varlistentry>
750 <varlistentry>
751 <term>j4p.start(period)</term>
752 <listitem>
753 <para>
754 Startup the scheduler for requeting the agent every
755 <code>period</code> milliseconds. If the scheduler is
756 already running, it adapts its scheduling period according
757 to the given argument. If no <code>period</code> is given,
758 the period provided during construction time (with the
759 option <code>fetchInterval</code>) is used. The default
760 value is 30 seconds.
761 </para>
762 </listitem>
763 </varlistentry>
764 <varlistentry>
765 <term>j4p.stop()</term>
766 <listitem>
767 <para>
768 Stop the scheduler. If the scheduler is not running,
769 nothing happens. The scheduler can be restarted after it
770 has been stopped.
771 </para>
772 </listitem>
773 </varlistentry>
774 <varlistentry>
775 <term>j4p.isRunning()</term>
776 <listitem>
777 <para>
778 Checks whether the scheduler is running. Returns
779 <code>true</code> if this is the case, <code>false</code>
780 otherwise.
781 </para>
782 </listitem>
783 </varlistentry>
784 </variablelist>
785 </section>
786
787 <section id="js-cubism">
788 <title>Jolokia as a Cubism Source</title>
789 <para>
790 <ulink url="http://square.github.com/cubism/">Cubism</ulink> is a Javascript library for
791 plotting time-series data and is based on <ulink
792 url="http://d3js.org/">d3.js</ulink>. Jolokia comes with a plugin for Cubism and
793 can act as a data source. The usage is quite simple: After
794 creating a Jolokia Cubism source, one or more JSON request can
795 be registered, which are queried periodically. No matter how
796 many requests are registered, only a single HTTP request is sent
797 to the server after each period. Cubism is then responsible for
798 plotting the data.
799 </para>
800 <para>
801 <xref linkend="fig-jolokia-cubism-example"/> shows a sample for a memory plot. More examples can
802 be found on this <ulink url="../../client/javascript-cubism.html">page</ulink>.
803 </para>
804 <figure id="fig-jolokia-cubism-example">
805 <title>Horizon Chart for Heap-Memory Usage</title>
806 <mediaobject>
807 <imageobject>
808 <imagedata fileref="jolokia-cubism-memory-horizon.png"/>
809 </imageobject>
810 </mediaobject>
811 </figure>
812 <para>
813 <filename>jolokia-cubism.js</filename> can be downloaded from
814 the <ulink url="/download.html">downlad page</ulink> and also
815 comes with a minified version. As dependencies it requires
816 <ulink url="/download.html">jolokia.js</ulink>, <ulink
817 url="http://www.jquery.com">JQuery</ulink>, <ulink
818 url="http://square.github.com/cubism/">Cubism</ulink> and <ulink
819 url="http://d3js.org/">d3.js</ulink>. <filename>jolokia-cubism.js</filename>
820 registers itself as an <ulink
821 url="http://requirejs.org/docs/whyamd.html">AMD</ulink> module
822 if running within an AMD environment.
823 </para>
824 <para>
825 In order to use Jolokia with Cubism, you first need to create a
826 Cubism <ulink url="https://github.com/square/cubism/wiki/Context">context</ulink>. Next use
827 <code>context.jolokia()</code> for creating a connection to the
828 Jolokia agent.
829 </para>
830 <programlisting language="javascript"><![CDATA[var context = cubism.context();
831
832 // Create a source for Jolokia metrics pointing to the agent
833 // at 'http://jolokia.org/jolokia'
834 var jolokia = context.jolokia("http://jolokia.org/jolokia");]]></programlisting>
835 <para>
836 The method <methodname>context.jolokia()</methodname> can take various
837 kind of arguments:
838 </para>
839 <itemizedlist>
840 <listitem>
841 <para>
842 A single string as in the example above is used as the
843 agent's URL. Additionally, options as key-value pairs can be
844 given as an additional argument. The possible keys are
845 described in <xref linkend="js-request-options-table"/>. If
846 the URL is omitted, but only an option object is provided,
847 then this object must also contain a key <code>url</code>
848 for specifying the agent URL.
849 </para>
850 </listitem>
851 <listitem>
852 <para>
853 Alternatively, an already instantiated Jolokia object can be
854 provided as single argument, which then is used for all
855 communications to the server.
856 </para>
857 </listitem>
858 </itemizedlist>
859 <para>
860 From this source object, a <ulink
861 url="https://github.com/square/cubism/wiki/Metric">metric</ulink>
862 object can be easily created. This metric object embrasses one
863 or more Jolokia requests which are send to the server
864 periodically. The response(s) are then used for calculating a
865 single numerical value which gets plotted. For example:
866 </para>
867 <programlisting language="javascript"><![CDATA[
868 // Read periodically the Heap-Memory use and take 'HeapMemory Usage' as name/label.
869 var metricMem = jolokia.metric({
870 type: 'read',
871 mbean: 'java.lang:type=Memory',
872 attribute: 'HeapMemoryUsage',
873 path: 'used'
874 },"HeapMemory Usage");
875
876 // Example for a callback function for evaluating responses
877 // dynamically. In this case, the first
878 // argument is a function, which gets feed with all response objects
879 // (one in this case). The requests objects are given next, and an
880 // options object as last argument.
881 var metricReq = jolokia.metric(
882 function (resp) {
883 var attrs = resp.value;
884 var sum = 0;
885 for (var key in attrs) {
886 sum += attrs[key].requestCount;
887 }
888 return sum;
889 },
890 {
891 type: "read",
892 mbean: "Catalina:j2eeType=Servlet,*",
893 attribute:"requestCount"
894 },
895 { name: "All", delta: 101000});]]></programlisting>
896 <para>
897 <methodname>metric()</methodname> is a factory method which can be
898 called in various ways.
899 </para>
900 <itemizedlist>
901 <listitem>
902 <para>
903 If the first argument is a Jolokia request object (i.e. not
904 a function), this request is used for sending requests
905 periodically.
906 </para>
907 </listitem>
908 <listitem>
909 <para>
910 If the first argument is a function, this function is used
911 for calculating the numeric value to be plotted. The rest of
912 the arguments can be one or more request objects, which are
913 registered and their responses are put as arguments to the
914 given callback function.
915 </para>
916 </listitem>
917 <listitem>
918 <para>
919 The last argument, if an object but not a Jolokia request
920 (i.e. there is no <code>type</code> key), is
921 taken as an option object which is described below.
922 </para>
923 </listitem>
924 <listitem>
925 <para>
926 Finally, if the last argument is a pure string, then this
927 string is used as name for the chart.
928 </para>
929 </listitem>
930 </itemizedlist>
931 <para>
932 An object which can be given as last argument is used for fine
933 tuning the metrics:
934 </para>
935 <variablelist>
936 <varlistentry>
937 <term><constant>name</constant></term>
938 <listitem>
939 <para>
940 Name used in charts. The name can also be given
941 alternatively as a string directly as last argument (but
942 then without any other options)
943 </para>
944 </listitem>
945 </varlistentry>
946 <varlistentry>
947 <term><constant>delta</constant></term>
948 <listitem>
949 <para>
950 Delta value in milliseconds for creating delta (velocity)
951 charts. This is done by taking the value measured
952 that many milliseconds ago and substract them from each other..
953 </para>
954 </listitem>
955 </varlistentry>
956 <varlistentry>
957 <term><constant>keepDelay</constant></term>
958 <listitem>
959 <para>
960 How many milliseconds before the oldest shown value should be
961 kept in memory, which e.g. is necessary for delta
962 charts. When <constant>delta</constant> is given, this
963 value is implicetly set.
964 </para>
965 </listitem>
966 </varlistentry>
967 </variablelist>
968 <para>
969 One or more metric objects can now be converted to charts and
970 added to a website with <filename>d3.js</filename>. This is done
971 in the usual cubism way as described here. In our example, in
972 order to append charts to a <constant>div</constant> with id
973 <constant>chart</constant> the following code can be used:
974 </para>
975 <programlisting language="xml"><![CDATA[// Use d3 to attach the metrics with a specific graph type
976 // ('horizon' in this case) to the document
977 d3.select("#charts").call(function(div) {
978 div.append("div")
979 .data([metricMem, metricReq])
980 .call(context.horizon())
981 });]]></programlisting>
982 <para>
983 For a complete API documentation please refer to the <ulink
984 url="https://github.com/square/cubism/wiki/API-Reference">Cubism API</ulink>.
985 </para>
986 </section>
987 <section id="js-maven">
988 <title>Maven integration</title>
989 <para>
990 For maven users' convenience, the Jolokia Javascript package is
991 also available as a JavaScript artifact. It can be easily
992 included with help of the
993 <constant>javascript-maven-plugin</constant>.
994 </para>
995 <sidebar>
996 <title>Recommended plugin</title>
997 Unfortunately, the "offical" version of this plugin hosted on
998 Codehaus has been stuck at version
999 <code>1.0-alpha-1-SNAPSHOT</code>. Although it is quite
1000 usable, in order to avoid a snapshot dependency, it is
1001 recommended to use a fork of this plugin hosted on <ulink
1002 url="https://github.com/harlanji/javascript-maven-tools">GitHub</ulink> and deployed at the
1003 <ulink url="https://oss.sonatype.org/content/groups/public">Sonatype Maven repository</ulink>.
1004 </sidebar>
1005 <para>
1006 The following example shows a sample configuration which could
1007 be used within a <filename>pom.xml</filename>:
1008 </para>
1009 <programlisting language="xml"><![CDATA[
1010 <project>
1011 ...
1012 <dependencies>
1013 <dependency>
1014 <groupId>org.jolokia</groupId>
1015 <artifactId>jolokia-client-javascript</artifactId>
1016 <type>javascript</type>
1017 <version>1.0.5</version>
1018 </dependency>
1019 ....
1020 </dependencies>
1021
1022 <build>
1023 <plugins>
1024 <plugin>
1025 <groupId>com.devspan.mojo.javascript</groupId>
1026 <artifactId>javascript-maven-plugin</artifactId>
1027 <version>0.9.3</version>
1028 <extensions>true</extensions>
1029 <configuration>
1030 <useArtifactId>false</useArtifactId>
1031 </configuration>
1032 <executions>
1033 <execution>
1034 <goals>
1035 <goal>war-package</goal>
1036 </goals>
1037 </execution>
1038 </executions>
1039 </plugin>
1040 ......
1041 </plugins>
1042 ....
1043 </build>
1044 ...
1045 <pluginRepositories>
1046 <pluginRepository>
1047 <id>sonatype-oss</id>
1048 <url>https://oss.sonatype.org/content/groups/public</url>
1049 </pluginRepository>
1050 </pluginRepositories>
1051 </project>
1052 ]]></programlisting>
1053 <para>
1054 Then, in your webapp project, <filename>jolokia.js</filename>,
1055 <filename>jolokia-simple.js</filename> and
1056 <filename>json2.js</filename> can be found in the
1057 <filename>scripts/lib</filename> directory (relative to the
1058 top level of you WAR). In order to include it in your HTML
1059 files use something like this:
1060 </para>
1061 <programlisting language="html"><![CDATA[
1062 <head>
1063 <script src="jquery-1.7.2.js"></script>
1064 <script src="scripts/libk/json2.js"></script>
1065 <script src="scripts/lib/jolokia.js"></script>
1066 <script src="scripts/lib/jolokia-simple.js"></script>
1067 </head>]]></programlisting>
1068 <para>
1069 <filename>jQuery.js</filename> has to be included on its own,
1070 though and is not included within the dependency. If the
1071 compressed version of <filename>jolokia.js</filename> should
1072 be used, add a
1073 <code><![CDATA[classifier="compressed"]]></code> to the
1074 <constant>jolokia-client-javascript</constant> dependency, and
1075 include <filename>scripts/lib/jolokia-min.js</filename>
1076 </para>
1077 <para>
1078 A full working example can be found in the Jolokia src at
1079 <filename>client/javascript/test-app/pom.xml</filename>.
1080 </para>
1081 </section>
1082
1083 </section>