Tag: WebContainer

JBoss AS 7 Clustering on OpenShift

Hi,

High availability and fail-over are very important feature for any kind of infrastructure. As the name suggests the services should be available at any given point of time and requests should fail over if any component goes down abruptly. You can have several parallel instance of an application and can scale up and down depending on the business requirement, without worrying much about the cost. Load is distributed across different servers, and even if one or more of the servers fails, the application is still accessible via the other application instances. HA is crucial for scalable enterprise applications, as you can improve performance by adding more gears (which will be replica of your current one).

The latest Openshift Online has came up with “JEE Full Profile on JBoss” cartridge which allows you to get benefits of JBoss Clustering. It simply uses HAProxy as a load balancer upfront and creates multiple replicas of you application. The scaling can be based on your choice automatic or manual.

In this article we will see a demo of JBoss Clustering over Openshift. We will deploy a sample application on a two node JBoss Cluster and will try to replicate the user sessions in case of a jvm failure.

Step-1: Create a new application. Please note that we are using “-s” here to enable scaling:

$ rhc app create -a clusterwebapp -t jbossas-7 -s

Above will create a directory “clusterwebapp” at the location from where you ran the command from your terminal.

Download the application from : https://github.com/nikhilmone/ClusteredWebApp and put it inside the deployments directory. Once done simple git add, commit and push your application.

Step-2 : For this example we would be using manual scaling, so that we can quickly check if session replication works.

$ cd clusterwebapp/.openshift/markers/

Step-3 : Create a blank file as “disable_auto_scaling” :

$ touch disable_auto_scaling

Step-4 : Now add the changes to git repository, commit the changes and push them to Openshift server :

..

$ cd ../../

$ git add .openshift/markers/disable_auto_scaling

$ git commit -m "disabling auto-scaling"

$ git push

..

Step-3 : Once the auto-scaling is disabled, lets enable manual scaling :

Create an SSH connection to your application :

$ssh UUID@APPNAME-NAMESPACE.rhcloud.com

for eg :

ssh 123a456c09d12345b123a12345cc1234@clusterwebapp-mydomain.rhcloud.com

Step-4 : Run below command to enable manual scaling :

$ add-gear -a APPNAME -u UUID -n NAMESPACE

for eg :

..

add-gear -a clusterwebapp -u 123a456c09d12345b123a12345cc1234 -n mydomain

..

Now manual scaling is enabled. Let’s check if High Availability works. Try to access the application using the url :

Navigate to the management console now and select how many gears you want to scale your application, select two for now, so we will have a 2 node JBoss Clustering.

Let’s try to hit the application which is currently deployed on a 2 node JBoss Cluster.

http://clusterwebapp-mydomain.rhcloud.com/ClusterWebApp, this gives the welcome page.

You can see the session ID here. Now since we have established a session with the application, let’s bring down the JBoss node abruptly to check if this session fails over.

SSH to your application using :

ssh 123a456c09d12345b123a12345cc1234@clusterwebapp-mydomain.rhcloud.com

Grep for the java process and kill the process id, now our JBoss server is down. If clustering is working, the url should still work.

Hit http://clusterwebapp-mydomain.rhcloud.com/ClusterWebApp again, if this gives the same session ID that means our session has been failed over to the other JBoss node. To make sure this, do check the server logs πŸ™‚

Note that you can only run TCP clustering on OpenShift as of now. The best part is a developer need not to bother about clustering configuration OpenShift takes care of that. Quite a PaaS huh !! πŸ™‚

Regards,
Middlewaremagic Team πŸ™‚


Install and Run Tomcat on Openshift

Hi,

Nikhil Mone

Nikhil Mone

In this article we will discuss how to run Tomcat server on Openshift using Do It Yourself cartridges.

A lot of developers like to test their code by deploying it to web-containers, such as Tomcat, due to less complexities, less overhead and less files to tweak πŸ™‚

We can use our own customized Tomcat server to achieve a simple web-hosting over OpenShift.

Lets check how ??

Step-1 : We will create a simple application “mytomcatapp” using diy (do it yourself) cartridge, which allows us a lot of tweak options. Run below command from your project directory:

$ rhc app create -a mytomcatapp -t diy0.1 -l youropenshiftaccount@blah.com

Step-2 : Above creates a directory as “mytomcatapp”, navigate inside up to “action_hooks”:

$Project_DIR/.openshift/action_hooks

for eg : /home/userone/mytomcatapp/.openshift/action_hooks

Step-3 : By default diy cartridge has a ruby server installed, which can be stop/start using start and stop scripts, lets do a “ls -ltra” here :

..
[userone@userone action_hooks]$ ls -ltra
total 32
-rwxrwxr-x. 1 userone userone  178 Jul  2 15:03 stop
-rwxrwxr-x. 1 userone userone  295 Jul  2 15:03 start
-rwxrwxr-x. 1 userone userone  257 Jul  2 15:03 pre_build
-rwxrwxr-x. 1 userone userone  186 Jul  2 15:03 post_deploy
-rwxrwxr-x. 1 userone userone  249 Jul  2 15:03 deploy
-rwxrwxr-x. 1 userone userone  264 Jul  2 15:03 build
drwxrwxr-x. 2 userone userone 4096 Jul  2 15:03 .
drwxrwxr-x. 4 userone userone 4096 Jul  2 15:03 ..

Step-4 : Now lets remove stop and start scripts from here :

$ rm stop start

for eg:

..
[userone@userone action_hooks]$ rm stop start
[userone@userone action_hooks]$ ls -ltra
total 24
-rwxrwxr-x. 1 userone userone  257 Jul  2 15:03 pre_build
-rwxrwxr-x. 1 userone userone  186 Jul  2 15:03 post_deploy
-rwxrwxr-x. 1 userone userone  249 Jul  2 15:03 deploy
-rwxrwxr-x. 1 userone userone  264 Jul  2 15:03 build
drwxrwxr-x. 4 userone userone 4096 Jul  2 15:03 ..
drwxrwxr-x. 2 userone userone 4096 Jul  2 15:11 .
[userone@userone action_hooks]$ pwd
/home/userone/tomcat/.openshift/action_hooks

Step-5 : Now recreate stop and start files :

$ touch stop start

for eg :

..
[userone@userone action_hooks]$ touch stop start
[userone@userone action_hooks]$ ls -ltra
total 24
-rwxrwxr-x. 1 userone userone  257 Jul  2 15:03 pre_build
-rwxrwxr-x. 1 userone userone  186 Jul  2 15:03 post_deploy
-rwxrwxr-x. 1 userone userone  249 Jul  2 15:03 deploy
-rwxrwxr-x. 1 userone userone  264 Jul  2 15:03 build
drwxrwxr-x. 4 userone userone 4096 Jul  2 15:03 ..
-rw-rw-r--. 1 userone userone    0 Jul  2 15:12 stop
-rw-rw-r--. 1 userone userone    0 Jul  2 15:12 start
drwxrwxr-x. 2 userone userone 4096 Jul  2 15:12 .

but here we can see the permissions are different from previous ls output, so lets give 775 permission as the earlier scripts had:

..
[userone@userone action_hooks]$ chmod 775 stop start
[userone@userone action_hooks]$ ls -ltra
total 24
-rwxrwxr-x. 1 userone userone  257 Jul  2 15:03 pre_build
-rwxrwxr-x. 1 userone userone  186 Jul  2 15:03 post_deploy
-rwxrwxr-x. 1 userone userone  249 Jul  2 15:03 deploy
-rwxrwxr-x. 1 userone userone  264 Jul  2 15:03 build
drwxrwxr-x. 4 userone userone 4096 Jul  2 15:03 ..
-rwxrwxr-x. 1 userone userone    0 Jul  2 15:12 stop
-rwxrwxr-x. 1 userone userone    0 Jul  2 15:12 start
drwxrwxr-x. 2 userone userone 4096 Jul  2 15:12 .

Step-6 : Once done lets commit the changes to git repository :

..
[userone@userone action_hooks]$ git commit -a -m "removing scripts"
[master e150ea0] removing scripts
2 files changed, 0 insertions(+), 9 deletions(-)

Step-7 : Lets push the changes to Openshift server now :

..
[userone@userone action_hooks]$ git push
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 471 bytes, done.
Total 4 (delta 1), reused 0 (delta 0)
remote: Stopping application...
remote: Done
remote: ~/git/tomcat.git ~/git/tomcat.git
remote: ~/git/tomcat.git
remote: Running .openshift/action_hooks/pre_build
remote: Running .openshift/action_hooks/build
remote: Running .openshift/action_hooks/deploy
remote: Starting application...
remote: Done
remote: Running .openshift/action_hooks/post_deploy
To ssh://420ne8xz7pq64949861a99ea941c8ab3@mytomcatapp-mydomain.rhcloud.com/~/git/tomcat.git/
67f5592..e150ea0  master -> master

Step-8 : Let us login to OpenShift server via ssh :

$ ssh 420ne8xz7pq64949861a99ea941c8ab3@mytomcatapp-mydomain.rhcloud.com

From you home directory navigate to : mytomcatapp/data/

$ cd mytomcatapp/data/

Make sure you do it, because on other directories you won’t have write permission.

Step-9 : Now lets download Apache-Tomcat server, directly on OpenShift :

..
[mytomcatapp-mydomain.rhcloud.com data]> wget http://apache.techartifact.com/mirror/tomcat/tomcat-7/v7.0.28/bin/apache-tomcat-7.0.28.tar.gz
--2012-07-02 05:51:42--  http://apache.techartifact.com/mirror/tomcat/tomcat-7/v7.0.28/bin/apache-tomcat-7.0.28.tar.gz
Resolving apache.techartifact.com... 101.153.143.60
Connecting to apache.techartifact.com|101.153.143.60|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7674156 (7.3M) [application/x-gzip]
Saving to: β€œapache-tomcat-7.0.28.tar.gz”

100%[==================================================================================================================================================================================================>] 7,674,156   60.5K/s   in 3m 5s

2012-07-02 05:54:48 (40.6 KB/s) - β€œapache-tomcat-7.0.28.tar.gz” saved [7674156/7674156]

Step-10 : unzip the downloaded file :

..
tar zxvf apache-tomcat-7.0.28.tar.gz
..

Step 11 : Once done remove “apache-tomcat-7.0.28.tar.gz” as it will unneccesarily consume disk space.

..
[mytomcatapp-mydomain.rhcloud.com data]> rm -f apache-tomcat-7.0.28.tar.gz
[mytomcatapp-mydomain.rhcloud.com data]> cd apache-tomcat-7.0.28/
[mytomcatapp-mydomain.rhcloud.com apache-tomcat-7.0.28]> ls -ltra
total 124
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jun 15 03:52 work
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jun 15 03:52 logs
drwxr-xr-x. 7 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jun 15 03:53 webapps
-rw-r--r--. 1 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3 15557 Jun 15 03:54 RUNNING.txt
-rw-r--r--. 1 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  8826 Jun 15 03:54 RELEASE-NOTES
-rw-r--r--. 1 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  1192 Jun 15 03:54 NOTICE
-rw-r--r--. 1 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3 56812 Jun 15 03:54 LICENSE
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jun 15 03:54 conf
drwxr-xr-x. 9 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jul  2 06:30 .
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jul  2 06:30 bin
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jul  2 06:30 lib
drwxr-xr-x. 2 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jul  2 06:30 temp
drwxr-x---. 3 420ne8xz7pq64949861a99ea941c8ab3 420ne8xz7pq64949861a99ea941c8ab3  4096 Jul  2 06:31 ..

Step-12 : Now navigate to tomcat’s “conf” directory and edit server.xml file as below :

<!--?xml version='1.0' encoding='utf-8'?-->
<!--   Licensed to the Apache Software Foundation (ASF) under one or more   contributor license agreements.  See the NOTICE file distributed with   this work for additional information regarding copyright ownership.   The ASF licenses this file to You under the Apache License, Version 2.0   (the "License"); you may not use this file except in compliance with   the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0   Unless required by applicable law or agreed to in writing, software   distributed under the License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the License for the specific language governing permissions and   limitations under the License. -->
<!-- Note:  A "Server" is not itself a "Container", so you may not      define subcomponents such as "Valves" at this level.      Documentation at /docs/config/server.html  -->

  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->

  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->

  <!-- Prevent memory leaks due to use of particular java/javax APIs-->

  <!-- Global JNDI resources        Documentation at /docs/jndi-resources-howto.html   -->

    <!-- Editable user database that can also be used by          UserDatabaseRealm to authenticate users     -->

  <!-- A "Service" is a collection of one or more "Connectors" that share        a single "Container" Note:  A "Service" is not itself a "Container",        so you may not define subcomponents such as "Valves" at this level.        Documentation at /docs/config/service.html    -->

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"         maxThreads="150" minSpareThreads="4" />
    -->

    <!-- A "Connector" represents an endpoint by which requests are received          and responses are returned. Documentation at :          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)          Java AJP  Connector: /docs/config/ajp.html          APR (HTTP/AJP) Connector: /docs/apr.html          Define a non-SSL HTTP/1.1 Connector on port 8080     -->

    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"                port="8080" protocol="HTTP/1.1"                connectionTimeout="20000"                redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443          This connector uses the JSSE configuration, when using APR, the          connector should be using the OpenSSL style configuration          described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"                maxThreads="150" scheme="https" secure="true"                clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->

    <!-- An Engine represents the entry point (within Catalina) that processes          every request.  The Engine implementation for Tomcat stand alone          analyzes the HTTP headers included with the request, and passes them          on to the appropriate Host (virtual host).          Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->

      <!--For clustering, please take a look at documentation at:           /docs/cluster-howto.html  (simple how to)           /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" />
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords            via a brute-force attack -->

        <!-- This Realm uses the UserDatabase configured in the global JNDI              resources under the key "UserDatabase".  Any edits              that are performed against this UserDatabase are immediately              available for use by the Realm.  -->

        <!-- SingleSignOn valve, share authentication between web applications              Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.              Documentation at: /docs/config/valve.html              Note: The pattern used is equivalent to using pattern="common" -->

Here the changes made are :

1. Server port is changed to 15005 :

<Server port="15005" shutdown="SHUTDOWN">

2. “address=”127.3.45.2” has been added to :

..
[mytomcatapp-mydomain.rhcloud.com conf]> env | grep -i internal
OPENSHIFT_INTERNAL_PORT=8080
OPENSHIFT_INTERNAL_IP=127.3.45.2

3. Changed the AJP connector port as well :

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="15009" protocol="AJP/1.3" redirectPort="8443" />

4. In “Engine name” default host has been changed :

<Engine name="Catalina" defaultHost="127.3.45.2">

5. In host name we will put:

<Host name="mytomcatapp-mydomain.rhcloud.com"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

which is our “application-namespace.rhcloud.com”

Note : OpenShift doesn’t allow allocating ports below 15000, except 8080 and that is by default.

Step-13 : Start tomcat server from bin directory using “startup.sh”

Step-14 : Navigate to the URL :

http://mytomcatapp-mydomain.rhcloud.com/

Step-15 : I know all would be interested to click on “Manager App” tab, but it will ask for credentials πŸ™‚

Edit “tomcat-users.xml” file inside tomcat’s conf directory as below :

..
<!--?xml version='1.0' encoding='utf-8'?-->
<!--   Licensed to the Apache Software Foundation (ASF) under one or more   contributor license agreements.  See the NOTICE file distributed with   this work for additional information regarding copyright ownership.   The ASF licenses this file to You under the Apache License, Version 2.0   (the "License"); you may not use this file except in compliance with   the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0   Unless required by applicable law or agreed to in writing, software   distributed under the License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the License for the specific language governing permissions and   limitations under the License. -->

<!--   NOTE:  By default, no user is included in the "manager-gui" role required   to operate the "/manager/html" web application.  If you wish to use this app,   you must define such a user - the username and password are arbitrary. -->
<!--
  NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
<!--
  <role rolename="tomcat" />
  <role rolename="role1" />
  <user username="tomcat" password="tomcat" roles="tomcat" />
  <user username="both" password="tomcat" roles="tomcat,role1" />
  <user username="role1" password="tomcat" roles="role1" />
-->

Here :

<role rolename="manager-gui"/>
<user username="tomcat" password="tomcat" roles="manager-gui"/>

provides us access to “Manager App“, from here you can manage your applications/jvm.

Regards,
Middleware Magic Team πŸ™‚


Expiring HttpSessions associated with a WebApp using JMX client in JBossAS7.1.1

Hi,

During various builds of JBoss AS7 the MBean access methodology was keep changing, even the JMX subsystem XSD “jboss-as-jmx_1_1.xsd” also changed a lot from JBossAS7.0 till JBossAS7.1.1 Final. So here we are going to see How can we access the HttpSessions associated with a particular webapplication deployed on JBoss with the help of MBeans Remotely & Programatically. Here are the following points which we will notice as part of this article:

Point-1). Listing and Expiring all the HttpSessions related to a particular WebApplication using JMX.

Point-2). Accessing MBeans using the JBoss Native Management port 9999 on JBoss AS7.1.1.Final.

Point-3). The jmx subsystem inside our JBoss configuration file like “standalone-full.xml” should look something like following:

        <subsystem xmlns="urn:jboss:domain:jmx:1.1">
            <show-model value="true"/>
             <remoting-connector  use-management-endpoint="true" />
        </subsystem>

Here If the value of “use-management-endpoint” is “true” then this connector will use the management endpoint, otherwise it will use the remoting subsystem endpoint.

Point-4). Here we will also need to make sure that we enable the following System Property in the JBoss Cofiguration file (standalone*.xml) So that JBoss will make the “jboss.web:type=Manager” access available for the remote JMX Clients.

    <system-properties>
        <property name="org.apache.tomcat.util.ENABLE_MODELER" value="true"/>
    </system-properties>

***NOTE***: If you will not add the above System property for your JBoss then JBoss will not expose some of the MBeans which are available as part of “jboss.web:type=*”

Expiring HttpSessions programatically Remotely/Locally

Step-1). After enabling the System property org.apache.tomcat.util.ENABLE_MODELER=true on your JBoss, Start your JBoss AS7.1.1 Final like following

     ./standalone.sh  -c standalone-full.xml

You can also start it in a particular Bind address as well.

Step-2). Write a Simple Class “JMXBasedHttpSessionManagement.java” inside “/home/userone/JmxDemo/” as following:

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.*;
import java.util.*;

public class JMXBasedHttpSessionManagement { 
    
    private String jbossHost;
    private int jbossMgmtPort;
    private MBeanServerConnection connection;
    private JMXConnector jmxConnector;

    public JMXBasedHttpSessionManagement(String jbossHost,int jbossMgmtPort)throws Exception
        {
          this.jbossMgmtPort=jbossMgmtPort;
          this.jbossHost=jbossHost;
          String urlString ="service:jmx:remoting-jmx://" + jbossHost + ":" + jbossMgmtPort;
          JMXServiceURL serviceURL = new JMXServiceURL(urlString);
          jmxConnector = JMXConnectorFactory.connect(serviceURL, null);
          connection = jmxConnector.getMBeanServerConnection();          
        }


    public void showSessionDetails(ObjectName objectName) throws Exception
        {
          System.out.println("nn********************* Details of "+objectName+" *********************");
          Integer sessionMaxAliveTime=(Integer)connection.getAttribute(objectName, "sessionMaxAliveTime");
          Integer maxInactiveInterval=(Integer)connection.getAttribute(objectName, "maxInactiveInterval");
          Integer activeSessions=(Integer)connection.getAttribute(objectName, "activeSessions");
          Integer sessionCounter=(Integer)connection.getAttribute(objectName, "sessionCounter");
          Integer sessionAverageAliveTime=(Integer)connection.getAttribute(objectName, "sessionAverageAliveTime");
          Long processingTime=(Long)connection.getAttribute(objectName, "processingTime");
          Integer sessionIdLength=(Integer)connection.getAttribute(objectName, "sessionIdLength");
          Integer maxActive=(Integer)connection.getAttribute(objectName, "maxActive");
          Integer maxActiveSessions=(Integer)connection.getAttribute(objectName, "maxActiveSessions");
          Integer expiredSessions=(Integer)connection.getAttribute(objectName, "expiredSessions");
          Integer rejectedSessions=(Integer)connection.getAttribute(objectName, "rejectedSessions");

          System.out.println("	maxInactiveInterval     = "+maxInactiveInterval);
          System.out.println("	activeSessions          = "+activeSessions);
          System.out.println("	sessionCounter          = "+sessionCounter);
          System.out.println("	sessionAverageAliveTime = "+sessionAverageAliveTime);
          System.out.println("	sessionAverageAliveTime = "+sessionAverageAliveTime);
          System.out.println("	processingTime          = "+processingTime);
          System.out.println("	sessionIdLength         = "+sessionIdLength);
          System.out.println("	maxActiveSessions       = "+maxActiveSessions);
          System.out.println("	maxActive               = "+maxActive);
          System.out.println("	expiredSessions         = "+expiredSessions);
        }

     // Following methd can be used to list all the HttpSessions associated with a particular web application.
    public void listSessionIds(ObjectName objectName) throws Exception
        {
          System.out.println("nn********************* JSESSIONID Details for "+objectName+" *********************");
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("Total Active HttpSessions: "+tokenizer.countTokens()+"n");
          int counter=0;
          while(tokenizer.hasMoreTokens())
             {
                System.out.println(++counter+"tt"+tokenizer.nextToken());
             }
         }

   
          //Following  method can be used to expire a Specific HttpSession associated with a particular Web Application. It requires that you should already have the JSESSIONID of the HttpSession which you want to expire.
     
    public void expireSession(ObjectName objectName, String jsessionId) throws Exception
        {
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("BEFORE expiration Total HttpSessions: "+tokenizer.countTokens());

          System.out.println("*** Expiring JSESSIONID " + jsessionId + " t"+objectName+" ***");
          connection.invoke(objectName,"expireSession", new String[]{jsessionId},  new String[]{"java.lang.String"});

          sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          tokenizer=new StringTokenizer(sessionIdList," ");
          System.out.println("*** AFTER expiration Total HttpSessions: "+tokenizer.countTokens());
         }
    
      // Following  method can be used to expire All the HttpSessions associated with a particular Web Application
    public void expireAllSession(ObjectName objectName) throws Exception
        {
          String sessionIdList=(String)connection.invoke(objectName,"listSessionIds", null, null);
          StringTokenizer tokenizer=new StringTokenizer(sessionIdList," ");

          int counter=0;
          while(tokenizer.hasMoreTokens())
             {
                String jsessionId=tokenizer.nextToken();
                connection.invoke(objectName,"expireSession", new String[]{jsessionId},  new String[]{"java.lang.String"});                
                System.out.println("t Expired Session "+ (++counter)  +"ttJSESSIONID= "+jsessionId);
             }
         }


    public static void main(String[] args) throws Exception {
        String jbossHost="localhost";
        int jbossMgmtPort=9999;
        String contextRootOfYourWebApp="Log4jDemo";

        JMXBasedHttpSessionManagement client=new JMXBasedHttpSessionManagement(jbossHost,jbossMgmtPort);
        ObjectName objectName=new ObjectName("jboss.web:type=Manager,path=/"+contextRootOfYourWebApp+",host=default-host");

        client.showSessionDetails(objectName);

        // EXAMPLE of ObjectName:    jboss.web:type=Manager,path=/Log4jDemo,host=default-host
        client.listSessionIds(objectName);

        // Call the following  method by passing a Specific HttpSession ID to expire it.
        //client.expireSession(objectName,"sFO2tCKf+-qPYZCkUHaia8Aa.undefined");

        // Call the following method to expire all the JSESSIONID s 
        System.out.println("nn*********************  Expiring All the HttpSession related to "+objectName);
        client.expireAllSession(objectName);

        client.listSessionIds(objectName);
        client.jmxConnector.close();
    }

}

***NOTE***: In the above program we are trying to access various attributes present inside the ObjectName “jboss.web:type=Manager,path=/Log4jDemo,host=default-host” where “Log4jDemo” is the Context-Root of My WebApplication which i wanted to monitor. And th edefault Host-Name is “default-host”, In your case these values might be different so better use the JConsole to connect to JBoss Locally and then get the exact Object name from it.

Step-3). Now oipen a Terminal where we need to set the PATh and CLASSPATH like following:

For UNIX Based Operating System:

export PATH=/home/userone/jdk1.6.0_21/bin:$PATH
export CLASSPATH=/home/userone/jboss-as-7.1.1.Final/bin/client/jboss-client.jar:$CLASSPATH:.:

++++++++++++++++++++++++++++++++
For Windows Based Operating System

set PATH=C:jdk1.6.0_21bin;%PATH%
set CLASSPATH=c:jboss-as-7.1.1.Finalbinclientjboss-client.jar;%CLASSPATH%;.;

***NOTE***: It is must that your JMX Client should include the “jboss-client.jar” in it’s classpath as above.

Step-4). Now compile and run the above program:

[userone@localhost JmxDemo]$ javac JMXBasedHttpSessionManagement.java 
[userone@localhost JmxDemo]$ java JMXBasedHttpSessionManagement 
May 20, 2012 12:20:01 PM org.xnio.Xnio <clinit>
INFO: XNIO Version 3.0.3.GA
May 20, 2012 12:20:01 PM org.xnio.nio.NioXnio <clinit>
INFO: XNIO NIO Implementation Version 3.0.3.GA
May 20, 2012 12:20:01 PM org.jboss.remoting3.EndpointImpl <clinit>
INFO: JBoss Remoting version 3.2.3.GA


********************* Details of jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
	maxInactiveInterval     = 1800
	activeSessions          = 4
	sessionCounter          = 133
	sessionAverageAliveTime = 1386
	sessionAverageAliveTime = 1386
	processingTime          = 59
	sessionIdLength         = 18
	maxActiveSessions       = -1
	maxActive               = 100
	expiredSessions         = 130


********************* JSESSIONID Details for jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
Total Active HttpSessions: 4

1		7paBncdqzoq1vXJHSB645jTB.undefined
2		Cy4QPyubiydfIrYD9A98B-Cs.undefined
3		6bdfUey9mXAA-y1tJo8xi508.undefined
4		U-57RR-B+bHhZicveBIYvhoq.undefined


*********************  Expiring All the HttpSession related to jboss.web:type=Manager,path=/Log4jDemo,host=default-host
	 Expired Session 1		JSESSIONID= 7paBncdqzoq1vXJHSB645jTB.undefined
	 Expired Session 2		JSESSIONID= Cy4QPyubiydfIrYD9A98B-Cs.undefined
	 Expired Session 3		JSESSIONID= 6bdfUey9mXAA-y1tJo8xi508.undefined
	 Expired Session 4		JSESSIONID= U-57RR-B+bHhZicveBIYvhoq.undefined


********************* JSESSIONID Details for jboss.web:type=Manager,path=/Log4jDemo,host=default-host *********************
Total Active HttpSessions: 0

.
.
Thanks πŸ™‚
Middleware Magic Team


Copyright Β© 2010-2012 Middleware Magic. All rights reserved. |