Java Client Library (Jolokia versions before 2.4.0)
The Java client library provides an easy access to the Jolokia agent from within Java. Since JSR-160 connectors themselves provide Java based remote access to MBeans one might wonder about the benefits of a Jolokia Java binding. There are several, though:
-
It provides a typeless access to remote MBeans. The big advantage is that for any non-OpenMBean access to custom typed objects is still possible without having the type information locally in the classpath.
-
Jolokia can be used in setups where JSR-160 connectors can not be used. I.e. in firewall secured environments it is much easier to get through to a Jolokia Agent than to a JSR-160 connector using RMI as the transport protocol.
-
Remoteness is explicit in this API instead of JSR-160 connector’s seeked transparent remoteness. RMI has some arguable conceptually advantages, but hiding all remote aspects proved to have quite some disadvantages when it comes to the programming model. Explicit awareness of a 'heavy-weight' remote call is better than false transparency in order to know the price tag.
The Java client library follows a strict request-response paradigm, much like the underlying HTTP. It uses generics heavily and can be centered around three classes:
-
org.jolokia.client.J4pClientis the client side class, which has various variants of anexecute()methods for sending requests. -
These methods take one or more
org.jolokia.client.request.J4pRequestobjects as arguments and -
return one or more
org.jolokia.client.request.J4pResponseobjects as a result.
But before we got into the details, the next section gives a first tutorial to get a feeling how the API can be used.
Tutorial
As seen in the following example, the usage is quite easy. First
a client object client is created pointing
to a Jolokia agent at http://localhost:8080/jolokia.
A read request for querying the heap memory usage from the
java.lang.management.MemoryMXBean is created and then send using
the execute() method to the agent. The
response returned is of type
org.jolokia.client.request.J4pReadResponse and holds the result
which finally is printed out to standard output.
import org.jolokia.client.J4pClient;
import org.jolokia.client.J4pClientBuilder;
import org.jolokia.client.request.*;
public class MemoryDemo {
public static void main(String[] args) {
J4pClient client = new J4pClientBuilder().url("http://localhost:7778/jolokia")
.user("jolokia")
.password("jolokia")
.build();
J4pReadRequest request = new J4pReadRequest("java.lang:type=Memory", "HeapMemoryUsage");
request.setPath("used");
J4pReadResponse response = client.execute(request);
System.out.println("Memory used: " + response.getValue());
}
}
In order to compile and run this example, jolokia-client-java-2.3.0.jar library is needed (see Download) as well as
some additional support libraries:
For Maven users, the following dependency is sufficient (it will include the other as transitive dependencies):
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-client-java</artifactId>
<version>2.3.0</version>
</dependency>
J4pClient
org.jolokia.client.J4pClient is the entry point for sending
requests to a remote Jolokia agent. It can be created in multiple
ways. For simple cases, public constructors are provided taking
the mandatory Jolokia agent URL and optionally a
org.apache.http.client.HttpClient
instance which is used for the HTTP business. The recommended style
is to use the org.jolokia.client.J4pClientBuilder, though. This way, all
parameters for the HTTP communication can easily be set:
J4pClient j4p = new J4pClientBuilder().url("http://localhost:8080/jolokia")
.user("roland")
.password("s!cr!t")
.authenticator(new BasicAuthenticator().preemptive())
.connectionTimeout(3000)
.build();
The builder supports the following parameters with the given defaults:
| Parameter | Description | Default |
|---|---|---|
|
The URL to the Jolokia agent. This is the only mandatory parameter. |
|
|
Username when authentication is used. If not set, no
authentication is used. If set, |
|
|
Password used for authentication. Only used when
|
|
|
Implementation of |
|
|
A JMX JSR-160 ServiceURL which should be used by the agent as the real target. This parameter should be set if the client is used for accessing the agent in Proxy Mode. |
|
|
The JSR-160 user to use when using the proxy mode. If not
given (and |
|
|
JSR-160 Password to use for the proxy mode. |
|
|
The timeout in milliseconds until a connection is established. A timeout value of zero is interpreted as an infinite timeout. |
|
|
Specifies, that the underlying HttpClient should use pooled
connection manager, which is thread safe and can service
connection requests from multiples threads
simultaneously. This is important if the
|
|
|
Specifies that single connection should be used which
maintains only one active connection at a time. Even though
|
|
|
Defines the number of total connections to be pooled. It
is only used when |
|
|
Defines the number of total connections per route. It
is only used when |
|
|
Defines the timeout for waiting to obtain a connection
from the pool. This parameter is only used when
|
|
|
Defines the socket timeout ( |
|
|
Defines the charset to be used per default for encoding content body. |
|
|
Activates |
|
|
Determines whether Nagle’s algorithm is to be used. The
Nagle’s algorithm tries to conserve bandwidth by minimizing
the number of segments that are sent. When applications wish
to decrease network latency and increase performance, they
can disable Nagle’s algorithm (that is enable
|
true |
|
Determines the size of the internal socket buffer in bytes used to buffer data while receiving and transmitting HTTP messages. |
|
|
Determines http proxy server. It can be defined as
|
|
|
Set the proxy for this client based on |
|
|
A response objectAccessor can be used for hooking into the JSON
deserialization process when a JSON response is converted
into a |
|
|
A map of default HTTP headers that should be sent with Jolokia requests. |
|
|
HttpClient4 cookie store to use |
|
|
|
|
The J4pClient provides various variants
of a execute() method, which take
either one single request or a list of requests. For a single
request, the preferred HTTP method (GET or POST) can be
specified optionally. The List<R>
argument type can be used only for a homogeneous bulk request,
i.e. for multiple requests of the same time. Otherwise an
untyped list must be used.
Each request can be tuned by giving a map of processing options
along with their values to the execute
method. The possible options are shown in table
Table 2, “J4pClient query parameters”.
| J4pQueryParameter enum | Description |
|---|---|
|
Maximum traversal depth for serialization of complex objects. Use this with a "list" request to restrict the depth of the returned meta data tree. |
|
Maximum size of collections returned during serialization. If larger, a collection is truncated to this size. |
|
Maximum number of objects returned in the response’s value. |
|
Option for ignoring errors during JMX operations and JSON
serialization. This works only for certain operations like
pattern reads and should be either |
|
Whether to include a stack trace in the response when an
error occurs. The allowed values are
|
|
Whether to include a JSON serialized version of the
exception. If set to |
|
Whether property keys of |
|
Can be specified as milliseconds of the UNIX epoch for |
|
Whether the response object should contain related request object. |
Request types
For each request type a dedicated request object is provided
which all are subclasses from
J4pRequest. For all requests it can be
specified which HTTP method is to be used by setting the
property preferredHttpMethod to either
GET or POST.
Each request type has a corresponding response type which used
for the return values of the
J4pClient.execute().
The constructor of each kind of request can take a
J4pTargetConfig as argument for using a
request in Proxy Mode. This
configurational object holds the JMX service url and
(optionally) credentials for JSR-160 authentication. When
given, this proxy target specification overrides any default
proxy configuration set during the initialization of the
J4pClient.
J4pReadRequestandJ4pReadResponse-
J4pReadRequestis a read request to get one or more attributes from one or more MBeans within a single request. Various constructor variants can be used to specify one or more attributes along with the ObjectName (which can be a pattern). Apathcan be set as property for specifying an inner path, too.J4pReadResponseis the corresponding response type and allows typed access to the fetched value for a single attribute fetch or to multiple values for a multi attribute read. In the latter case, the found object and attributes names can be retrieved as well.For more information on fetching the value of multiple attributes and multiple MBeans at once, please refer to Reading attributes (read) or the Javadoc of
J4pReadResponse. J4pWriteRequestandJ4pWriteResponse-
A
J4pWriteRequestis used to set the value of an MBean attribute. Beside the mandatory object and attribute name the value must be give in the constructor as well. Optionally apathcan be provided, too. Only certain types for the given value can be serialized properly for calling the Jolokia agent as described in Request parameter serialization.The old value is returned as
J4pWriteResponse's value. J4pExecRequestandJ4pExecResponse-
J4pExecRequest's are used for executing operation on MBeans. The constructor takes as mandatory arguments the MBean’s object name, the operation name and any arguments required by the operation. Only certain types for the given arguments can be serialized properly for calling the Jolokia agent as described in Request parameter serialization.The returned
J4pExecResponsecontains the return value of the operation called. J4pSearchRequestandJ4pSearchResponse-
A
J4pSearchRequestcontains a valid single MBean object name pattern which is used for searching MBeans.The
J4pSearchResponseholds a list of found object names. J4pListRequestandJ4pListResponse-
For obtaining meta data on MBeans a
J4pListRequestshould be used. It can be used with a inner path to obtain only a subtree of the response, otherwise the whole tree as described in List response is returned. With the query parametermaxDepthcan be used to restrict the depth of returned tree.The single value of a
J4pListResponseis a tree (or subtree) as a JSON object, which has the format described in List response. J4pVersionRequestandJ4pVersionResponse-
A
J4pVersionRequestrequest the Jolokia agent’s version information and takes no argument.The
J4pVersionResponsereturns the agent’s version (agentVersion), the protocol version (protocolVersion), the application server product name (product), the vendor name (vendor) and any extra info (extraInfo) specific to the platform the Jolokia is running on.
Exceptions
In case of an error when executing a request a
J4pException or one its subclass is
thrown.
J4pConnectException-
Exception thrown when the connection to the server fails. It contains the original
ConnectExceptionas nested value. J4pTimeoutException-
Exception thrown in case of an timeout. The nested exception is of type
ConnectTimeoutException. J4pRemoteException-
Generic exception thrown when an exception occurred on the remote side. This is the case when the JSON response obtained is an error response as described in Responses. The error type, error value, the status, the request leading to this error and the remote stacktrace as string) can be obtained from this exception.
J4pBulkRemoteException-
Exception thrown when a bulk request fails on the remote side. This contains a mixed list which contains the
J4pRemoteExceptionoccurred as well as theJ4pResponseobjects for the requests, which succeeded. The list obtained bygetResults()contains these objects in the same order as the list of requests given toexecute. All responses and remote exceptions can also be obtained separately in homogeneous lists. J4pException-
Base exception thrown, when no other exception fits, i.e. when the exception happened on the client side. The original exception is contained as nested exception.