Deep development of Ajax based on JMX Notification Framework __ Framework

Source: Internet
Author: User
Tags add time event listener wrapper
The article suggests that Ajax and JMX are located on the two opposite sides of the system management stack. However, Ajax models are now ubiquitous in Rich browser clients. This makes the model become blurred in the architecture domain to enhance the support pattern in the problem parsing pipeline.

This article describes in detail the advantages of an AJAX architecture-it can "broadcast" administrative status to a user base that can use the browser without waiting for the page to be updated.

This architecture is an extension of a common model-can be used to record JMX events and attributes into a server-side log file, and this change further records or "broadcasts" of management information to (AJAX-enabled) user bases.

In this article, we will specifically analyze the AJAX request/response model and the process of drawing management data to the page, as well as the beautiful JMX notification framework-all of which are clearly integrated together through an assembled servlet.

Next, we'll look at the content-security and capacity models that are typically not in standard AJAX discussions.

In this article, we use the BEA WebLogic 8.1 as the release platform for these software, although the architecture and methodology are also applicable to other Java EE application servers.

  I. Key needs

The system management stack for enterprise Java and EE applications forms part of the problem-resolution pipeline-where the JAVA/J2EE application interacts with a management to monitor potential problems, such as application server thread starvation, heap overflow, or stale connections to a database.

Management typically includes a JMX mbeans-which application to assemble and use, and other products such as wily Introscope and HP openview-that read these JMX properties can be warned from wily if they exceed a previously configured threshold.

There is a problem with this model-if the system is having problems in the background, the server-side mode for JMX management will not be able to help the browser-side customers because the model is all server-centric. For example, if a new Java EE Web application is to be published or the application is to be closed in minutes-because wily detects a problem, the user in the browser does not know that such an urgent management event has occurred.

By fully allowing users to enter the problem resolution pipeline, a system administrator can manage the end-user experience by broadcasting management information to the user base and, to some extent, controlling the user's behavior.

In order to deliver management information to customers through the HTTP protocol, there is a question of how management can send management information to an HTTP customer if the client user is not openly using GET or post update pages but secretly updating a hidden framework.

  Ii. Description of the programme

To implement a simple Ajax script, this article will obtain management information in the form of XML messages from the Mbean server and resolve the problem through a servlet. These management information must be managed and fed back to all participating application servers that can receive AJAX requests.

On the server side:

• A Java EE application server cluster is used to service requests from browser-based users and online transaction processing (OLTP) user bases, such as two or four servers. By using a Third-party Web server, user requests are balanced mounted across the cluster (OLTP cluster).

• A standard Mbean (Userweb) is used to store management information, such as administrative messages with metadata attributes. The Mbean is hosted on the Java EE "admin" server and on the Java server on the OLTP cluster.

• On the Management Server, the system administrator uses the Htmladaptor for JMX to set the warning state, the retry interval (the interval between adjacent xmlhttp-requests), and the warning message-for example, "System down in Minutes.". The administrator then broadcasts the status to the mbeans-on the Management server to reset their state to master management State by the Management Server.

On the client:

• AJAX-enabled clients retrieve states, retry intervals, and messages using a XMLHttpRequest (which calls a servlet to return related Mbean values in the form of an XML message).

• Then the client JavaScript analyzes the XML message, resets the retry interval, and uses the admin message to redraw part of the screen.

• After retry-interval seconds, the customer makes another xmlhttprequest and the customer cycle begins again. III. Basic Structure

Figure 1 shows a comprehensive solution architecture, where table 1 describes the corresponding basic architectural elements.


Figure 1 Scenario Architecture

Elements Describe
Standard Mbean (Userweb) Properties for warning states and messages, and Getter/setters and a method to broadcast (notify) Mbean status
Mbean Assistant (Userwebmbeanhelper) Packaging the assembled code to facilitate the use of the Userweb MBean
Mbean Server Mbean server in Java-EE container
Servlet (Admin.java) Assembled servlet, formatted XML response based on Userwebmbean content
Event Listener
(Managementlistener.java)
singleton-it registers itself as a listener for a "alert.broadcast" type of event with the Userweb Mbean on the Management Server
Client Ajax engine (admin.js) JavaScript for managing the Xmlhttprequest-/-repaint cycle
Client Description (main.jsp) The assembled JSP. Ajax launches the page based on the Mbean property
HTML adapter wrapper (Starthtmladaptor.java) Start a htmladaptorserver on listening port +100 to enable HTTP access to Mbeans
Table 1 Schema elements

(i) JMX notification model

This model contains two components:

· mbean-Activate events for local and remotely registered listeners

• Listener-it registers itself with an mbean to hear events generated by the Mbean

The first one is implemented by the Userweb Mbean, and the second is implemented by Managementlistener.

(ii) JMX MBean for managing user information

The Userweb standard Mbean is a simple class-it contains key properties and methods (table 2).

Elements Describe
Alertenabled If alertstatus>-1, True
Alertmessage Information that the user will see on the screen
Alertready If alertstatus>0, True
CallBack The number of milliseconds between each two XMLHttpRequest
Broadcaststate Method-it notifies all registered listeners on the local/remote JVM with an event (Alert.broadcast) (it passes the Mbean status as event data)

Table 2 Userweb Mbeam Properties and methods

(iii) Event listeners

Singleton The Managementlistener class implements weblogic.management.remotenotificationlistener-it expands Javax.management.NotificationListener and JAVA.RMI.R Emote to allow events on a remote WebLogic JVM to be notified to the remote listener by using RMI technology.
At Application server startup, a listener on each JVM registers itself with the Userweb Mbean on the Management server.

(iv) Mbean assistants

It's a good idea to use an assistant class to package Mbeans. In this way, we can invoke this assistant from the assembled code to invoke the Mbean method.
The Userwebmbeanhelper class is used as a wrapper for the Userweb Mbean. The ancestors of all assistants were applicationmbeanhelper, and it was responsible for:

• Find local and remote Mbean servers

• Call these servers to get/set Mbean properties and invoke the Mbean method

To ensure a match, both Mbean and Mbean assistants implement Interface Userwebmbean.

(v) assembling a servlet

An application can be assembled to use JMX. In AOP terms, the management aspect is woven into the application code. The first JMX assembly point in this article is a httpservlet. This servlet is the target of the AJAX request, and it implements a controller pattern-it can be crafted to handle other AJAX requests with simple request parameters.
From an MVC perspective, the model is a userweb Mbean, and the view is an AJAX-enabled (JSP) page, and the controller is an assembled servlet.

(vi) Client AJAX engine

This is a set of JavaScript functions that:

• Manage XMLHttpRequest and respond to repetitive actions

• Analysis of XML messages returned by XMLHttpRequest

• Repaint the screen with XML message content

Customer description

This is the main.jsp page-it contains the client Ajax engine and the part that can be repaint.

(vii) Sequence

Essentially, the server-side sequence participates in managing the settings of administrative properties and broadcasts these properties to all interested (listening) JVMs. The client sequences, however, participate in retrieving these properties and redraw the HTML page with important management information at the specified interval of time.

(eight) JMX notification (server sequence)

· Userweb Mbeans and Mbean event listeners are created and registered with the appropriate startup class when the application server is started

• The administrator sets the "master" Userweb Mbean attribute (warning message and retry interval), and then broadcasts or notifies the host on the remote Management server of this state

• Remote listener processing notification-by copying master (notification) data to a local userweb Mbean implementation

(ix) XMLHttpRequest query (customer sequence)

• AJAX-enabled clients call a servlet at intervals to query for administrative status

• The servlet reads the local Userweb Mbean properties, inserts them into an XML message, and returns the XML message as an XML response to the browser client (later discusses the alternative message format)

• Then, the AJAX customer analyzes the XML document, extracts messages such as warning and retry intervals, repaint the screen, and then uses this retry interval to set the next XMLHttpRequest delay.

Each of these steps is described in detail below.

Iv. registered Mbeans and Mbean listeners

On each Java server instance, run two startup classes when the server starts:

· managementstartup-It registers the Userweb Mbean with the local mbean server. The startup class parameter includes the default setting for the warning state, as well as the Mbean name and Mbean class. For example:

Arguments= "Servername=admin,
Mbeanname=exampleapp:name=userweb,
Mbeanclass=com.grahamh.management.userweb.userweb "
Classname= "Com.grahamh.management.startup.ManagementStartup"
Failureisfatal= "true" Name= "Userweb" notes= ""
targets= "Admin,oltpcluster"/>

· mbeanregistrations-It registers a singleton pojo-managementlistener with the Userweb Mbean on the Management server.

A Javax.management.NotificationFilterSupport object is used to enumerate the types of notifications that Userweb Mbean will generate and the listener will receive:

Mbeanregistrations.java
Mbeanhelperfactory.getwebhelper (). Registerlistener ();
Userwebmbeanlistener.java
public void Registerlistener () throws userwebexception{
try {
Get the Listener and filter
Managementlistener listener = Mbeanhelperfactory.getlistener ();
Notificationfiltersupport filter = Listener.getsupportedevents ();
Get admin Mbean server;
Register the Listener and filter with the Userweb Mbean
Remotembeanserver RMBS = Getadminmbeanserver ();
Rmbs.addnotificationlistener ("Exampleapp:name=userweb", listener, filter, NULL);
}
catch (Exception e) {
throw new Userwebexception ("Unable to Registerlistener:" + e.getmessage (), E);
}
}

The Listener.getsupportedevents () method returns the following filter:

Notificationfiltersupport filter = new Notificationfiltersupport ();
Filter.enabletype ("Alert.broadcast");

When the Managementlistener is started on the server, a connection to the Mbean server is established on the (remote) Management Server, and the (local) Managementlistener is registered as a listener-listen to the Userweb The event generated on the Mbean, and there is a filter set to the "Alert.broadcast" event type.

Because the Managementlistener implements Weblogic.management.RemoteNotificationListener, so it can get JMX notifications generated on a local JVM or a remote JVM; In this article, the JM that is generated on the remote Management Server JVM X notice.

V. Broadcast Admin Mbean Properties

Managed and managed Userweb Mbeans can be set independently-this gives any Java server a localized AJAX response. However, a common operation, management and Support (OA&M) Support mode sets the properties of the admin Mbean, and then uses the notification model to broadcast these properties to the Mbeans on the remote application server for subsequent Ajax retrieval.

Because the Userweb Mbean is based on applicationmbean-it expands the javax.management.NotificationBroadcasterSupport, the infrastructure is suitable for the Userweb Mbean to inform all the listeners. Therefore, the administrator sets the associated Mbean properties (using Htmladaptor) and clicks Broadcaststate (see Figure 2).


Figure 2 An Mbean view seen using Htmladaptor

Thus, the Userweb.broadcaststate () method is executed-it notifies all listeners synchronously about the status of the admin Mbean:

public void Broadcaststate () throws Exception {
try {
Notification n = new Notification ("Alert.broadcast", "Exampleapp:name=userweb", 0);
N.setuserdata (This) (new Userweb);
This.sendnotification (n);
}
catch (Exception e) {
Throw e;
}
}

Because the data is serialized on the network, this is not a temporary object graph that must be serializable.

  Vi. use of listeners to receive notifications from Mbean props

The so-called event listener is Managementlistener Singleton. The JMX notification Framework on the Management Server Managementlistener the Handlenotification () method in the remote call-this method exists in each of the listeners on each OLTP cluster JVMs (which is registered at server startup):

public void Handlenotification (Notification Notification, Object handback) {
SYSTEM.OUT.PRINTLN ("Received alert:" + Notification.gettype ());
Get an event from a notification UserData
Object userData = Notification.getuserdata ();
if (userData instanceof Userweb) {
From the Destin8 Web
Userweb WEBVO = (userweb) userData;
Userwebmbeanhelper helper = Mbeanhelperfactory.getwebhelper ();
Fetching data from a value object and putting it in a local mbean using Mbeanhelper
Helper.setalertmessage (Webvo.getalertmessage ());
Helper.setalertstatus (Webvo.getalertstatus ());
Helper.setcallback (Webvo.getcallback ());
Helper.setrefreshalertstatus (Webvo.getrefreshalertstatus ());
}
}

The "master" Userweb data is placed in a local user Web Mbean-implemented by its Mbean assistant. As a result, each Management server is updated with the master userweb status. This is the functionality that the JMX element has.

VII. Ajax requests for management status

To enable the browser client to support Ajax, you need to have the following:

main.jsp-is an assembled JSP page that can check (JMX) Warning status and query the server for warnings. This. jsp file includes Admin.js

admin.js-This is a JavaScript utility that uses XMLHttpRequest to query management status to the server, parse XML responses, and redraw the "status" area of the screen

The JavaScript included in main.jsp is described as follows:

Instead of querying continuously, we do so only when we start the browser warning function. We use Userwebmbeanhelper to check this feature. If the feature is started, the JavaScript function initadmin () will be invoked when the page loads:

<%
if (Mbeanhelperfactory.getwebhelper (). isalertenabled ()) {
%>

<%
} else {
%>

<%
}
%>

The Repaint ' status ' screen area is defined as follows:

"Adminbanner" will be used to mark areas that can be repaint-when parsing an XML response and extracting the message.

This initadmin () method dispatches a JavaScript Method Trapalert ()-this method executes after callbacktimeout milliseconds:

function Setcallback () {
CallBack = settimeout (' Trapalert () ', callbacktimeout);
}
function Initadmin () {
Setcallback ();
}

Note that the Trapalert () method is used to implement the startup XMLHttpRequest:

function Trapalert () {
if (window. XMLHttpRequest) {
req = new XMLHttpRequest ();
else if (window. ActiveXObject) {
req = new ActiveXObject ("Microsoft.XMLHTTP");
}
Req.onreadystatechange = ProcessRequest;
Req.open ("Get", './admin?reqid=0 ', true);
Req.send (NULL);
}

Here, the HTTP get is used to read the data (only one small request parameter is used) and the target is the admin servlet. This request is asynchronous, and the ProcessRequest JavaScript function is invoked when the request state changes:

Req.onreadystatechange = ProcessRequest;

It seems reasonable to wait for a response before proceeding, however, if a network or server problem causes a transaction to fail, you risk making your script hang. In contrast, an asynchronous invocation corresponding to the onReadyStateChange event is more flexible.

When the request completes, the ProcessRequest event handler is invoked:

function ProcessRequest () {
if (req.readystate = = 4) {
if (Req.status = = 200) {
Parsemessages ();
}
....
Setcallback ()//Only when it is done
}
}

Listing 1 (see download source) shows all the status codes available. When the request completes and returns the HTTP status code (OK), the Parsemessages () method is called to extract the data from the XML message. Then, schedule the Trapalert () method again. If the XML response has a different retry interval, the value is set by the Parsemessages () function.

Analyze XML responses and draw screens

The Parsemessages () function first extracts the XML response

Response = Req.responsexml;

It then extracts elements about the warning state, warning text, and retry intervals:

ItemStatus = response.getelementsbytagname (' status ') [0].firstchild.nodevalue;
Itemtext = Response.getelementsbytagname (' TextBody ') [0].firstchild.nodevalue;
Callbacktimeout = parseint (Response.getelementsbytagname (' CallBack ') [0].firstchild.nodevalue);

The warning text is then repaint to the Adminbanner document element (see above):

document.getElementById ("Adminbanner"). Innerhtml= Itemtext;

The warning message is displayed on the screen shown in Figure 3.

Figure 3 The Repaint screen

  Nine, servlet format XML response

To enable the browser to display administrative warnings to users, you need to use XMLHttpRequest to request administrative status.

When the browser sends the request, the servlet uses the Mbean attendant to check the warning state and, if a warning is available, constructs an XML document as a response.

If there is no return status, the response status is set as follows:

Response.setstatus (httpservletresponse.sc_no_content);

Otherwise, the text/xml response type is set to:

Response.setcontenttype ("Text/xml");

Listing 2 shows the complete servlet method.

When the servlet is invoked and the XML content is returned, the console should print:

Received Alert:alert.broadcast

1

! [Cdata[system Down minutes]]>

10000

  10, capacity modeling and security

Because Ajax has an interesting way of opening up the architecture, there are two key aspects that need to be considered:

• Capacity Modelling

• Security

Of course, buffer and Response message types (XML or text) are also important.

11, Capacity modeling

Rich clients that support Ajax do not have to submit requests as frequently as before. However, as XMLHttpRequest asynchronously executes on the browser side, the number of HTTP requests sent to the server increases as appropriate for the retry interval.

• Retry interval (think time) = 20 seconds

• Number of users connected =5000

• Transaction per second (TPS) =5000/20=250

We expect an additional 250 requests per second (transaction) to be generated by the HTTP user base.

Of course, this relies on the tasks accomplished by these requests on the server to increase the potential for response time. In our example, each request must look up an Mbean attribute and format an XML response, but the response is small and the Mbean processing is in local memory. Because each Web server thread can handle approximately 200 get requests per second, and the user requests a balanced load across a Java-EE server running approximately 200 threads, the increased load is less important.

It should also be noted that when modeling an AJAX architecture, the increased load may be offset by reduced bandwidth.

  12. Safety

Suppose you only ask users in the WebUser group to be able to access the admin servlet, what would happen.

If the admin servlet is accessible only to authenticated users, then XMLHttpRequest will run as the user if the user is authenticated.

For example, once the user Joe is logged into the application and Joe is a member of a webuser group, XMLHttpRequest will be able to activate the admin servlet.

Adding the following code to the admin servlet will confirm the subject to be authenticated and return True and Joe respectively:

Request.isuserinrole ("WebUser");
Request.getremoteuser ();

  13, Buffer

Some users have found that IE buffers responses from AJAX requests; This may be due to browser/page settings, but a mandatory workaround is to add time stamps to the URL:

var urlstr = "./admin?reqid=0&ts=" + new Date (). Gettimestamp ();

  14. Use no XML.

Some Ajax designers readily discard XML and send responses in plain text:

Response.setcontenttype ("Text/plain");

This obviously depends on the degree of coupling between your client needs and the data that the customer needs. A simple text response is sufficient for a text warning; however, the advantage of the XML model in this article is that response data can be further elaborated to refine State and state-related data. This article shows you how to analyze a more complex response-the customer may have to encode to receive it.

  15. Conclusion

Ajax represents some new architectural opportunities, but they should not be obscured by rich client functionality. This article, while weighing the benefits provided by Ajax, also emphasizes its technical requirements for capacity and security-a requirement for the use of this new technology.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.